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.common.enums.PostInfoEnum;
import com.liang.common.utils.GetJsonIDUtil;
import com.liang.entity.*;
import com.liang.service.*;
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.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (PrjContract)表控制层
 *
 * @author makejava
 * @since 2023-06-30 09:30:26
 */
@Controller
@RequestMapping("prjContract")
public class PrjContractController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private PrjContractService prjContractService;
    @Resource
    private BaseProjecttypeService projecttypeService;
    @Resource
    private SysUserInfoService sysUserInfoService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private StaPayapprovalService staPayapprovalService;
    @Resource
    private PrjProjectService prjProjectService;

    @Resource
    private BasePersonService basePersonService;
    @Resource
    private PrjPayplanService prjPayplanService;


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

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

    /**
     * 列表初始化
     *
     * @return
     */
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        String userPostName = getSysUserInfo().getUserPostName();
        model.addAttribute("userId", getSysUserId());
        model.addAttribute("userPostName", userPostName);
        return "prjcontract/list";
    }

    /**
     * 页面初始化
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{id}", method = RequestMethod.GET)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @PathVariable(required = false) Integer id,
                           @RequestParam(required = false, defaultValue = "", value = "rws") String rws,
                           @RequestParam(required = false, defaultValue = "", value = "htmc") String htmc,
                           @RequestParam(required = false, defaultValue = "", value = "rwsmc") String rwsmc,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                           @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                           @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc,
                           @RequestParam(required = false, defaultValue = "", value = "erpbh")String erpbh,
                           @RequestParam(required = false, defaultValue = "", value = "cjr")String cjr,
                           @RequestParam(required = false, defaultValue = "", value = "kssj")String kssj,
                           @RequestParam(required = false, defaultValue = "", value = "jssj")String jssj) {
        List<SysUserInfo> lists = sysUserInfoService.getDept(id);
        String deptId = getSysUserInfo().getDeptId();
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("htmc", htmc);
        paraMap.put("rws", rws);
        paraMap.put("rwsmc", rwsmc);
        paraMap.put("cjr",cjr);
        paraMap.put("erpbh",erpbh);
        paraMap.put("spzt",spzt);
        paraMap.put("xmmc",xmmc);
        paraMap.put("kssj",kssj);
        paraMap.put("jssj",jssj);
        boolean containsKeyField = false;
        if (lists.size() > 0){
            for (int i = 0; i<lists.size();i++) {
                // 假设 obj 是一个包含字段的对象，例如 obj.getField() 是获取字段的方法
                if (lists.get(i).getUserPostName() == null){
                    continue;
                }
                if (lists.get(i).getUserPostName().contains("科技部部门主任") || lists.get(i).getUserPostName().contains("科研负责人")||lists.get(i).getUserPostName().contains("科技项目管理专责")) {
                    containsKeyField = true;
                    break;
                }
                if (lists.get(i).getAccount().contains("刘娇健") | lists.get(i).getAccount().contains("admin") ){
                    containsKeyField = true;
                    break;

                }
            }
            if(containsKeyField != true){
                paraMap.put("deptId",deptId);
            }
        }
        // 部门的可以查看本部门的 ，主任查看 本部门全部的
        List<PrjContract> list = prjContractService.getContractList(paraMap);

        PageInfo<PrjContract> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjContract> 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 = "/forAdd", method = RequestMethod.GET)
    public String forAdd() {
        return "prjcontract/add";
    }

    /**
     * 任务书
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/init_project", method = RequestMethod.GET)
    public String init_rws(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);

        return "prjcontract/list_project";
    }

    /**
     * 保存数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(PrjContract prjContract) {
        List<PrjContract> prjContractList =prjContractService.selectByMcAndHtjr(prjContract);
        if (prjContractList.size()==1){
            return BaseResult.failure("保存失败，系统已经存在相同的合同,创建人为"+prjContractList.get(0).getCjrxm()+"!!");
        }else if (prjContractList.size()>1){
            return BaseResult.failure("合同保存失败。当前创建的合同系统中已存在"+prjContractList.size()+"个相同合同，请联系系统管理员以解决此问题!!!");
        }
        prjContract.setCjr(getSysUserId());
        prjContract.setSpzt("未锁定");
        int num = prjContractService.insert(prjContract);
        if (num > 0) {
            return BaseResult.success("保存成功!", prjContract);
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        //当前项目
        PrjContract contract = prjContractService.queryById(id);
        PrjProject prjProject = prjProjectService.queryById(contract.getRws());
        List<PrjPayplan> payPlanList = prjPayplanService.getPayPlanList(id);
        for (int i = 0; i < payPlanList.size(); i++) {
            Integer id1 = payPlanList.get(i).getId();
            if (id1 != null) {
                List<StaPayapproval> list = staPayapprovalService.getFkjh(id1);
                payPlanList.get(i).setCountpay(list.size());
            }
        }

        String userPostName = getSysUserInfo().getUserPostName();
        model.addAttribute("rwsqssj",prjProject.getQs());
        model.addAttribute("rwswcsj",prjProject.getWc());
        model.addAttribute("dataFkjh",payPlanList);
        model.addAttribute("contract", contract);
        model.addAttribute("userPostName",userPostName);

        return "prjcontract/update";
    }
    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forXgUpdate/{id}", method = RequestMethod.GET)
    public String forXgUpdate(Model model, @PathVariable Integer id) {
        //当前项目
        PrjContract contract = prjContractService.queryById(id);
        List<PrjPayplan> payPlanList = prjPayplanService.getPayPlanList(id);
        for (int i = 0; i < payPlanList.size(); i++) {
            Integer id1 = payPlanList.get(i).getId();
            if (id1 != null) {
                List<StaPayapproval> list = staPayapprovalService.getFkjh(id1);
                payPlanList.get(i).setCountpay(list.size());
            }
        }

        model.addAttribute("payPlanList",payPlanList);
        model.addAttribute("contract", contract);
        model.addAttribute("htId",id);
        List<StaPayapproval> list =staPayapprovalService.queryByHtId(id);
        model.addAttribute("staPayapproval",list);
        return "prjcontract/xg_update";
    }

    /**
     * 更新数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(PrjContract prjContract) {
        int num = prjContractService.update(prjContract);
        //修改合同关联的付款金额
        staPayapprovalService.updateHtje(prjContract);
        if (num > 0) {
            return BaseResult.success("保存成功!", prjContract);
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 浏览数据
     *
     * @return
     */
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        //合同
        PrjContract contract = prjContractService.queryById(id);
        model.addAttribute("contract", contract);

        return "prjcontract/view";
    }

    /**
     * 批量删除
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data,
                                  @RequestParam(required = false,defaultValue = "",value = "Id")Integer id) {
        Map<String, Integer> maps = new HashMap<>();
        maps.put("id",id);
        maps.put("zt",0);
        int num = prjContractService.updateZt(maps);
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        }
        return BaseResult.failure("批量删除失败!");
    }

    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd", method = RequestMethod.GET)
    public String forApproveAdd(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        //部门主任岗位
        Map<String, String> paraMap = new HashMap<>();
        if (userInfo != null && userInfo.getDeptId().equals("52")) {
            paraMap.put("postName", "科技部部门主任");
        } else {
            paraMap.put("postName", "科研负责人");
        }
        SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap);
        if (postInfo == null)
            postInfo = new SysPostInfo();
        model.addAttribute("postInfo", postInfo);
        //系统当前用户
        model.addAttribute("userInfo", userInfo);

        return "prjcontract/add_approve";
    }

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    public BaseResult updateSpzt(@RequestBody String strData) {
        PrjContract prjContract = JsonTool.parseObject(strData, PrjContract.class);
    // 1.更新修改申请审批状态
        int num = prjContractService.updateSpzt(prjContract);
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据（提交审批）
     *
     * @return
     */
    @RequestMapping(value = "/forApproveUpdate/{xmid}", method = RequestMethod.GET)
    public String forApproveUpdate(Model model, @PathVariable Integer xmid, @RequestParam String spzt) {
        //系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);

        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid.toString());
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            model.addAttribute("approveInfo", approveList.get(0));
        }
        return "prjcontract/finish_approve";
    }

    /**
     * 审批列表
     *
     * @return
     */
    @RequestMapping(value = "/forApproveList", method = RequestMethod.GET)
    public String forApproveList() {
        return "prjcontract/list_approve";
    }


    /**
     * 获取电科院人员名单
     */
    @ResponseBody
    @RequestMapping(value = "/dkyfzr", method = RequestMethod.GET)
    public Object dkyfzr(@RequestParam("page") Integer pageNum,
                         @RequestParam("limit") Integer pageSize,
                         @RequestParam(required = false, defaultValue = "", value = "xm") String xm) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("xm", xm);
        List<BasePerson> list = basePersonService.getBasePersonList(paraMap);

        PageInfo<BasePerson> pageinfo = new PageInfo<>(list);
        // 取出查询结果
        List<BasePerson> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();

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

        return resultMap;
    }


    /**
     * 获取创建人
     * @param pageNum
     * @param pageSize
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cjr", method = RequestMethod.GET)
    public Object dwlist(@RequestParam("page") Integer pageNum,
                         @RequestParam("limit") Integer pageSize,
                         @RequestParam(required = false, defaultValue = "", value = "name") String name) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("name", name);
        List<SysUserInfo> list = sysUserInfoService.getSysUserInfoList(paraMap);

        PageInfo<SysUserInfo> pageinfo = new PageInfo<>(list);
        // 取出查询结果
        List<SysUserInfo> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();

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

        return resultMap;
    }




    @ResponseBody
    @RequestMapping(value = "getPayApply/{id}",method = RequestMethod.GET)
    public BaseResult getPayApply(@PathVariable Integer id){
         int num;
        List<StaPayapproval> list = staPayapprovalService.queryByHtId(id);
        if (list.isEmpty()){
            num = 0;
        }else {
            num = list.size();
        }
        return BaseResult.success(num);
    }

    /**
     * 导出接口
     */
    @ResponseBody
    @RequestMapping(value = "/getAllGL/{fromdata}",method = RequestMethod.POST)
    public BaseResult getAllGL(@PathVariable(required = false) String fromdata) throws  Exception{
        Map<String, Object> paraMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        PrjContract formDatas = objectMapper.readValue(fromdata, PrjContract.class);
        List<SysUserInfo> lists = sysUserInfoService.getDept(formDatas.getId());
        paraMap.put("htmc", formDatas.getHtmc());
        paraMap.put("rws", formDatas.getRws());
        paraMap.put("rwsmc", formDatas.getRwsmc());
        paraMap.put("cjr",formDatas.getCjr());
        paraMap.put("erpbh",formDatas.getErpbh());
        paraMap.put("spzt",formDatas.getSpzt());
        paraMap.put("xmmc",formDatas.getXmmc());
        paraMap.put("kssj",formDatas.getKssj());
        paraMap.put("jssj",formDatas.getJssj());
        boolean containsKeyField = false;
        if (lists.size() > 0){
            for (int i = 0; i<lists.size();i++) {
                // 假设 obj 是一个包含字段的对象，例如 obj.getField() 是获取字段的方法
                if (lists.get(i).getUserPostName() == null){
                    continue;
                }
                if (lists.get(i).getUserPostName().contains("科技部部门主任") || lists.get(i).getUserPostName().contains("科研负责人")||lists.get(i).getUserPostName().contains("科技项目管理专责")) {
                    containsKeyField = true;
                    break;
                }
                if (lists.get(i).getAccount().contains("刘娇健") | lists.get(i).getAccount().contains("admin") ){
                    containsKeyField = true;
                    break;

                }
            }
            if(containsKeyField != true){
                paraMap.put("id",formDatas.getId());
            }
        }
        List<PrjContract> list = prjContractService.getContractList(paraMap);
        return BaseResult.success("导出成功",list);
    }


    @ResponseBody
    @RequestMapping(value = "/getAll/{fromdata}",method = RequestMethod.POST)
    public BaseResult getAll(@PathVariable(required = false) String fromdata) throws  Exception{
        Map<String, Object> paraMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        PrjContract formDatas = objectMapper.readValue(fromdata, PrjContract.class);
        Date kssj = formDatas.getKssj();
        Date jssj = formDatas.getJssj();
        paraMap.put("htmc", formDatas.getHtmc());
        paraMap.put("rws", formDatas.getRws());
        paraMap.put("rwsmc", formDatas.getRwsmc());
        paraMap.put("cjr",formDatas.getCjr());
        paraMap.put("erpbh",formDatas.getErpbh());
        paraMap.put("spzt",formDatas.getSpzt());
        if (kssj != null) {
            paraMap.put("kssj", formDatas.getKssj().toString());
        }
        if (jssj !=null) {
            paraMap.put("jssj", formDatas.getJssj().toString());
        }
        List<PrjContract> list = prjContractService.getContractList(paraMap);
        return BaseResult.success("导出成功",list);

    }

}

