package com.liang.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseController;
import com.liang.common.base.BaseResult;
import com.liang.entity.*;
import com.liang.entity.baobiao.LsUtilEntity;
import com.liang.entity.baobiao.StaTempMemberDtile;
import com.liang.entity.baobiao.UtilEntity;
import com.liang.service.BaseEducationService;
import com.liang.service.LsUserService;
import com.liang.service.PrjAnnualbudgetService;
import com.liang.service.StaTempmemberService;
import io.swagger.annotations.ApiOperation;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目人员（主要完成人）(StaTempmember)表控制层
 *
 * @author makejava
 * @since 2023-07-03 15:44:54
 */
@Controller
@RequestMapping("staTempmember")
public class StaTempmemberController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaTempmemberService staTempmemberService;
    @Resource
    private BaseEducationService baseEducationService;

    @Resource
    private LsUserService lsUserService;

    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;

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

    /**
     * 临时人员
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{fysq}", method = RequestMethod.POST)
    public BaseResult list(@PathVariable Integer fysq,
                           @RequestParam(required = false, defaultValue = "", value = "qsrq") String qsrq,
                           @RequestParam(required = false, defaultValue = "", value = "jsrq") String jsrq)
    {

        Map<String, String> map = new HashMap<>();
        map.put("fysq", fysq.toString());
        map.put("qsrq", qsrq);
        map.put("jsrq", jsrq);
        List<StaTempmember> list = staTempmemberService.getMemberList(map);

        PageInfo<StaTempmember> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaTempmember> 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);
    }

    /**
     * 临时人员
     * @param zb
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/lslist/{zb}", method = RequestMethod.POST)
    public BaseResult lslist(@PathVariable Integer zb)
    {
        List<StaTempmember> list = staTempmemberService.getLSList(zb);

        PageInfo<StaTempmember> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaTempmember> 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
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model)
    {

        Map<String, String> map = new HashMap<>();
        map.put("zt","0");
        List<SysLsUserEntity> list = lsUserService.UserAll(map);
        model.addAttribute("list",list);

        return "tempmember/add";
    }

    /**
     * 新建临时人员
     * @param tempMember
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(StaTempmember tempMember) {

        int num = staTempmemberService.insert(tempMember);
        if (num > 0) {
            return BaseResult.success("项目人员保存成功！");
        } else if(num == -1) {
            return BaseResult.success("该项目人员已存在，如需修改，请选中后编辑！");
        }
        else {
            return BaseResult.success("项目人员保存失败！");
        }
    }
    public static void removeCommonElement(List<SysLsUserEntity> list1, List<SysLsUserEntity> list2) {
        // 创建列表的副本，以避免 ConcurrentModificationException
        List<SysLsUserEntity> copy1 = new ArrayList<>(list1);
        List<SysLsUserEntity> copy2 = new ArrayList<>(list2);

        // 从 list1 和 list2 中删除共有元素
        for (SysLsUserEntity item1 : copy1) {
            for (SysLsUserEntity item2 : copy2) {
                if (item1.getSfzh().equals(item2.getSfzh())) {
                    list1.remove(item1);
                    list2.remove(item2);
                    break; // 移除一个共有元素后退出内部循环
                }
            }
        }
    }

    /**
     * 批量保存临时人员
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchInsert/{zb}", method = RequestMethod.POST)
    public BaseResult batchInsert(@RequestBody String data, @PathVariable Integer zb)
    {

        StaTempMemberDtile staTempMemberDtile = new StaTempMemberDtile();
        // 查询数据库中项目 下所有临时人员
        List<SysLsUserEntity> list = lsUserService.getZb(zb);
        // 定义两个数组 一个存储共有的，一个存储没有的
        // 解析当前 Data 字符串 ，将字符串 转成 list<SysLsUserentity> 对象
        List<SysLsUserEntity> memberList = JsonTool.jsonToList(data, SysLsUserEntity.class);
        // 若当查询出的 list 与 传入 Data 解析的list 长度 为 1 则执行一下代码
        if (list.size() == 0 && memberList.size() == 1){
            Map<String, String> map = new HashMap<>();
            map.put("xm", memberList.get(0).getXm());
            List<SysLsUserEntity> list1 = lsUserService.getUserxm(map);
            list1.get(0).setZb(zb);
            list1.get(0).setZt(1);
            boolean a = lsUserService.upDate(list1.get(0));
            return BaseResult.success("临时人员保存成功");
        }

        // 删除已有元素
        if (list.size()>0){
            Map<String, Object> mapes = new HashMap<>();
            mapes.put("zb",zb);
            // 查询全部数据
            List<StaTempmember> list1 = staTempmemberService.getAlls(mapes);
            for (int i = 0 ;i<list1.size();i++){
                Map<String, Object> map = new HashMap<>();
                map.put("zt",0);
                map.put("id",list1.get(i).getId());
                int upst = lsUserService.upSt(map);
            }
        }
                if (memberList.size()>0){
                    for (int b = 0;b<memberList.size();b++){
                        Map<String, String> map = new HashMap<>();
                        map.put("xm",memberList.get(b).getXm());
                        map.put("sfzh",memberList.get(b).getSfzh());
                        List<SysLsUserEntity> list3= lsUserService.getUserxm(map);
                        if (list3.size() > 1){
                            return BaseResult.failure("临时人员保存失败，身份证号与人名重复！");
                        }
                        list3.get(0).setZb(zb);
                        list3.get(0).setZt(1);
                        boolean a = lsUserService.upDate(list3.get(0));
                        staTempMemberDtile.setZb(zb);
                        staTempMemberDtile.setFysqid(list3.get(0).getId());
                        staTempMemberDtile.setXmqssj(memberList.get(b).getXmqssj());
                        staTempMemberDtile.setXmjsrq(memberList.get(b).getXmjsrq());
                        int num = lsUserService.insert(staTempMemberDtile);
                    }
                    return BaseResult.success("临时人员保存成功");
                }
        return BaseResult.failure("临时人员保存失败");
    }

    @ApiOperation(value = "修改页面初始化", notes = "修改页面初始化")
    @RequestMapping(value = "/forUpdate", method = RequestMethod.GET)
    public String forUpdate(Model model) {
        //学历
        List<Map<String, String>> xlList = baseEducationService.getEducationList();
        model.addAttribute("xlList", xlList);
        return "tempmember/update";
    }

    @ApiOperation(value = "浏览页面初始化", notes = "浏览页面初始化")
    @RequestMapping(value = "/forView", method = RequestMethod.GET)
    public String forView(Model model)
    {
        //学历
        List<Map<String, String>> xlList = baseEducationService.getEducationList();
        model.addAttribute("xlList", xlList);
        return "tempmember/view";
    }

    @ResponseBody
    @RequestMapping(value = "/memberExist", method = RequestMethod.POST)
    public boolean memberExist(@RequestParam String xm, @RequestParam String qsrq, @RequestParam String jsrq)
    throws  Exception{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, String> maps = new HashMap<>();
        maps.put("xm",xm);
        StaTempmember tempmemberss = staTempmemberService.getTempMember(maps);
        // 判断 qsrq 与 jsrq 是否 在 聘用时间之内
        // 将String 类型 转换成 date 类型
        Date date1 = dateFormat.parse(qsrq);
        Date date2 = dateFormat.parse(jsrq);
        int comparison = date1.compareTo(date2);
        int com1 = tempmemberss.getQsrq().compareTo(date1);
        int com2 = tempmemberss.getJsrq().compareTo(date2);

        // 若 comparison > 0 则表示 date1 在 date2 之后
        if (comparison > 0){
            return false;
        }
        if (com1 > 0){
            return false;
        }
        if (com2 < 0){
            return false;
        }

        Map<String, String> map = new HashMap<>();
        map.put("xm", xm);
        map.put("xmqssj", qsrq);
        StaTempmember tempMembers = staTempmemberService.getXm(map);
        if (tempMembers == null){
            map.put("xmjsrq", jsrq);
            StaTempmember tempMember = staTempmemberService.getXm(map);
            return tempMember == null ? true : false;
        }

        return tempMembers == null ? true : false;
    }

    //项目报表（临时费用）页面
    @RequestMapping("/search")
    public String search(Model model){
        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);
        return "statistical/tempMember";
    }

    //临时费用全部及条件查询
    @ResponseBody
    @RequestMapping(value = "/searchData", method = RequestMethod.POST)
    public BaseResult searchData(@RequestParam(required = false, defaultValue = "", value = "XMMC") String xmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "ERPBH")String erpbh,
                                 @RequestParam(required = false, defaultValue = "", value = "FYSQBH")String fysqbh,
                                 @RequestParam(required = false, defaultValue = "", value = "QSRQ")String qsrq,
                                 @RequestParam(required = false, defaultValue = "", value = "JSRQ")String jsrq,
                                 @RequestParam(required = false, defaultValue = "", value = "XM")String xm,
                                 @RequestParam(required = false,defaultValue = "",value = "PYQSSJ") String pyqssj,
                                 @RequestParam(required = false,defaultValue = "",value = "PYDQSSJ")String pydqssj,
                                 @RequestParam(required = false,defaultValue = "",value = "NF")String nf,
                                 @RequestParam("page")Integer pageNum,
                                 @RequestParam("limit")Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("xmmc",xmmc);
        map.put("erpbh",erpbh);
        map.put("bh",fysqbh);
        map.put("qsrq",qsrq);
        map.put("jsrq",jsrq);
        map.put("xm",xm);
        map.put("pyqssj",pyqssj);
        map.put("pydqssj",pydqssj);
        map.put("nf",nf);
        List<HashMap<String,Object>> staFeasibilityreport = staTempmemberService.searchTemeMemberCost(map);
        PageInfo<HashMap<String,Object>> pageinfo = new PageInfo<>(staFeasibilityreport);
        List<HashMap<String,Object>> 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);
    }


    @ResponseBody
    @RequestMapping(value = "/getAll/{formDate}",method = RequestMethod.POST)
    public BaseResult getAll(@PathVariable(required = false)String formDate)throws Exception{
        Map<String, String> map = new HashMap<>();
        if (formDate.isEmpty()){
            List<HashMap<String,Object>> staFeasibilityreport = staTempmemberService.searchTemeMemberCost(map);
            return BaseResult.success(staFeasibilityreport);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        LsUtilEntity util = objectMapper.readValue(formDate, LsUtilEntity.class);

        map.put("xmmc",util.getXmmc());
        map.put("erpbh",util.getErpbh());
        map.put("bh",util.getFysqbh());
        map.put("qsrq",util.getQsrq());
        map.put("jsrq",util.getJsrq());
        map.put("xm",util.getXm());
        map.put("pyqssj",util.getPyqssj());
        map.put("pydqssj",util.getPYDQSSJ());
        map.put("nf",util.getNf());
        List<HashMap<String,Object>> staFeasibilityreport = staTempmemberService.searchTemeMemberCost(map);

        return BaseResult.success(staFeasibilityreport);
    }


}

