package com.liang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.base.BaseResult;
import com.liang.common.JsonTool;
import com.liang.common.annotation.LogAround;
import com.liang.common.base.BaseController;
import com.liang.entity.SysPostInfo;
import com.liang.service.SysDictInfoService;
import com.liang.service.SysPostInfoService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SysPostInfo)表控制层
 *
 * @author makejava
 * @since 2023-02-27 17:14:56
 */
@Controller
@RequestMapping("/sysPostinfo")
public class SysPostInfoController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private SysDictInfoService sysDictInfoService;

    final static Logger logger = LoggerFactory.getLogger(SysPostInfoController.class);

    /**
     * 分页查询
     *
     * @param sysPostInfo 筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<SysPostInfo>> queryByPage(SysPostInfo sysPostInfo, PageRequest pageRequest) {
        return ResponseEntity.ok(this.sysPostInfoService.queryByPage(sysPostInfo, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<SysPostInfo> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.sysPostInfoService.queryById(id));
    }

    /**
     * 岗位信息新增页面初始化
     *
     * @return
     */
    @ApiOperation(value = "岗位信息新增页面初始化", notes = "岗位信息新增页面初始化")
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> baseDictList = sysDictInfoService.queryByCode("postinfo_status");
        model.addAttribute("baseDictList", baseDictList);
        return "postinfo/add";
    }


    /**
     * 岗位信息新增
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult add(SysPostInfo postInfo) {
        // 增加判断 若是 存在 postName则不能新建，且岗位编码也不可以重复
        Map<String,Object> map = new HashMap<>();
        map.put("postName",postInfo.getPostName());
        List<SysPostInfo> list = sysPostInfoService.getPost(map);
        // 判断岗位名称（postName）是否存在
        if (list.size() > 0){
            return BaseResult.failure(1,"创建失败，岗位名称已存在！");
        }else {
            map.clear();
            map.put("postCode",postInfo.getPostCode());
            List<SysPostInfo> list1 = sysPostInfoService.getPost(map);
            // 判断岗位编码（postSort）是否存在
            if (list1.size()>0){
                return BaseResult.failure(1,"创建失败,岗位编码已存在！");
            }else {
                // 录入 创建人
                postInfo.setCreateUser(getSysUserId());
                int num = sysPostInfoService.insert(postInfo);
                if (num > 0) {
                    return BaseResult.success("新增岗位信息成功！");
                } else if (num == -1) {
                    return BaseResult.failure("该岗位已存在！");
                } else {
                    return BaseResult.failure("新增岗位信息，请联系后台管理员！");
                }
            }

        }
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{postId}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer postId) {
        // 获取下拉栏枚举值
        List<Map<String, String>> baseDictList = sysDictInfoService.queryByCode("postinfo_status");
        model.addAttribute("baseDictList", baseDictList);

        SysPostInfo postInfo = sysPostInfoService.queryById(postId);
        model.addAttribute("postInfo", postInfo);
        return "postinfo/update";
    }

    /**
     * 更新数据
     *
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult update(SysPostInfo postInfo) {
        Map<String,Object>map = new HashMap<>();
        map.put("postName",postInfo.getPostName());
        List<SysPostInfo> list = sysPostInfoService.getPost(map);
        if (list.size()>1){
            return BaseResult.failure(1,"修改失败，岗位名称已存在！");
        }else {
            map.clear();
            map.put("postCode",postInfo.getPostCode());
            List<SysPostInfo> list1 = sysPostInfoService.getPost(map);
            if (list1.size()>1){
                return BaseResult.failure(1,"修改失败，岗位编码已存在！");
            }else {
                postInfo.setUpdateUser(getSysUserId());
                int num = sysPostInfoService.update(postInfo);
                if (num > 0) {
                    return BaseResult.success("修改岗位信息成功！");
                } else if (num == -1) {
                    return BaseResult.failure("该岗位已存在！");
                } else {
                    return BaseResult.failure("修改岗位信息，请联系后台管理员！");
                }
            }
        }
    }

    /**
     * 查看数据
     *
     * @return
     */
    @RequestMapping(value = "/forView/{postId}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer postId) {
        // 获取下拉栏枚举值
        List<Map<String, String>> baseDictList = sysDictInfoService.queryByCode("postinfo_status");
        model.addAttribute("baseDictList", baseDictList);

        SysPostInfo postInfo = sysPostInfoService.queryById(postId);
        model.addAttribute("postInfo", postInfo);
        return "postinfo/view";
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.sysPostInfoService.deleteById(id));
    }


    /**
     * 岗位信息删除
     *
     * @return
     */
    @ApiOperation(value = "岗位信息删除", notes = "岗位信息删除")
    @RequestMapping(value = "/delete/{postId}/{postName}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult delete(@PathVariable Integer postId, @PathVariable String postName) {
        boolean flag = sysPostInfoService.deleteById(postId);
        if (flag) {
            return BaseResult.success("删除岗位信息'" + postName + "'成功！");
        } else {
            return BaseResult.failure("删除岗位信息失败，请联系后台管理员！");
        }
    }

    /**
     * 岗位管理页面初始化
     *
     * @return
     */
    @ApiOperation(value = "岗位管理页面初始化", notes = "岗位管页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> baseDictList = sysDictInfoService.queryByCode("postinfo_status");
        model.addAttribute("baseDictList", baseDictList);
        return "postinfo/list";
    }

    /**
     * 岗位数据分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @LogAround("岗位数据分页查询")
    @ApiOperation(value = "岗位数据分页查询", notes = "岗位数据分页查询")
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "postCode") String postCode,
                           @RequestParam(required = false, defaultValue = "", value = "postName") String postName,
                           @RequestParam(required = false, defaultValue = "", value = "status") String status,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("postCode", postCode);
        paraMap.put("postName", postName);
        paraMap.put("status", status);
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);

        List<SysPostInfo> postinfos = sysPostInfoService.getSysPostInfoList(paraMap);

        PageInfo<SysPostInfo> pageinfo = new PageInfo<>(postinfos);
        // 取出查询结果
        List<SysPostInfo> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    /**
     * 批量删除岗位
     *
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data) {
        if (logger.isInfoEnabled()) {
            logger.info("SysPostInfoController -- batchDelete -- data：{}", data);
        }
        List<Integer> postIdList = JsonTool.parseArray(data, Integer.class);
        int num = sysPostInfoService.batchDelete(postIdList);
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }

    /**
     * 岗位列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/postList", method = RequestMethod.GET)
    public Object postlist(@RequestParam(required = false, defaultValue = "", value = "postName") String postName) {
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("postName", postName);
        paraMap.put("status", "0");

        List<SysPostInfo> list = sysPostInfoService.getSysPostInfoList(paraMap);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        resultMap.put("count", list.size());
        resultMap.put("data", list);

        return resultMap;
    }
}

