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.exception.CustomException;
import com.liang.common.utils.ExcelPoiUtil;
import com.liang.dao.StaReimbursementDao;
import com.liang.entity.*;
import com.liang.service.*;
//import com.liang.vo.service.*;
import com.liang.vo.dto.ViewFileVo;
import io.swagger.annotations.ApiOperation;
import netscape.javascript.JSObject;
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.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 付款申请(StaPayapproval)表控制层
 *
 * @author makejava
 * @since 2023-06-05 16:03:47
 */
@Controller
@RequestMapping("staPayapproval")
public class StaPayapprovalController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaPayapprovalService staPayapprovalService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private PrjContractService prjContractService;
    @Resource
    private PrjPayplanService prjPayplanService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private StaBudgetapprovalService staBudgetapprovalService;
    @Resource
    private CyyService cyyService;
    @Resource
    private SysUserInfoService sysUserInfoService;


    @Resource
    private BaseProjecttypeService projecttypeService;


    @Resource
    private  PrjAnnualbudgetService prjAnnualbudgetService;


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

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

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


    @Resource
    private StaReimbursementDao staReimbursementDao;
    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("pay_status");
        model.addAttribute("approveList", approveList);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        //年份
        List<String> yearList = staReimbursementDao.getYears();
        model.addAttribute("yearList", yearList);

        return "payapply/list";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "fysqmc") String fysqmc,
                           @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                           @RequestParam(required = false, defaultValue = "", value = "cjr") String cjr,
                           @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                           @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                           @RequestParam(required = false, defaultValue = "", value = "cjsj1") String cjsj1,
                           @RequestParam(required = false, defaultValue = "", value = "cjsj2") String cjsj2,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                           @RequestParam(required = false, defaultValue = "", value = "rwsmc") String rwsmc,
                           @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                           @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc) {
        PageHelper.startPage(pageNum, pageSize);
        if (cjsj1 != "" && cjsj2 != "" && cjsj1.compareTo(cjsj2) > 0) {
            String cjsj = cjsj1;
            cjsj1 = cjsj2;
            cjsj2 = cjsj;
        }

        Map<String, String> paraMap = new HashMap<>();

        if (nf != null && !nf.isEmpty()){
            String[] nfs = nf.split(",");
            if (nfs.length>1){
                if (nfs[1].equals("0")){
                    paraMap.put("nf","");

                }else {
                    paraMap.put("nf", nfs[1]);
                }

            }else {
                paraMap.put("nf",nf);
            }
        }
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("fysqmc", fysqmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("bh", bh);
        paraMap.put("spzt", spzt);
        paraMap.put("cjsj1", cjsj1);
        paraMap.put("cjsj2", cjsj2);
        paraMap.put("cjr", cjr);
        paraMap.put("rwsmc", rwsmc);
        paraMap.put("xmmc",xmmc);

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

    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_payApply", method = RequestMethod.GET)
    public String init_payApply(Model model,
                                @RequestParam(required = false, defaultValue = "", value = "id") Integer id
                                ) {
//       获取当前报账的费用申请id
        String fysq=staReimbursementDao.getfysqmc(id);
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("pay_status");
        model.addAttribute("approveList", approveList);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        if (fysq!=null && fysq != ""){
        model.addAttribute("fysq",fysq);
        }

        //年份
        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);

        return "payapply/mylist";
    }

    /**
     * 我的付款申请
     */
    @ResponseBody
    @RequestMapping(value = "/mylist", method = RequestMethod.POST)
    public BaseResult mylist(@RequestParam("page") Integer pageNum,
                             @RequestParam("limit") Integer pageSize,
                             @RequestParam(required = false, defaultValue = "", value = "fysq") String fysq,
                             @RequestParam(required = false, defaultValue = "", value = "fysqmc") String fysqmc,
                             @RequestParam(required = false, defaultValue = "", value = "cjr") String cjr,
                             @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                             @RequestParam(required = false, defaultValue = "", value = "cjsj1") String cjsj1,
                             @RequestParam(required = false, defaultValue = "", value = "cjsj2") String cjsj2,
                             @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                             @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                             @RequestParam(required = false, defaultValue = "", value = "erpbh")String erpbh,
                             @RequestParam(required = false, defaultValue = "", value = "bh")String bh,
                             @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                             @RequestParam(required = false, defaultValue = "", value = "nf") String nf) {
        SysUserInfo userInfo = getSysUserInfo();
        List<String> postName = sysUserInfoService.getPostNameByUserId(userInfo.getUserId());
        String post = "";
        if (postName.size() > 0) {
            for (int i = 0; i < postName.size(); i++) {
                if (PostInfoEnum.KYZZ.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        if (cjsj1 != "" && cjsj2 != "" && cjsj1.compareTo(cjsj2) > 0) {
            String cjsj = cjsj1;
            cjsj1 = cjsj2;
            cjsj2 = cjsj;
        }

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("fysq",fysq);
        paraMap.put("fysqmc", fysqmc);
        paraMap.put("cjr", cjr);
        paraMap.put("spzt", spzt);
        paraMap.put("cjsj1", cjsj1);
        paraMap.put("cjsj2", cjsj2);
        paraMap.put("erpbh",erpbh);
        paraMap.put("bh",bh);
        paraMap.put("nf",nf);
        paraMap.put("xmmc",xmmc);

        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }
        }
        List<StaPayapproval> list = staPayapprovalService.getFksqList(paraMap);

        PageInfo<StaPayapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaPayapproval> 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/{fysq}", method = RequestMethod.GET)
    public String forAdd(Model model, @PathVariable Integer fysq) {
        Map<String, String> map = new HashMap<>();
        map.put("fysq", fysq.toString());
        List<PrjContract> htList = prjContractService.getContractList(map);
        model.addAttribute("htList", htList);
        StaPayapproval yfkje = staPayapprovalService.getYFKJE(fysq.toString());
        model.addAttribute("yfkje",yfkje);
        return "payapply/add";
    }
    @RequestMapping(value = "/forAdds", method = RequestMethod.GET)
    public String forAdds() {
        return "payapply/adds";
    }


    @RequestMapping(value = "/getHt",method = RequestMethod.POST)
    @ResponseBody
    public BaseResult getHt (@RequestParam("page") Integer pageNum,
                             @RequestParam("limit") Integer pageSize,
                             @RequestParam(required = false) String fysqid,
                             @RequestParam(required = false, defaultValue = "",value = "htmc") String htmc,
                             @RequestParam(required = false, defaultValue = "",value = "xmmc") String xmmc){
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("fysq", fysqid);
        map.put("htmc", htmc);
        map.put("xmmc",xmmc);
        List<PrjContract> list = prjContractService.getContractList(map);
        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);

    }


    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_project", method = RequestMethod.GET)
    public String init_rws(Model model) {

        return "payapply/list_projects";
    }

    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_projects/{htmc}", method = RequestMethod.GET)
    public String init_rwss(Model model,@PathVariable String htmc) {
        model.addAttribute("xmmc",htmc);
        return "payapply/list_projectes";
    }



    /**
     * 保存数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(StaPayapproval staPayapproval) {

        // 需要校验合同下有多少付款申请
        Map<Object,Object> map = new HashMap<>();
        map.put("nys",staPayapproval.getRws());
        map.put("fymc",staPayapproval.getFylbmc());
        // 获取项目总预算
        PrjAnnualbudget pr = prjAnnualbudgetService.queryById(staPayapproval.getRws());
        map.put("id",pr.getRws());
        List<PrjAnnualbudget> lists = staPayapprovalService.getXmzys(map);
        if (lists.size() != 1){
            return BaseResult.failure(-1,"项目汇总数据不唯一,请联系管理员!");
        }
        if (staPayapproval.getRws() != null){
            if (lists.get(0).getBzze() < (lists.get(0).getYfze() + (staPayapproval.getBcfkje() * 10000))){
                return BaseResult.failure(-1,"该付款总额已超出,该科目下报账总额,请先创建报账信息!");
            }
        }
        List<StaBudgetapproval> sb = staBudgetapprovalService.getFylb(map);
        if (sb.size() == 0){
            return BaseResult.failure(-1,"保存失败，该项目类型下无报账记录！请先提交报账记录");
        }
        for(int i = 0 ; i<sb.size();i++){
            if (sb.get(i).getBzje() > staPayapproval.getBcfkje()){
                staPayapproval.setFysq(sb.get(i).getId());
                break;
            }
        }
        java.util.Date cjsj = new java.util.Date(System.currentTimeMillis());
        staPayapproval.setCjr(getSysUserId());
        staPayapproval.setCjsj(cjsj);
        staPayapproval.setSpzt("未提交");
        staPayapproval.setSqmc(staPayapproval.getHtmc() + "/" + staPayapproval.getFysqmc());
        int num = staPayapprovalService.insert(staPayapproval);
        if (num > 0)
            return BaseResult.success("保存成功!", staPayapproval);
        else
            return BaseResult.failure("保存失败!");
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        StaPayapproval payapproval = staPayapprovalService.queryById(id);
        Double aDouble = staPayapprovalService.selectPayByFkjh(payapproval.getFkjh());
        payapproval.setYfkje(aDouble);
        model.addAttribute("payapproval", payapproval);

        Map<String, String> map1 = new HashMap<>();
        map1.put("rws", payapproval.getRws().toString());
        List<PrjContract> htList = prjContractService.getContractList(map1);
        model.addAttribute("htList", htList);

        Map<String, String> map2 = new HashMap<>();
        map2.put("ht", payapproval.getHt().toString());
        List<PrjPayplan> payplanList = prjPayplanService.getPayPlanList(payapproval.getHt());
        //添加判断 此付款计划是否已经被使用
        for (int i = 0; i < payplanList.size(); i++) {
            Double a = staPayapprovalService.selectPayByFkjh(payplanList.get(i).getId());
            if (a !=null){
            payplanList.get(i).setYfkje(a);
            }else {
                payplanList.get(i).setYfkje(0.0);
            }
        }
        model.addAttribute("payplanList", payplanList);

        return "payapply/update";
    }

    /**
     * 更新数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    @Transactional
    public BaseResult doUpdate(StaPayapproval staPayapproval,
                               @RequestParam(required = false,defaultValue = "",value = "id")Integer id) {
        staPayapproval.setSqmc(staPayapproval.getHtmc() + "/" + staPayapproval.getFysqmc());
        staPayapproval.setId(id);
        StaPayapproval sp = staPayapprovalService.queryById(staPayapproval.getId());
        Map<String,Integer> map = new HashMap<>();
        // 根据费用ID 查询xmid
        StaBudgetapproval st = staBudgetapprovalService.queryById(staPayapproval.getFysq());
        // 查询总预算
        if (st != null){
            map.put("id",st.getXmid());
            List<PrjAnnualbudget> list = staPayapprovalService.getXmzys(map);
            if (list.size() == 1){
                if (list.get(0).getBzze() > (list.get(0).getYfze() - (sp.getBcfkje()*10000) + (staPayapproval.getBcfkje()*10000))){
                    int num = staPayapprovalService.update(staPayapproval);
                    if (num > 0) {
                        return BaseResult.success("保存成功!", staPayapproval);
                    } else{
                        return BaseResult.failure("保存失败!");
                    }
                }else {
                    return BaseResult.failure(1,"该项目累计付款金额大于报账总额，请补充报账金额后再创建付款申请！");
                }
            }
        }
        return BaseResult.failure(1,"该项目数据汇总值不为一，请联系管理员！");
    }

    /**
     * 撤销数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/TJrevokeApprove", method = RequestMethod.POST)
    public BaseResult TJrevokeApprove(@RequestBody String data) {
        StaPayapproval fksq = JsonTool.parseObject(data, StaPayapproval.class);
        int num;
        int temp;
        num = staPayapprovalService.tjrevokeApprove(fksq);
        //修改审批列表里的状态为完成
        temp = prjApproverecordService.updateRevokeRecord(fksq.getId());
        //return BaseResult.success(num+"撤销成功!");
        if (num > 0 && temp > 0) {
            return BaseResult.success("撤销成功!");
        } else {
            return BaseResult.failure("撤销失败!");
        }
    }

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

        return "payapply/view";
    }

    /**
     * 批量删除
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data) {
        List<StaPayapproval> prjList = JsonTool.parseArray(data, StaPayapproval.class);
        List<Integer> idList = new ArrayList<>();
        List<Integer> htList = new ArrayList<>();
        List<Integer> jhList = new ArrayList<>();
        prjList.forEach(item -> {
            idList.add(item.getId());
            htList.add(item.getHt());
            jhList.add(item.getFkjh());
        });

        int num = staPayapprovalService.batchDelete(idList);
        if (num > 0) {
//            prjContractService.batchDelete(htList);
//            prjPayplanService.batchDelete(jhList);
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }

    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd", method = RequestMethod.GET)
    public String forApproveAdd(Model model) {
        //部门主任岗位
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("postName", PostInfoEnum.KJXMGLZZ2.postName());
        SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap);
        if (postInfo == null)
            postInfo = new SysPostInfo();
        model.addAttribute("postInfo", postInfo);

        //系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);

        return "payapply/add_approve";
    }

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    @Transactional
    public BaseResult updateSpzt(@RequestBody String strData) {
        StaPayapproval fksq = JsonTool.parseObject(strData, StaPayapproval.class);
        int num = staPayapprovalService.updateSpzt(fksq);
        if (fksq.getSpzt().equals("审批结束")){
//             第一笔付款结束后更新合同状态
            Map<String, Object>maps = new HashMap<>();
            maps.put("id",fksq.getHt());
            maps.put("spzt","已锁定");
            prjContractService.updateSpzt(maps);
        }
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据（提交审批）
     *
     * @return
     */
    @RequestMapping(value = "/forApproveUpdate/{xmid}/{htje}", method = RequestMethod.GET)
    public String forApproveUpdate(Model model, @PathVariable Integer xmid, @PathVariable Double htje, @RequestParam String spzt) {

        StaPayapproval payapproval = staPayapprovalService.queryById(xmid);
        model.addAttribute("payapproval", payapproval);

        //系统当前用户
        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));
        else {
            StaPayapproval approve = staPayapprovalService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(approve.getSqmc());
            approveInfo.setZt("数据不匹配");
            model.addAttribute("approveInfo", approveInfo);
        }
//        List<CyyEntriy> cyyList =cyyService.queryByAccount(String.valueOf(userInfo.getUserId()));
//        model.addAttribute("cyyList", cyyList);

        if (spzt.equals(PostInfoEnum.KJBBMZR.postName()+"审批")) {
            return "payapply/finish_approve";
        } else {
            Map<String, String> paraMap2 = new HashMap<>();
                if (spzt.equals(PostInfoEnum.KJXMGLZZ2.postName() + "审批"))
                paraMap2.put("postName", PostInfoEnum.KJBBMZR.postName());
            else
                paraMap2.put("postName", PostInfoEnum.KJXMGLZZ2.postName());

            SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap2);
            if (postInfo == null)
                postInfo = new SysPostInfo();
            model.addAttribute("postInfo", postInfo);

            if (spzt.contains("未提交"))
                return "payapply/back_approve";
            else
                return "payapply/update_approve";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/bathUpdate/{xmid}/{htje}", method = RequestMethod.GET)
    public Map<Object, Object> bathUpdate(@PathVariable Integer xmid, @PathVariable Double htje, @RequestParam String spzt) {
        Map<Object, Object> res = new HashMap<>();
        //系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        res.put("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) {
            PrjApproverecord approverecord = approveList.get(0);
            if ((PostInfoEnum.KJBBMZR.postName()+"审批").equals(spzt)) {
                approverecord.setSpcz("批量审批");
                approverecord.setYj("同意");
            } else {
                Map<String, String> paraMap2 = new HashMap<>();
                if ((PostInfoEnum.KJXMGLZZ2.postName() + "审批").equals(spzt)) {
                    paraMap2.put("postName", PostInfoEnum.KJBBMZR.postName());
                } else {
                    paraMap2.put("postName", PostInfoEnum.KJXMGLZZ2.postName());
                }

                SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap2);

                if (postInfo == null) {
                    throw new CustomException("没有改岗位");
                }
                Map<String, String> paraMap = new HashMap<>();
                paraMap.put("postId", String.valueOf(postInfo.getPostId()));
                paraMap.put("deptName", String.valueOf(userInfo.getDeptName()));
                List<SysUserPost> list = sysUserPostService.getPostUserList(paraMap);
                approverecord.setSpcz("批量审批");
                approverecord.setYj("同意");
                approverecord.setSjshgw(postInfo.getPostId());
                approverecord.setSjshgwmc(postInfo.getPostName());
                approverecord.setSjshr(list.get(0).getUserId());
                approverecord.setSjshrxm(list.get(0).getName());

            }
            res.put("approveInfo", approverecord);
        } else {
            StaPayapproval approve = staPayapprovalService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(approve.getSqmc());
            approveInfo.setZt("数据不匹配");
            res.put("approveInfo", approveInfo);
            throw new CustomException("数据异常");
        }


        return res;
    }

    @Resource
    private SysUserPostService sysUserPostService;


    //初始化下拉
    @RequestMapping(value = "/init_cyy/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public List<CyyEntriy> init_cyy(Model model, @PathVariable Integer userId) {
        List<CyyEntriy> cyyList = cyyService.queryByAccount(String.valueOf(userId));
        return cyyList;
    }

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

    /**
     * 导出列表到excel
     *
     * @param response
     */
    @ApiOperation(value = "导出全部数据到excel", notes = "导出全部数据到excel")
    @RequestMapping(value = "/exportExcel/{fromdata}", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletResponse response,@PathVariable(required = false)String fromdata)throws Exception {
        HashMap<String, Object> paraMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        StaPayapproval fromData = objectMapper.readValue(fromdata,StaPayapproval.class);
        if (fromData.getNf().equals("0")){
            paraMap.put("nf","");
            }else {
                paraMap.put("nf",fromData.getNf());
            }
        paraMap.put("fysqmc", fromData.getFysqmc());
        paraMap.put("erpbh", fromData.getErpbh());
        paraMap.put("bh", fromData.getBh());
        paraMap.put("spzt", fromData.getSpzt());
        paraMap.put("cjsj1", fromData.getCjsj1());
        paraMap.put("cjsj2", fromData.getCjsj2());
        paraMap.put("cjr", fromData.getCjr());
        paraMap.put("rwsmc", fromData.getRwsmc());
        paraMap.put("xmmc", fromData.getXmmc());
        List<StaPayapproval> payapprovalList = staPayapprovalService.getFksqList(paraMap);
        List<String> listName = Arrays.asList("审批状态","项目名称","科研编号","ERP编号","合同", "合同金额(万元)","本次付款金额(万元)", "付款计划", "创建人", "创建时间","费用申请名称");
        List<Map<String, String>> list = new ArrayList<>();
        for (StaPayapproval payapproval : payapprovalList) {
            Map<String, String> map = new HashMap<>();
            map.put("审批状态", payapproval.getSpzt());
            map.put("项目名称",payapproval.getXmmc());
            map.put("科研编号",payapproval.getBh());
            map.put("ERP编号",payapproval.getErpbh());
            map.put("合同", payapproval.getHtmc());
            if (payapproval.getHtje() == null){
                map.put("合同金额(万元)", "0.0");
            }else {
                map.put("合同金额(万元)", payapproval.getHtje().toString());
            }
            if (payapproval.getBcfkje() == null){
                map.put("本次付款金额(万元)", "0.0");
            }else {
                map.put("本次付款金额(万元)", payapproval.getBcfkje().toString());
            }
            map.put("付款计划", payapproval.getFkjhmc());
            map.put("创建人", payapproval.getCjrxm());
            Date cjsjUtil = payapproval.getCjsj();
            java.sql.Date cjsj = new java.sql.Date(cjsjUtil.getTime());
            map.put("创建时间", cjsj.toString());
            map.put("费用申请名称", payapproval.getFysqmc());
            list.add(map);
        }

        ExcelPoiUtil.excelPort("付款", listName, list, null, response);
    }

    @RequestMapping(value = "/getYFKJE/{fysq}",method = RequestMethod.POST)
    @ResponseBody
    public StaPayapproval getYFKJE(@PathVariable String fysq){
        //获取该费用申请的报账金额和付款已申请金额
        StaPayapproval staPayapproval =staPayapprovalService.getYFKJE(fysq);

        return staPayapproval;
    }

    @RequestMapping(value = "/getZf",method = RequestMethod.POST)
    @ResponseBody
    public BaseResult getZf(
            @RequestParam(required = false, defaultValue = "",value = "id") Integer id) {
       StaPayapproval staPayapproval =  staPayapprovalService.queryById(id);
       staPayapproval.setSpzt("作废");
       int mun = staPayapprovalService.update(staPayapproval);
       if (mun <=  0){
         return   BaseResult.failure("'"+staPayapproval.getFkjh()+"'"+"该笔付款计划作废失败！");
       }
        return  BaseResult.success("该笔付款计划作废成功 ");
    }

    // 批量查看

    @RequestMapping(value = "/Viewfile", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult viewFile(@RequestBody String data) {
        // json 解析
        StaPayapproval staPayapproval = JsonTool.parseObject(data,StaPayapproval.class);
        PrjContract prjContract = prjContractService.queryById(staPayapproval.getId());
        if (staPayapproval.getType().equals("ht") && !prjContract.getWj().equals("[]")){
                List<ViewFileVo> vo = staPayapprovalService.viewfile(prjContract.getWj());
                return BaseResult.success(vo);
        }
        if (staPayapproval.getType().equals("ys") && !prjContract.getYszl().equals("[]")){
                List<ViewFileVo> vo = staPayapprovalService.viewfile(prjContract.getYszl());
                return BaseResult.success(vo);
                    }
        return BaseResult.failure(-1,"暂无可查看文件！");

    }


    @RequestMapping(value = "/getXmNd",method = RequestMethod.POST)
    @ResponseBody
    public BaseResult getXmNd(@RequestParam("page") Integer pageNum,
                              @RequestParam("limit") Integer pageSize,
                              @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                              @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh){
        // 获取当前账号部门ID
        int id = getSysUserId();
        SysUserInfo sysUserInfo = sysUserInfoService.queryById(id);
        PageHelper.startPage(pageNum, pageSize);
        Map<String,String> hashmap = new HashMap<>();
        hashmap.put("xmmc",xmmc);
        hashmap.put("erpbh",erpbh);
        hashmap.put("ssbm",sysUserInfo.getDeptId());
        List<PrjAnnualbudget> list = staPayapprovalService.getNdfk(hashmap);
        PageInfo<PrjAnnualbudget> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjAnnualbudget> 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);

    }
}

