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.enums.ProjectTypeEnnum;
import com.liang.common.exception.CustomException;
import com.liang.common.utils.time;
import com.liang.dao.PrjProjectDao;
import com.liang.entity.*;
import com.liang.service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
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 java.text.SimpleDateFormat;
import java.time.Period;
import java.util.*;

/**
 * (StaBudgetapproval)表控制层
 *
 * @author makejava
 * @since 2023-04-14 10:54:58
 */
@Controller
@RequestMapping("staBudgetapproval")
public class StaBudgetapprovalController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaBudgetapprovalService staBudgetapprovalService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private BaseProjecttypeService projecttypeService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private PrjProjectService prjProjectService;
    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;
    @Resource
    private PrjAnnualbudgetdetailService prjAnnualbudgetdetailService;
    @Resource
    private CyyService cyyService;
    @Resource
    private SysUserInfoService sysUserInfoService;
    @Resource
    private  SysUserPostService sysUserPostService;
    @Resource
    private  SysDeptInfoService sysDeptInfoService;
    @Resource
    private StaSourceFeeService staSourceFeeService;


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

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

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

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_apply", method = RequestMethod.GET)
    public String init_apply(Model model) {
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("approve_status");
        model.addAttribute("approveList", approveList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());

        //费用类别
        List<String> xmlx = staBudgetapprovalService.getXmlx();
        model.addAttribute("fylb", xmlx);

        return "stabudgetapproval/list_apply";
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel/{fromdata}", method = RequestMethod.POST)
    public BaseResult exportExcel(@PathVariable(required = false) String fromdata)throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        StaBudgetapprovals formData = objectMapper.readValue(fromdata, StaBudgetapprovals.class);

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("xmmc",formData.getXmmc());
        paraMap.put("erpbh", formData.getErpbh());
        paraMap.put("bh", formData.getBh());
        if (formData.getNf().equals("0")){
            paraMap.put("nf","");
        }else {
            paraMap.put("nf",formData.getNf());
        }
        paraMap.put("spzt", formData.getSpzt());
        paraMap.put("ssbmmc",formData.getSsbmmc());
        paraMap.put("xmlx", formData.getXmlx());

        paraMap.put("sqmc", formData.getSqmc());

        paraMap.put("sqr", formData.getSqr());
        paraMap.put("fylb", formData.getFylb());

        paraMap.put("dkyfzr",formData.getDkyfzr());
        paraMap.put("bzid","0");

        List<StaBudgetapproval> list = staBudgetapprovalService.getFysqList(paraMap);

        return BaseResult.success("导出完成！",list);
    }
    @ResponseBody
    @RequestMapping(value = "/exportExcelBYJ/{fromdata}", method = RequestMethod.POST)
    public BaseResult exportExcelBYJ(@PathVariable(required = false) String fromdata)throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        StaBudgetapprovals formData = objectMapper.readValue(fromdata, StaBudgetapprovals.class);

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("xmmc",formData.getXmmc());
        paraMap.put("erpbh", formData.getErpbh());
        paraMap.put("bh", formData.getBh());
        if (formData.getNf().equals("0")){
            paraMap.put("nf","");
        }else {
            paraMap.put("nf",formData.getNf());
        }
        paraMap.put("spzt", formData.getSpzt());
        paraMap.put("ssbmmc",formData.getSsbmmc());
        paraMap.put("xmlx", formData.getXmlx());

        paraMap.put("sqmc", formData.getSqmc());

        paraMap.put("sqr", formData.getSqr());
        paraMap.put("fylb", formData.getFylb());

        paraMap.put("dkyfzr",formData.getDkyfzr());
        paraMap.put("sfbyj",1);

        List<StaBudgetapproval> list = staBudgetapprovalService.getFysqList(paraMap);

        return BaseResult.success("导出完成！",list);
    }

    /**
     * 费用申请列
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_apply", method = RequestMethod.POST)
    public BaseResult list_apply(@RequestParam("page") Integer pageNum,
                                 @RequestParam("limit") Integer pageSize,
                                 @RequestParam(required = false, defaultValue = "", value = "sqmc") String sqmc,
                                 @RequestParam(required = false, defaultValue = "", value = "fylb") String fylb,
                                 @RequestParam(required = false, defaultValue = "", value = "sqr") String sqr,
                                 @RequestParam(required = false, defaultValue = "", value = "sfbyj") String sfbyj,
                                 @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                 @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                 @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                 @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                 @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "dkyfzr") String dkyfzr,
                                 @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                 @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                 @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                                 @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "bzid")String bzid) {
        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))||PostInfoEnum.KYFZR.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        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 {
                if (nfs[0].equals("0")){
                    paraMap.put("nf","");
                }else{
                    paraMap.put("nf",nf);
                }
            }
        }

        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("sqmc", sqmc);
        paraMap.put("sqr", sqr);
        paraMap.put("fylb", fylb);
        paraMap.put("erpbh", erpbh);
        paraMap.put("spzt", spzt);
        paraMap.put("bh", bh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("ssbmmc", ssbmmc);
        paraMap.put("dkyfzr", dkyfzr);
        paraMap.put("xmmc",xmmc);
        paraMap.put("bzid",bzid);
        paraMap.put("sfbyj",sfbyj);

        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }else {
                if (userInfo.getDeptName().contains("电源")){
                    paraMap.put("deptName","电源技术中心");
                }else {
                    paraMap.put("deptName", userInfo.getDeptName());
                }
            }
        }
        List<StaBudgetapproval> list = staBudgetapprovalService.getFysqList(paraMap);

        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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 = "/forApplyAdd", method = RequestMethod.GET)
    public String forApplyAdd(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);
        return "annualbudget/add_apply";
    }
    /**
     * 新建数据(费用申请页面)
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        String deptName = userInfo.getDeptName();
        //获取该部门下已申请的书籍
        List<StaSourceFee> TsmcList = staSourceFeeService.searchSourceTsmcByDeptName(deptName);
        List list = new ArrayList();
        for (int i = 0; i < TsmcList.size(); i++) {
            list.add(TsmcList.get(i).getTsmc());
        }
        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ClfTemplate", fileUrl + "差旅费模版.xlsx");
        model.addAttribute("HyfTemplate", fileUrl + "会议费模版.xlsx");
        model.addAttribute("ZlfTemplate", fileUrl + "资料费模版.xlsx");
        model.addAttribute("ZscqfTemplate", fileUrl + "知识产权费模版.xlsx");
        model.addAttribute("YsfTemplate", fileUrl + "印刷费模版.xlsx");
        model.addAttribute("JjfTemplate", fileUrl + "间接费模版.xlsx");
        model.addAttribute("ZjfTemplate", fileUrl + "专家费模版.xlsx");
        model.addAttribute("LsryTemplate", fileUrl + "临时人员模版.xlsx");
        model.addAttribute("DevTemplate", fileUrl + "仪器设备使用费模版.xlsx");
        model.addAttribute("RjsyfTemplate", fileUrl + "软件使用费模版.xlsx");
        model.addAttribute("CLfTemplate", fileUrl + "材料费模版.xlsx");
        model.addAttribute("WwTemplate", fileUrl + "外委研究支出费模版.xlsx");
        model.addAttribute("WxTemplate", fileUrl + "外协测试试验与加工费模版.xlsx");
        model.addAttribute("userInfo", userInfo);
        model.addAttribute("tsmclist",list);
        return "stabudgetapproval/add";
    }

    @RequestMapping(value = "/init_prjAnnualbudget", method = RequestMethod.GET)
    public String init_prjAnnualbudget(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);

        return "stabudgetapproval/list_annualbudget";
    }

    /**
     * 保存数据（费用申请）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAddApply", method = RequestMethod.POST)
    public BaseResult doAddApply(StaBudgetapproval budgetapproval) {
        Integer a = 0;
        Map<String, Integer> paraMap = new HashMap<>();
        // 获取当前操作人信息
        SysUserInfo user = getSysUserInfo();
        // 获取岗位信息
        paraMap.put("id",user.getUserId());
        // 获取备注信息
        String sys = sysUserInfoService.getBzs(1);
        List<SysUserInfo> accounts = sysUserInfoService.getSysUserInfoList(paraMap);
        if (accounts.size() >0){
            for (int i = 0;i<accounts.size();i++){
                if (!sys.isEmpty()){
                    if (accounts.get(i).getUserPostName().equals("科研专责")){
                        PrjProject project = prjProjectDao.queryById(budgetapproval.getXmid());
                        if(project != null){
                            budgetapproval.setSqrxm(getSysUserInfo().getName());
                            budgetapproval.setSqr(getSysUserId());
                            budgetapproval.setSfth(0);
                            budgetapproval.setSfbz(false);
                            budgetapproval.setSsbm(project.getSsbm());
                            budgetapproval.setSsbmmc(project.getSsbmmc());
                            budgetapproval.setErpbh(project.getErpbh());
                            budgetapproval.setXmlx(project.getXmlx());
                            budgetapproval.setXmlxmc(project.getXmlxmc());
                            budgetapproval.setDkyfzr(String.valueOf(project.getDkyfzr()));
                            int num = staBudgetapprovalService.insert(budgetapproval);
                            if (num > 0) {
                                a = 0;
                                break;
                            }

                        }else {
                            return BaseResult.failure(-1,"项目数据为空，费用申请失败！");
                        }
                    }
                }else {
                        PrjProject project = prjProjectDao.queryById(budgetapproval.getXmid());
                        if(project != null){
                            budgetapproval.setSqrxm(getSysUserInfo().getName());
                            budgetapproval.setSqr(getSysUserId());
                            budgetapproval.setSfth(0);
                            budgetapproval.setSfbz(false);
                            budgetapproval.setSsbm(project.getSsbm());
                            budgetapproval.setSsbmmc(project.getSsbmmc());
                            budgetapproval.setErpbh(project.getErpbh());
                            budgetapproval.setXmlx(project.getXmlx());
                            budgetapproval.setXmlxmc(project.getXmlxmc());
                            budgetapproval.setDkyfzr(String.valueOf(project.getDkyfzr()));
                            int num = staBudgetapprovalService.insert(budgetapproval);
                            if (num > 0) {
                                a = 0;
                                break;
                            }
                        }else {
                            return BaseResult.failure(-1,"项目数据为空，费用申请失败！");
                        }
                    }
                a++;
            }
        }
        // 返回为查询出数据
        if (a == accounts.size()){
            return BaseResult.failure(1,sys);
        }else {
            return BaseResult.success("费用申请成功!", budgetapproval);
        }
    }

    /**
     * 保存数据（备用金）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAddImprest", method = RequestMethod.POST)
    public BaseResult doAddImprest(StaBudgetapproval budgetapproval) {
        budgetapproval.setSqrxm(getSysUserInfo().getName());
        budgetapproval.setSqr(getSysUserId());
        int num = staBudgetapprovalService.insertImprest(budgetapproval);
        if (num > 0) {
            return BaseResult.success("备用金申请成功!", budgetapproval);
        } else {
            return BaseResult.failure("备用金申请失败!");
        }
    }

    /**
     * 编辑数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/TJrevokeApprove", method = RequestMethod.POST)
    @Transactional
    public BaseResult TJrevokeApprove(@RequestBody String data) {
        StaBudgetapproval fysq = JsonTool.parseObject(data, StaBudgetapproval.class);
        SysUserInfo userInfo = getSysUserInfo();
        int num;
        int temp;
        String spzt = fysq.getSpzt();
        switch (spzt) {
            case "主管院领导审批":
                fysq.setSpzt("科技部部门主任审批");
                break;
            case "科技部部门主任审批":
                fysq.setSpzt("科技项目管理专责审批");
                break;
            case "科技项目管理专责审批":
                fysq.setSpzt("部门主任审批");
                break;
            case "部门主任审批":
                fysq.setSpzt("未提交");
                break;
        }
//        修改为撤销后的审批状态
        num = staBudgetapprovalService.updateSpzt(fysq);

        Map<String, String> paraMap2 = new HashMap<>();
        paraMap2.put("deptName",userInfo.getDeptName());
        if (spzt.equals("科技项目管理专责审批")){
            if (userInfo != null && userInfo.getDeptId().equals("52")) {
                paraMap2.put("postName", "科技部部门主任");
                paraMap2.put("postId","16");
            } else {
                paraMap2.put("postName", "科研负责人");
                paraMap2.put("postId","28");
            }
    }else if (spzt.equals("科技部部门主任审批")){
            paraMap2.put("postName", "科技项目管理专责");
            paraMap2.put("postId","39");
    }else if (spzt.equals("主管院领导审批")) {
            paraMap2.put("postName", "科技部部门主任");
            paraMap2.put("postId","16");
    }else {
            paraMap2.put("postName",null);
    }
//  获取当前费用申请申请人的所属部门名称
        if(paraMap2.get("postId")=="28"){
            Integer sqr = fysq.getSqr();
            String deptName=sysDeptInfoService.getUserDept(sqr);
            if(deptName.contains("电源")){
                deptName = null;
            }
            paraMap2.put("deptName",deptName);
        }
//修改审批列表里的状态为完成
        temp = prjApproverecordService.updateRevokeRecord(fysq.getId());
        if (paraMap2.get("postName")!=null){
//            获取默认审批人
            List<SysUserPost> userPostList = sysUserPostService.getPostUserList(paraMap2);
            Integer shr = userPostList.get(0).getUserId();
            PrjApproverecord record = prjApproverecordService.getOldApproveRecord(fysq.getId());
            List<PrjApproverecord> recordList= new ArrayList<>();
//        审批列表中插入撤销后的审批流程
            PrjApproverecord record1 =new PrjApproverecord();
            record1.setTablename(record.getTablename());
            record1.setXm(record.getXm());
            record1.setXmid(record.getXmid());
            record1.setZt(fysq.getSpzt());
            record1.setTjr(record.getTjr());
            record1.setTjsj(record.getTjsj());
            record1.setShr(shr);
            record1.setSfsjsh(true);//是否需要上级审核
            record1.setSjshr(record.getShr());
            record1.setSjshgw(record.getShgw());//上级审核岗位
            record1.setSffh(false);//是否返回
            record1.setYcshr(false);//隐藏审核人
            record1.setWc(false);//完成
            recordList.add(record1);

            if (!fysq.getSpzt().equals("未提交")){
                prjApproverecordService.insertBatch(recordList);
            }
            if (num > 0 && temp > 0) {
                return BaseResult.success("撤销成功!");
            } else {
                return BaseResult.failure("撤销失败!");
            }
        }else {
            return BaseResult.success("撤销成功！");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/ThApproval", method = RequestMethod.POST)
    public BaseResult ThApproval(@RequestBody String data) {
        StaBudgetapproval fysq = JsonTool.parseObject(data, StaBudgetapproval.class);

        int num;
        int temp;
        num = staBudgetapprovalService.tjrevokeApprove(fysq);
//修改审批列表里的状态为完成
        temp = prjApproverecordService.updateRevokeRecord(fysq.getId());
//return BaseResult.success(num+"撤销成功!");
        if (num > 0 && temp > 0) {
            return BaseResult.success("撤销成功!");
        } else {
            return BaseResult.failure("撤销失败!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/bathUpdate/{xmid}/{sqje}", method = RequestMethod.GET)
    @Transactional
    public Map<Object, Object> bathUpdate(@PathVariable Integer xmid, @PathVariable Double sqje, @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() == 1) {
            PrjApproverecord approveInfo = approveList.get(0);
            approveInfo.setSqje(sqje);

            if (spzt.equals(PostInfoEnum.YZ.postName() + "审批") || spzt.equals(PostInfoEnum.ZGYLD.postName() + "审批") && sqje < 1000000) {
                approveInfo.setSpcz("批量审批");
                approveInfo.setYj("通过");
            } else {
                //岗位
                Map<String, String> paraMap2 = new HashMap<>();
                if ((PostInfoEnum.BMZR.postName() + "审批").equals(spzt)) {
                    paraMap2.put("postName", PostInfoEnum.KJXMGLZZ.postName());
                } else if ((PostInfoEnum.KJXMGLZZ.postName() + "审批").equals(spzt)) {
                    paraMap2.put("postName", PostInfoEnum.KJBBMZR.postName());
                } else if ((PostInfoEnum.KJBBMZR.postName() + "审批").equals(spzt)) {
                    paraMap2.put("postName", PostInfoEnum.ZGYLD.postName());
                } else if ((PostInfoEnum.ZGYLD.postName() + "审批").equals(spzt)) {
                    paraMap2.put("postName", PostInfoEnum.YZ.postName());
                } else {
                    paraMap2.put("postName", PostInfoEnum.BMZR.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);
                approveInfo.setSpcz("批量审批");
                approveInfo.setSjshgw(postInfo.getPostId());
                approveInfo.setSjshgwmc(postInfo.getPostName());
                approveInfo.setSjshr(list.get(0).getUserId());
                approveInfo.setSjshrxm(list.get(0).getName());
                approveInfo.setYj("同意");
            }
            res.put("approveInfo", approveInfo);
        } else {
            throw new CustomException("费用申请批量审批ERROR:数据不匹配,xmid:", xmid);
        }
        return res;

    }


    /**
     * 编辑数据（费用申请）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateApply", method = RequestMethod.POST)
    public BaseResult doUpdateApply(StaBudgetapproval budgetapproval) {
        int num = staBudgetapprovalService.update(budgetapproval);
        if (num > 0) {
            return BaseResult.success("费用申请更新成功!");
        } else {
            return BaseResult.failure("费用申请更新失败!");
        }
    }

    /**
     * 编辑数据（备用金申请）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateImprest", method = RequestMethod.POST)
    public BaseResult doUpdateImprest(StaBudgetapproval budgetapproval) {
        int num = staBudgetapprovalService.updateImprest(budgetapproval);
        if (num > 0) {
            return BaseResult.success("备用金申请更新成功!");
        } else {
            return BaseResult.failure("备用金申请更新失败!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/ImprestConnect", method = RequestMethod.POST)
    public BaseResult ImprestConnect(StaBudgetapproval budgetapproval) {
        if (budgetapproval.getErpbh() == null || budgetapproval.getXmlx() == null ||
                budgetapproval.getDkyfzr() == null || budgetapproval.getSsbm() == null){
            PrjProject  project= prjProjectDao.queryById(budgetapproval.getXmid());
            budgetapproval.setErpbh(project.getErpbh());
            budgetapproval.setXmlx(project.getXmlx());
            budgetapproval.setSsbm(project.getSsbm());
            budgetapproval.setDkyfzr(project.getDkyfzr());
        }

        int num = staBudgetapprovalService.ImprestConnect(budgetapproval);
        if (num > 0) {
            return BaseResult.success("备用金项目关联成功!");
        } else {
            return BaseResult.failure("备用金项目关联失败!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/DisConnect/{id}", method = RequestMethod.POST)
    public BaseResult DisConnect(@PathVariable Integer id) {
        StaBudgetapproval budgetapproval = new StaBudgetapproval();
        budgetapproval.setId(id);
        int num = staBudgetapprovalService.ImprestConnect(budgetapproval);

        if (num > 0) {
            return BaseResult.success("备用金项目取消成功!");
        } else {
            return BaseResult.failure("备用金项目取消失败!");
        }
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forApplyUpdate/{id}", method = RequestMethod.GET)
    public String forApplyUpdate(Model model, @PathVariable Integer id,
                                 @RequestParam(required = false ,defaultValue = "",value = "fylbmc")String fymc) {
        /**
         * 审核开始
         */
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(id);
        model.addAttribute("budgetapproval", budgetapproval);
        //费用信息
        StaBudgetapproval xmFyInfo = staBudgetapprovalService.getXmFyInfo(budgetapproval.getNys());
        //        获取科目费用小项xmzys
        Double kmXmzys=prjAnnualbudgetdetailService.getKmXmzys(budgetapproval.getNys(),fymc);
        if (xmFyInfo.getYsje() == null)
            xmFyInfo.setYsje(0.0);
        if (xmFyInfo.getSqje() == null)
            xmFyInfo.setSqje(0.0);
        if (xmFyInfo.getBzje() == null)
            xmFyInfo.setBzje(0.0);
        model.addAttribute("xmFyInfo", xmFyInfo);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("nys1", budgetapproval.getNys().toString());
        paraMap.put("fylb1", budgetapproval.getFylb().toString());
        paraMap.put("nys", budgetapproval.getNys().toString());
        paraMap.put("fylb", budgetapproval.getFylb().toString());
        StaBudgetapproval kmFyInfo = staBudgetapprovalService.getKmFyInfo(paraMap);
        // 申请金额总额 开始
        Map<String, Object> maps = new HashMap<>();
        maps.put("nys",budgetapproval.getNys());
        maps.put("fymc",fymc);
        Double xxzje = staBudgetapprovalService.getSqfyze(maps).getSqje();
        Double byjzje = staBudgetapprovalService.getByjze(maps).getSqje();
        Double byjbzze = staBudgetapprovalService.getByjze(maps).getBzje();
        // 项目使用费用
        String xmndjfysq = staBudgetapprovalService.getFyzz(maps).getXmndjfysq();
        Double byjje = staBudgetapprovalService.getByjzje(maps).getByj();
        Double sqe = staBudgetapprovalService.getSqe(maps).getSqje();
        kmFyInfo.setXmndjfysq(xmndjfysq);
//        kmFyInfo.setSqje(xxzje);
        kmFyInfo.setByj(byjzje);
        kmFyInfo.setXmzys(kmXmzys);
        kmFyInfo.setByjbzze(byjbzze);
        kmFyInfo.setBzje2(byjje);
        kmFyInfo.setSqje(sqe);
        // 申请金额总额 结束
        if (kmFyInfo.getYsje() == null)
            kmFyInfo.setYsje(0.0);
        if (kmFyInfo.getSqje() == null)
            kmFyInfo.setSqje(0.0);
        if (kmFyInfo.getBzje() == null)
            kmFyInfo.setBzje(0.0);
        if (kmFyInfo.getBzzje() == null)
            kmFyInfo.setBzzje(0.0);
        model.addAttribute("kmFyInfo", kmFyInfo);
        String deptName = getSysUserInfo().getDeptName();
        //获取该部门下已申请的书籍
        List<StaSourceFee> TsmcList = staSourceFeeService.searchSourceTsmcByDeptName(deptName);
        List list = new ArrayList();
        for (int i = 0; i < TsmcList.size(); i++) {
            list.add(TsmcList.get(i).getTsmc());
        }
        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ClfTemplate", fileUrl + "差旅费模版.xlsx");
        model.addAttribute("HyfTemplate", fileUrl + "会议费模版.xlsx");
        model.addAttribute("ZlfTemplate", fileUrl + "资料费模版.xlsx");
        model.addAttribute("ZscqfTemplate", fileUrl + "知识产权费模版.xlsx");
        model.addAttribute("YsfTemplate", fileUrl + "印刷费模版.xlsx");
        model.addAttribute("JjfTemplate", fileUrl + "间接费模版.xlsx");
        model.addAttribute("ZjfTemplate", fileUrl + "专家费模版.xlsx");
        model.addAttribute("LsryTemplate", fileUrl + "临时人员模版.xlsx");
        model.addAttribute("DevTemplate", fileUrl + "仪器设备使用费模版.xlsx");
        model.addAttribute("RjsyfTemplate", fileUrl + "软件使用费模版.xlsx");
        model.addAttribute("CLfTemplate", fileUrl + "材料费模版.xlsx");
        model.addAttribute("WwTemplate", fileUrl + "外委研究支出费模版.xlsx");
        model.addAttribute("WxTemplate", fileUrl + "外协测试试验与加工费模版.xlsx");
        model.addAttribute("userInfo",getSysUserInfo());
        model.addAttribute("tsmclist",list);
        return "stabudgetapproval/update_apply";
    }

    /**
     * 浏览数据
     *
     * @return
     */
    @RequestMapping(value = "/forApplyView/{id}", method = RequestMethod.GET)
    public String   forApplyView(Model model, @PathVariable Integer id,
                                 @RequestParam(required = false ,defaultValue = "",value = "fylbmc")String fymc) {
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(id);
        model.addAttribute("budgetapproval", budgetapproval);
        //费用信息
        if (budgetapproval.getSfbyj() == false) {
            StaBudgetapproval xmFyInfo = staBudgetapprovalService.getXmFyInfo(budgetapproval.getNys());
            if (xmFyInfo.getYsje() == null)
                xmFyInfo.setYsje(0.0);
            if (xmFyInfo.getSqje() == null)
                xmFyInfo.setSqje(0.0);
            if (xmFyInfo.getBzje() == null)
                xmFyInfo.setBzje(0.0);
            model.addAttribute("xmFyInfo", xmFyInfo);

            Map<String, String> paraMap = new HashMap<>();
            paraMap.put("nys1", budgetapproval.getNys().toString());
            paraMap.put("fylb1", budgetapproval.getFylb().toString());
            paraMap.put("nys", budgetapproval.getNys().toString());
            paraMap.put("fylb", budgetapproval.getFylb().toString());
            StaBudgetapproval kmFyInfo = staBudgetapprovalService.getKmFyInfo(paraMap);
            // 申请金额总额 开始
            Map<String, Object> maps = new HashMap<>();
            maps.put("nys",budgetapproval.getNys());
            if(fymc != null || fymc.isEmpty()){

                maps.put("fymc",fymc);
            }else {
                maps.put("fymc",budgetapproval.getFylbmc());
            }

            Double xxzje = staBudgetapprovalService.getSqfyze(maps).getSqje();
            Double byjzje = staBudgetapprovalService.getByjze(maps).getSqje();
            Double byjbzze = staBudgetapprovalService.getByjze(maps).getBzje();
            String xmndjfysq = staBudgetapprovalService.getFyzz(maps).getXmndjfysq();
            Double byjje = staBudgetapprovalService.getByjzje(maps).getByj();
            Double sqe = staBudgetapprovalService.getSqe(maps).getSqje();
            kmFyInfo.setSqje(sqe);
            kmFyInfo.setXmndjfysq(xmndjfysq);
//            kmFyInfo.setSqje(xxzje);
            kmFyInfo.setByj(byjzje);
            kmFyInfo.setByjbzze(byjbzze);
            kmFyInfo.setBzje2(byjje);

            if (budgetapproval.getXmid() != null){
                PrjProject project = prjProjectDao.queryById(budgetapproval.getXmid());
                int yearsDifference =  time.calculateYearDifference(project.getQs(),project.getWc()); // 年
                long daysDifference = time.calculateDaysDifference(project.getQs(),project.getWc());// 天

                model.addAttribute("xmzq",project.getQs()+" -- "+project.getWc() +" -- "+yearsDifference+"年"+" -- "+daysDifference+"天" );
            }else {
                model.addAttribute("xmzq","");
            }
            // 项目周期获取
            // 申请金额总额 结束
            if (kmFyInfo.getYsje() == null)
                kmFyInfo.setYsje(0.0);
            if (kmFyInfo.getSqje() == null)
                kmFyInfo.setSqje(0.0);
            if (kmFyInfo.getBzje() == null)
                kmFyInfo.setBzje(0.0);
            model.addAttribute("kmFyInfo", kmFyInfo);
        }
        if (budgetapproval.getSfbyj() == true) {
            return "stabudgetapproval/view_imprest";
        } else {
            return "stabudgetapproval/view_apply";
        }
    }

    /**
     * 删除数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteApply/{id}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult deleteApply(@PathVariable Integer id) {
        boolean flag = staBudgetapprovalService.deleteApplyById(id);
        if (flag) {
            return BaseResult.success("删除成功!");
        } else {
            return BaseResult.failure("删除失败!");
        }
    }

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

        int num = staBudgetapprovalService.batchDeleteApply(idList);
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }

    /**
     * 项目经费管理板块下的备用金申请页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/init_my", method = RequestMethod.GET)
    public String init_my(Model model) {
//审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("approve_status");
        model.addAttribute("approveList", approveList);
//年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);
//当前用户ID
        model.addAttribute("userId", getSysUserId());
        return "stabudgetapproval/list_imprest_my";
    }

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

        return "stabudgetapproval/list_imprest";
    }

    /**
     * 备用金申请
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_imprest", method = RequestMethod.POST)
    public BaseResult list_imprest(@RequestParam("page") Integer pageNum,
                                   @RequestParam("limit") Integer pageSize,
                                   @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                   @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                   @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                                   @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                   @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                   @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                   @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                                   @RequestParam(required = false, defaultValue = "", value = "sqmc") String sqmc) {
        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 ("科研专责".equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("spzt", spzt);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmmc", xmmc);
        paraMap.put("bh", bh);
        paraMap.put("nf", nf);
        paraMap.put("sqmc",sqmc);

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

        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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
     */
    @ResponseBody
    @RequestMapping(value = "/list_imprest1", method = RequestMethod.POST)
    public BaseResult list_imprest1(@RequestParam("page") Integer pageNum,
                                    @RequestParam("limit") Integer pageSize,
                                    @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                    @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                    @RequestParam(required = false, defaultValue = "", value = "sqmc") String sqmc,
                                    @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                    @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                    @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                    @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                                    @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc) {
        SysUserInfo userInfo = getSysUserInfo();
        PageHelper.startPage(pageNum, pageSize);

        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("spzt", spzt);
        paraMap.put("erpbh", erpbh);
        paraMap.put("sqmc", sqmc);
        paraMap.put("bh", bh);
        paraMap.put("xmmc",xmmc);


        List<StaBudgetapproval> list = staBudgetapprovalService.getByjsqList(paraMap);

        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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 = "/forImprestAdd", method = RequestMethod.GET)
    public String forImprestAdd(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);

        return "stabudgetapproval/add_imprest";
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forImprestUpdate/{id}", method = RequestMethod.GET)
    public String forImprestUpdate(Model model, @PathVariable Integer id) {
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(id);
        model.addAttribute("budgetapproval", budgetapproval);

        return "stabudgetapproval/update_imprest";
    }

    /**
     * 浏览数据(备用金)
     *
     * @return
     */
    @RequestMapping(value = "/forImprestView/{id}", method = RequestMethod.GET)
    public String forImprestView(Model model, @PathVariable Integer id) {
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(id);
        model.addAttribute("budgetapproval", budgetapproval);

        return "stabudgetapproval/view_imprest";
    }

    /**
     * 删除数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteImprest/{id}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult deleteImprest(@PathVariable Integer id) {
        boolean flag = staBudgetapprovalService.deleteApplyById(id);
        if (flag) {
            return BaseResult.success("删除成功!");
        } else {
            return BaseResult.failure("删除失败!");
        }
    }

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_reported", method = RequestMethod.GET)
    public String init_reported(Model model) {
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("approve_status");
        model.addAttribute("approveList", approveList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);

        return "stabudgetapproval/list_reported";
    }

    /**
     * 已报账费用申请列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_reported", method = RequestMethod.POST)
    public BaseResult list_reported(@RequestParam("page") Integer pageNum,
                                    @RequestParam("limit") Integer pageSize,
                                    @RequestParam(required = false, defaultValue = "", value = "sqmc") String sqmc,
                                    @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                    @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                    @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                    @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                                    @RequestParam(required = false, defaultValue = "", value = "dkyfzr") String dkyfzr,
                                    @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                    @RequestParam(required = false, defaultValue = "", value = "sfbyj") String sfbyj,
                                    @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                    @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                                    @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc) {
        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))||PostInfoEnum.KYFZR.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("sqmc", sqmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("bh", bh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("dkyfzr", dkyfzr);
        if (userInfo.getDeptName().contains("电源")){
            paraMap.put("ssbmmc","电源技术中心");
        }else {
            paraMap.put("ssbmmc", userInfo.getDeptName());
        }
//        paraMap.put("ssbmmc", getSysUserInfo().getDeptName());
        paraMap.put("nf", nf);
        paraMap.put("sfbyj", sfbyj);
        paraMap.put("xmmc",xmmc);
        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }
        }
        List<StaBudgetapproval> list = staBudgetapprovalService.getYbzFysqList(paraMap);
        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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 model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_allapply", method = RequestMethod.GET)
    public String init_allapply(Model model) {
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("approve_status");
        model.addAttribute("approveList", approveList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);
        //费用类别
        List<String> xmlx = staBudgetapprovalService.getXmlx();
        model.addAttribute("fylb", xmlx);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        /*List<String> fylb =*/

        return "stafeemanage/list_allapply";
    }

    /**
     * 全部费用申请（审批完成）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_allApply", method = RequestMethod.POST)
    public BaseResult list_allApply(@RequestParam("page") Integer pageNum,
                                    @RequestParam("limit") Integer pageSize,
                                    @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                                    @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                    @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                    @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                    @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                    @RequestParam(required = false, defaultValue = "", value = "fylb") String fylb,
                                    @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                    @RequestParam(required = false, defaultValue = "", value = "sqr") String sqr,
                                    @RequestParam(required = false, defaultValue = "", value = "sfbyj") String sfbyj,

                                    @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                                    @RequestParam(required = false, defaultValue = "", value = "sfbz") String sfbz,
                                    @RequestParam(required = false, defaultValue = "", value = "sfth") String sfth,
                                    @RequestParam(required = false, defaultValue = "", value = "dkyfzr") String dkyfzr,
                                    @RequestParam(required = false, defaultValue = "", value = "sqsj1") String sqsj1,
                                    @RequestParam(required = false, defaultValue = "", value = "sqsj2") String sqsj2,
                                    @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                    @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                                    @RequestParam(required = false, defaultValue = "", value = "dlr")Integer dlrId) {

        PageHelper.startPage(pageNum, pageSize);

        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);
            }
        }

        if (dlrId != null && dlrId.equals(0)){
            String deptName = getSysUserInfo().getDeptName();
            paraMap.put("ssbmmc", deptName);
        }else {
            paraMap.put("ssbmmc", ssbmmc);
        }
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("bh", bh);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("sfbyj", sfbyj);
        paraMap.put("xmmc", xmmc);

        paraMap.put("spzt", spzt);
        paraMap.put("sfbz", sfbz);
        paraMap.put("sfth", sfth);
        paraMap.put("dkyfzr", dkyfzr);
        paraMap.put("sqsj1", sqsj1);
        paraMap.put("sqsj2", sqsj2);
        paraMap.put("fylb", fylb);
        paraMap.put("sqr", sqr);

        List<StaBudgetapproval> list = staBudgetapprovalService.getAllApplyList(paraMap);
        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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/{fromdata}",method = RequestMethod.POST)
    public BaseResult getAll(@PathVariable(required = false) String fromdata) throws  Exception{
        Map<String, Object> map = new HashMap<>();
        if (fromdata == null){
            List<StaBudgetapproval> list = staBudgetapprovalService.getAllApplyList(map);
            return BaseResult.success("导出成功",list);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        StaBudgetapproval formDatas = objectMapper.readValue(fromdata, StaBudgetapproval.class);

        map.put("sortName",formDatas.getSortName());
        map.put("sortOrder", formDatas.getSortOrder());
        map.put("bh", formDatas.getBh());
        map.put("erpbh", formDatas.getErpbh());
        map.put("xmlx", formDatas.getXmlx());
        map.put("sfbyj", formDatas.getSfbyj());
        map.put("xmmc", formDatas.getXmmc());
        map.put("ssbmmc", formDatas.getSsbmmc());
        map.put("spzt", formDatas.getSpzt());
        map.put("sfbz", formDatas.getSfbz());
        map.put("dkyfzr", formDatas.getDkyfzr());
        map.put("sqsj1", formDatas.getSqsj1());
        map.put("sqsj2", formDatas.getSqsj2());
        map.put("fylb", formDatas.getFylb());
        map.put("sqr", formDatas.getSqr());
        map.put("nf",formDatas.getNf());
        List<StaBudgetapproval> list = staBudgetapprovalService.getAllApplyList(map);

        return BaseResult.success("导出成功",list);

    }*/

    /**
     * 浏览数据
     *
     * @return
     */
    @RequestMapping(value = "/forAllApplyView", method = RequestMethod.GET)
    public String forAllApplyView() {
        return "stafeemanage/view";
    }

    /**
     * 列表初始化(审批中的费用申请)
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_approving", method = RequestMethod.GET)
    public String init_approving(Model model) {
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("approve_status");
        model.addAttribute("approveList", approveList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);

        return "stafeemanage/list_approving";
    }

    @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();
        StaBudgetapproval formDatas = objectMapper.readValue(fromdata, StaBudgetapproval.class);
        if (formDatas.getNf().equals("0")){
            paraMap.put("nf","");
        }else {
            paraMap.put("nf",formDatas.getNf());
        }
        paraMap.put("bh", formDatas.getBh());
        paraMap.put("erpbh", formDatas.getErpbh());
        paraMap.put("xmlx", formDatas.getXmlx());
        paraMap.put("xmmc", formDatas.getXmmc());
        paraMap.put("ssbmmc", formDatas.getSsbmmc());
        paraMap.put("spzt", formDatas.getSpzt());
        paraMap.put("dkyfzr", formDatas.getDkyfzr());
        paraMap.put("sqsj1", formDatas.getSqsj1());
        paraMap.put("sqsj2", formDatas.getSqsj2());
        paraMap.put("xmfzrxm",formDatas.getXmfzrxm());
        List<StaBudgetapproval> list = staBudgetapprovalService.getAllApplyList(paraMap);
        return BaseResult.success("导出成功",list);

    }
    @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();
        StaBudgetapproval formDatas = objectMapper.readValue(fromdata, StaBudgetapproval.class);
        String nf = formDatas.getNf();
        String xmmc = formDatas.getXmmc();
        String erpbh = formDatas.getErpbh();
        String xmlx = formDatas.getXmlx();
        String xmfzrxm = formDatas.getXmfzrxm();
        String ssbmmc = formDatas.getSsbmmc();
        String spzt = formDatas.getSpzt();
        String bh = formDatas.getBh();
        if (formDatas.getNf().equals("0")){
            paraMap.put("nf","");
        }else {
            paraMap.put("nf",formDatas.getNf());
        }
        paraMap.put("xmmc", xmmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("xmfzrxm", xmfzrxm);
        paraMap.put("ssbmmc", ssbmmc);
        paraMap.put("spzt",spzt);
        paraMap.put("bh",bh);

        List<FeeManagemant> list = prjProjectService.getFyglList(paraMap);
        return BaseResult.success("导出成功",list);
    }

    /**
     * 审批中的费用申请
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_approving", method = RequestMethod.POST)
    public BaseResult list_approving(@RequestParam("page") Integer pageNum,
                                     @RequestParam("limit") Integer pageSize,
                                     @RequestParam(required = false, defaultValue = "", value = "bh") String bh,
                                     @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                     @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                     @RequestParam(required = false, defaultValue = "", value = "sfbyj") String sfbyj,
                                     @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                                     @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                                     @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                     @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                     @RequestParam(required = false, defaultValue = "", value = "dkyfzr") String dkyfzr,
                                     @RequestParam(required = false, defaultValue = "", value = "sqsj1") String sqsj1,
                                     @RequestParam(required = false, defaultValue = "", value = "sqsj2") String sqsj2,
                                     @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                     @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        Map<String, String> paraMap = new HashMap<>();
        PageHelper.startPage(pageNum, pageSize);

        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("bh", bh);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("sfbyj", sfbyj);
        paraMap.put("xmmc", xmmc);
        paraMap.put("ssbmmc", ssbmmc);

        paraMap.put("spzt", spzt);
        paraMap.put("dkyfzr", dkyfzr);
        paraMap.put("sqsj1", sqsj1);
        paraMap.put("sqsj2", sqsj2);

        List<StaBudgetapproval> list = staBudgetapprovalService.getApprovingList(paraMap);

        PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaBudgetapproval> 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 = "/getAlls/{fromdata}",method = RequestMethod.POST)
    public BaseResult getAlls(@PathVariable(required = false) String fromdata) throws  Exception{
        Map<String, Object> paraMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        StaBudgetapproval formDatas = objectMapper.readValue(fromdata, StaBudgetapproval.class);
        if (formDatas.getNf().equals("0")){
            paraMap.put("nf","");
        }else {
            paraMap.put("nf",formDatas.getNf());
        }
        paraMap.put("bh", formDatas.getBh());
        paraMap.put("erpbh", formDatas.getErpbh());
        paraMap.put("xmlx", formDatas.getXmlx());
        paraMap.put("xmmc", formDatas.getXmmc());
        paraMap.put("ssbmmc", formDatas.getSsbmmc());
        paraMap.put("spzt", formDatas.getSpzt());
        paraMap.put("dkyfzr", formDatas.getDkyfzr());
        paraMap.put("sqsj1", formDatas.getSqsj1());
        paraMap.put("sqsj2", formDatas.getSqsj2());
        paraMap.put("xmfzrxm",formDatas.getXmfzrxm());
        paraMap.put("sfbyj", formDatas.getSfbyj());

        paraMap.put("sqsj1", formDatas.getSqsj1());
        paraMap.put("sqsj2", formDatas.getSqsj2());
        List<StaBudgetapproval> list = staBudgetapprovalService.getApprovingList(paraMap);



        return BaseResult.success("导出成功",list);

    }


    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd", method = RequestMethod.GET)
    public String forApproveAdd(Model model) {
//部门主任岗位
        Map<String, String> paraMap = new HashMap<>();
//系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        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 "stabudgetapproval/add_approve";
    }

    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd1", method = RequestMethod.GET)
    public String forApproveAdd1(Model model) {
//部门主任岗位
//岗位
        Map<String, String> paraMap = new HashMap<>();
//系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        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 "stabudgetapproval/add_approve1";
    }

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    public BaseResult updateSpzt(@RequestBody String strData) {
        StaBudgetapproval fysq = JsonTool.parseObject(strData, StaBudgetapproval.class);
        if (fysq.getSpzt().equals("审批结束")) {
            fysq.setBh("");
        }
        int num = staBudgetapprovalService.updateSpzt(fysq);
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据（提交审批）
     *
     * @return
     */
    @RequestMapping(value = "/forApproveUpdate/{xmid}/{sqje}", method = RequestMethod.GET)
    public String forApproveUpdate(Model model,
                                   @PathVariable Integer xmid,
                                   @PathVariable Double sqje,
                                   @RequestParam String spzt,
                                   @RequestParam String fymc) {
        // 费用申请查看
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(xmid);
        model.addAttribute("budgetapproval", budgetapproval);
        //费用信息
        if (budgetapproval.getSfbyj() == false) {
            StaBudgetapproval xmFyInfo = staBudgetapprovalService.getXmFyInfo(budgetapproval.getNys());
            if (xmFyInfo.getYsje() == null)
                xmFyInfo.setYsje(0.0);
            if (xmFyInfo.getSqje() == null)
                xmFyInfo.setSqje(0.0);
            if (xmFyInfo.getBzje() == null)
                xmFyInfo.setBzje(0.0);
            model.addAttribute("xmFyInfo", xmFyInfo);

            Map<String, String> paraMap = new HashMap<>();
            paraMap.put("nys1", budgetapproval.getNys().toString());
            paraMap.put("fylb1", budgetapproval.getFylb().toString());
            paraMap.put("nys", budgetapproval.getNys().toString());
            paraMap.put("fylb", budgetapproval.getFylb().toString());
            StaBudgetapproval kmFyInfo = staBudgetapprovalService.getKmFyInfo(paraMap);
            // 申请金额总额 开始
            Map<String, Object> maps = new HashMap<>();
            maps.put("nys",budgetapproval.getNys());
            if(fymc != null || fymc.isEmpty()){

                maps.put("fymc",fymc);
            }else {
                maps.put("fymc",budgetapproval.getFylbmc());
            }

            Double xxzje = staBudgetapprovalService.getSqfyze(maps).getSqje();
            Double byjzje = staBudgetapprovalService.getByjze(maps).getSqje();
            Double byjbzze = staBudgetapprovalService.getByjze(maps).getBzje();
            String xmndjfysq = staBudgetapprovalService.getFyzz(maps).getXmndjfysq();
            Double byjje = staBudgetapprovalService.getByjzje(maps).getByj();
            Double sqe = staBudgetapprovalService.getSqe(maps).getSqje();
            kmFyInfo.setSqje(sqe);
            kmFyInfo.setXmndjfysq(xmndjfysq);

            kmFyInfo.setByj(byjzje);
            kmFyInfo.setByjbzze(byjbzze);
            kmFyInfo.setBzje2(byjje);

            if (budgetapproval.getXmid() != null){
                PrjProject project = prjProjectDao.queryById(budgetapproval.getXmid());
                int yearsDifference =  time.calculateYearDifference(project.getQs(),project.getWc()); // 年
                long daysDifference = time.calculateDaysDifference(project.getQs(),project.getWc());// 天

                model.addAttribute("xmzq",project.getQs()+" -- "+project.getWc() +" -- "+yearsDifference+"年"+" -- "+daysDifference+"天" );
            }else {
                model.addAttribute("xmzq","");
            }
            // 项目周期获取
            // 申请金额总额 结束
            if (kmFyInfo.getYsje() == null)
                kmFyInfo.setYsje(0.0);
            if (kmFyInfo.getSqje() == null)
                kmFyInfo.setSqje(0.0);
            if (kmFyInfo.getBzje() == null)
                kmFyInfo.setBzje(0.0);
            model.addAttribute("kmFyInfo", kmFyInfo);
        }

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

        if (spzt.equals("院长审批") || spzt.equals("主管院领导审批") && sqje < 1000000) {
            return "stabudgetapproval/finish_approve";
        } else {
            //岗位
            Map<String, String> paraMap2 = new HashMap<>();
            if (spzt.equals("部门主任审批"))
                paraMap2.put("postName", "科技项目管理专责");
            else if (spzt.equals("科技项目管理专责审批"))
                paraMap2.put("postName", "科技部部门主任");
            else if (spzt.equals("科技部部门主任审批"))
                paraMap2.put("postName", "主管院领导");
            else if (spzt.equals("主管院领导审批"))
                paraMap2.put("postName", "院长");
            else {
                paraMap2.put("postName", "部门主任");
            }

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

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

    //初始化下拉
    @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 = "/forApproveUpdate1/{xmid}/{sqje}", method = RequestMethod.GET)
    public String forApproveUpdate1(Model model, @PathVariable Integer xmid, @PathVariable Double sqje, @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() == 1) {为
        if (approveList.size() < 1) {
            StaBudgetapproval approve = staBudgetapprovalService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(approve.getSqmc());
            approveInfo.setSqje(sqje);
            approveInfo.setZt("数据不匹配");
            model.addAttribute("approveInfo", approveInfo);
        } else {
            PrjApproverecord approveInfo = approveList.get(approveList.size() - 1);
            approveInfo.setSqje(sqje);
            model.addAttribute("approveInfo", approveInfo);
        }

        if (spzt.equals("院长审批") || spzt.equals("主管院领导审批") && sqje < 1000000) {
            return "stabudgetapproval/finish_approve1";
        } else {
            //岗位
            Map<String, String> paraMap2 = new HashMap<>();
            if (spzt.equals("未提交(返回)")) {
                if (userInfo != null && userInfo.getDeptId().equals("52")) {
                    paraMap2.put("postName", "科技部部门主任");
                } else {
                    paraMap2.put("postName", "科研负责人");
                }
            } else if (spzt.equals("部门主任审批"))
                paraMap2.put("postName", "科技项目管理专责");
            else if (spzt.equals("科技项目管理专责审批"))
                paraMap2.put("postName", "科技部部门主任");
            else if (spzt.equals("科技部部门主任审批"))
                paraMap2.put("postName", "主管院领导");
            else if (spzt.equals("主管院领导审批"))
                paraMap2.put("postName", "院长");
            else
                paraMap2.put("postName", "部门主任");

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

            if (spzt.contains("未提交"))
                return "stabudgetapproval/back_approve1";
            else
                return "stabudgetapproval/update_approve1";
        }
    }

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

        return "stabudgetapproval/list_approve";
    }

    @RequestMapping(value = "/forApproveList1", method = RequestMethod.GET)
    public String forApproveList1() {
        return "stabudgetapproval/list_approve1";
    }

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_feemanage", method = RequestMethod.GET)
    public String init_feemanage(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //年份
        List<String> yearList = staBudgetapprovalService.getYearList();
        model.addAttribute("yearList", yearList);

        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("pay_status");
        model.addAttribute("approveList", approveList);

        return "stafeemanage/list_feemanage";
    }

    @Resource
    private  PrjProjectDao prjProjectDao;

    @ResponseBody
    @RequestMapping(value = "/list_feemanage", method = RequestMethod.POST)
    public BaseResult list_feemanage(@RequestParam("page") Integer pageNum,
                                     @RequestParam("limit") Integer pageSize,
                                     @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                                     @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                     @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                     @RequestParam(required = false, defaultValue = "", value = "xmfzrxm") String xmfzrxm,
                                     @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                                     @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                                     @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 = "bh")String bh
    ) {
        PageHelper.startPage(pageNum, pageSize);

        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("xmmc", xmmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("xmfzrxm", xmfzrxm);
        paraMap.put("ssbmmc", ssbmmc);
        paraMap.put("spzt",spzt);
        paraMap.put("bh",bh);

        List<FeeManagemant> list = prjProjectService.getFyglList(paraMap);
//        for (int i = 0;i<list.size();i++){
//           // 万元 转换成元
//            if (list.get(i).getSqje() != null){
//                list.get(i).setSqje(list.get(i).getSqje() *10000);
//            }else {
//                list.get(i).setSqje(0.00);
//            }
//            if (list.get(i).getBzje() != null){
//                list.get(i).setBzje(list.get(i).getBzje() *10000);
//            }else {
//                list.get(i).setBzje(0.00);
//            }
//            if(list.get(i).getYe() != null){
//                list.get(i).setYe(list.get(i).getYe() *10000);
//            }else {
//                list.get(i).setYe(0.00);
//            }
//            if (list.get(i).getByj() != null){
//                list.get(i).setByj(list.get(i).getByj() * 10000);
//            }else {
//                list.get(i).setByj(0.00);
//            }
//            if(list.get(i).getByjsqje() != null){
//
//                list.get(i).setByjsqje(list.get(i).getByjsqje() *10000);
//            }else {
//                list.get(i).setByjsqje(0.00);
//            }
//            if (list.get(i).getByjbzje() != null){
//                list.get(i).setByjbzje(list.get(i).getByjbzje() *10000);
//            }else {
//                list.get(i).setByjbzje(0.00);
//            }
//            if (list.get(i).getByjye() != null){
//                list.get(i).setByjye(list.get(i).getByjye() *10000);
//            }else {
//                list.get(i).setByjye(0.00);
//            }
//
//
//            FeeManagemant sqje =  prjProjectDao.getSqje(list.get(i).getErpbh());
//           if (sqje.getSqje().equals(list.get(i).getSqje()) != true){
//               list.get(i).setSqje(sqje.getSqje());
//           }
//
//
//        }
        PageInfo<FeeManagemant> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<FeeManagemant> 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);
    }

    @RequestMapping(value = "/init_project/{nf}", method = RequestMethod.GET)
    public String init_project(Model model, @PathVariable String nf) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);

        model.addAttribute("nf", nf);
        return "stabudgetapproval/list_project";
    }

    /**
     * 批量作废
     *
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchNullify", method = RequestMethod.POST)
    public BaseResult batchNullify(@RequestBody String data) {
        List<StaBudgetapproval> prjList = JsonTool.parseArray(data, StaBudgetapproval.class);
        List<Integer> idList = new ArrayList<>();
        prjList.forEach(item -> {
            idList.add(item.getId());
        });

        int num = staBudgetapprovalService.batchNullify(idList);
        if (num > 0) {
            return BaseResult.success("作废成功!");
        } else {
            return BaseResult.failure("作废失败!");
        }
    }

    private String GetApproveRecordBH(String partBh) {
        String bh = "";
        List<StaBudgetapproval> bhList = staBudgetapprovalService.queryByBH(partBh);
        List<Integer> bh_List = new ArrayList();
        if (bhList != null && bhList.size() > 0) {
            for (int i = 0; i < bhList.size(); i++) {
                int _tmpBh = Integer.parseInt(bhList.get(i).getBh().substring(bhList.get(i).getBh().length() - 4));
                bh_List.add(_tmpBh);
            }
            if (bh_List.size() > 0) {
                try {
                    Integer max = Collections.max(bh_List);
                    Integer idx = max + 1;
                    bh = partBh + String.format("%04d", idx);
                } catch (Exception er) {
                    bh = partBh + "1001";
                }
            } else
                bh = partBh + "1001";
        } else
            bh = partBh + "1001";
        return bh;
    }

    /**
     * 获取年度费用申请预算列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/yslist/{nys}", method = RequestMethod.POST)
    public Object yslist(@PathVariable Integer nys) {
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getFysqBudgetList(nys);

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

        return resultMap;
    }




    /**
     * 项目备用金信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getXmFyInfo/{rws}/{nf}", method = RequestMethod.POST)
    public StaBudgetapproval getXmFyInfo(@PathVariable Integer rws, @PathVariable Integer nf) {
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("rws", rws.toString());
        paraMap.put("nf", nf.toString());
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.getAnnualBudget(paraMap);

        StaBudgetapproval xmFyInfo = staBudgetapprovalService.getByjInfo(annualbudget.getId());
        if (xmFyInfo == null) {
            StaBudgetapproval staBudgetapproval = new StaBudgetapproval();
            staBudgetapproval.setYsje(0.0);
            staBudgetapproval.setSqje(0.0);
            staBudgetapproval.setBzje(0.0);
            staBudgetapproval.setNys(annualbudget.getId());
            return staBudgetapproval;
        } else {

            if (xmFyInfo.getYsje() == null) {
                xmFyInfo.setYsje(0.0);
            }

            if (xmFyInfo.getSqje() == null) {
                xmFyInfo.setSqje(0.0);
            }

            if (xmFyInfo.getBzje() == null) {
                xmFyInfo.setBzje(0.0);
                xmFyInfo.setNys(annualbudget.getId());
            }

            return xmFyInfo;
        }

    }

    /**
     * 项目分项费用信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getKmFyInfo/{nys}/{fylb}", method = RequestMethod.POST)
    public StaBudgetapproval getKmFyInfo(@PathVariable Integer nys, @PathVariable Integer fylb,
                                         @RequestParam(required = false,defaultValue = "",value = "fylbmc")String fymc) {
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("fylb", fylb.toString());
        paraMap.put("nys", nys.toString());
        StaBudgetapproval kmFyInfo = staBudgetapprovalService.getKmFyInfo(paraMap);
        // 申请金额总额 开始
        if (kmFyInfo != null ){
            Map<String, Object> maps = new HashMap<>();
            maps.put("nys",nys);
            maps.put("fymc",fymc);
            Double xxzje = staBudgetapprovalService.getSqfyze(maps).getSqje();
            Double byjzje = staBudgetapprovalService.getByjze(maps).getSqje();
            Double byjbzze = staBudgetapprovalService.getByjze(maps).getBzje();
            kmFyInfo.setSqje(xxzje);
            kmFyInfo.setByj(byjzje);
            kmFyInfo.setByjbzze(byjbzze);
            Double sqe = staBudgetapprovalService.getSqe(maps).getSqje();
            kmFyInfo.setSqje(sqe);
            // 申请金额总额 结束
        }
        //        获取科目费用小项xmzys
        Double kmXmzys=prjAnnualbudgetdetailService.getKmXmzys(nys,fymc);
        Map<String, Object> maps = new HashMap<>();
        maps.put("nys",nys);
        maps.put("fymc",fymc);
        if (kmFyInfo == null) {
            kmFyInfo = new StaBudgetapproval();
            kmFyInfo.setSqje(0.0);
            kmFyInfo.setBzje(0.0);
        } else {
            if (kmFyInfo.getSqje() == null)
                kmFyInfo.setSqje(0.0);
            if (kmFyInfo.getBzje() == null)
                kmFyInfo.setBzje(0.0);
            if (kmFyInfo.getBzzje() == null)
                kmFyInfo.setBzzje(0.0);
                kmFyInfo.setXmzys(kmXmzys);

        }

        return kmFyInfo;
    }

    @RequestMapping(value = "/forByjConnect/{id}", method = RequestMethod.GET)
    public String forByjConnect(Model model, @PathVariable Integer id) {
        StaBudgetapproval budgetapproval = staBudgetapprovalService.getFysqById(id);
        model.addAttribute("budgetapproval", budgetapproval);

        return "stabudgetapproval/connect_project";
    }

    @ResponseBody
    @RequestMapping(value = "/doByjConnect", method = RequestMethod.POST)
    public BaseResult doByjConnect(@RequestBody String strData) {
        StaBudgetapproval fysq = JsonTool.parseObject(strData, StaBudgetapproval.class);
        if (fysq.getSpzt().equals("审批结束")) {
            fysq.setBh("");
        }
        int num = staBudgetapprovalService.updateSpzt(fysq);
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 获取年度费用申请预算列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSubNode/{nys}", method = RequestMethod.GET)
    public Object getSubNode(@PathVariable Integer nys,
                             @RequestParam Integer page,
                             @RequestParam Integer limit,
                             @RequestParam(required = false, value = "mc") String mc
    ) {
        Integer count = prjAnnualbudgetdetailService.getSubNodeCount(nys, page, limit);
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getSubNode(nys, page, limit, mc);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        resultMap.put("count", count);
        resultMap.put("data", list);

        return resultMap;
    }

    /**
     * 获取年度保障费用类别总额
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getFyBz/{nys}", method = RequestMethod.GET)
    public Object getFyBz(@PathVariable Integer nys,
                             @RequestParam Integer page,
                             @RequestParam Integer limit,
                             @RequestParam(required = false, value = "mc") String mc
    ) {
        // 获取查询数据总条数

        PageHelper.startPage(page, limit);
        Map<Object,Object> map = new HashMap<>();
        map.put("fymc",mc);
        map.put("nys",nys);
        map.put("page",page);
        map.put("limit",limit);
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getBz(map);
        Map<String, Object> resultMap = new HashMap<>();
        PageInfo<PrjAnnualbudgetdetail> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjAnnualbudgetdetail> rows = pageinfo.getList();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        resultMap.put("count", list.size());
        resultMap.put("data", rows);
        return resultMap;
    }


    @Resource
    private StaPayapprovalService staPayapprovalService;
    /**
     * 获取单科目下项目报账总额
     */
    @ResponseBody
    @RequestMapping(value = "/getKmze",method = RequestMethod.POST)
    public BaseResult getKmze(@RequestParam Integer id){
        // 传入一个值 费用申请 ID
        if (id == null){
            return BaseResult.failure(-1,"费用申请异常请联系管理员！");
        }
        StaBudgetapproval st = staBudgetapprovalService.queryById(id);
        if (st ==  null){
            return BaseResult.failure(-1,"数据异常请联系管理员！");
        }
        Map<Object,Object> map = new HashMap<>();
        map.put("fymc",st.getFymc());
        map.put("nys",st.getNys());
        map.put("id",st.getXmid());
        // 此处传入值硬使用 项目整体汇总值，而非单项目汇总值
       /* List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getBz(map);*/
        List<PrjAnnualbudget> list = staPayapprovalService.getXmzys(map);
        if (list.size() == 0){
            return BaseResult.failure(-1,"报账金额为空！");
        }
        list.get(0).setFymc(st.getFymc());
        return  BaseResult.success(list);
    }


    /**
     * 未关联项目备用金列表
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/unassociated/{fromdata}")
    public BaseResult unassociated(@PathVariable String fromdata,
                                   @RequestParam("page") Integer pageNum,
                                   @RequestParam("limit") Integer pageSize) {

        try {
            PageHelper.startPage(pageNum,pageSize);
            Map<String, String> map = new HashMap<>();
            ObjectMapper objectMapper = new ObjectMapper();
            FormData formData = objectMapper.readValue(fromdata, FormData.class);

            if (!formData.getNf().equals("0")){
                String[] dk = formData.getNf().split(",");
                if (dk.length>1){
                    map.put("nf",dk[1]);
                }else {
                    map.put("nf", formData.getNf());
                }

            }else {
                map.put("nf","");
            }
            map.put("bh", formData.getBh());

            map.put("xmmc", formData.getXmmc());
            List<StaBudgetapproval> list = staBudgetapprovalService.unassociated(map);
            PageInfo<StaBudgetapproval> pageinfo = new PageInfo<>(list);
            //取出查询结果
            List<StaBudgetapproval> 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);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.failure("处理转换异常");
        }
    }


    /**
     * 审批列表获取科研编号
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/getBhById/{id}")
    public BaseResult getBhById(@PathVariable String id) {
        String bh = staBudgetapprovalService.getBhById(id);
        return BaseResult.success(bh);
    }

    /**
     * 获取项目总预算
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/getXMZYS/{id}")
    public BaseResult getXMZYS(@PathVariable String id) {
        Double xmzys = prjAnnualbudgetdetailService.getXMZYS(id);
        return BaseResult.success(xmzys);
    }


    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/updateSsbm", method = RequestMethod.GET)
    public String updateSsbm(Model model ,@RequestParam Integer id){
        model.addAttribute("dept",sysDeptInfoService.list());
        if (id != null ){
            StaBudgetapproval staBudgetapproval =  staBudgetapprovalService.queryById(id);
            model.addAttribute("sta",staBudgetapproval);
            return "stabudgetapproval/bmbg";
        }else {
            return "数据异常，请联系管理员";
        }
    }

    @ResponseBody
    @RequestMapping(value = "bgbm",method = RequestMethod.POST)
    public BaseResult bgbm(@RequestBody String formData){

        // 解析JSON 为对象
        StaBudgetapproval sta = JsonTool.parseObject(formData,StaBudgetapproval.class);
        StaBudgetapproval staBudgetapproval = staBudgetapprovalService.queryById(sta.getId());
        // 增加审批列表留痕选项
        // 获取当前系统时间
        // 转换时间格式
        Date data = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 审批列表记录
        if (staBudgetapproval != null){
            staBudgetapproval.setSsbm(Integer.parseInt(sta.getSsbmmc()));
            int num = staBudgetapprovalService.updatebmbg(staBudgetapproval);
            if (num > 0){
                PrjApproverecord prjApproverecord = new PrjApproverecord();
                prjApproverecord.setTablename("sta_BudgetApproval");
                prjApproverecord.setXmid(staBudgetapproval.getXmid());
                prjApproverecord.setYj( "项目名称："+staBudgetapproval.getXmmc()+",ERP编号："+staBudgetapproval.getErpbh()+","+"'部门'从'"+
                        staBudgetapproval.getSsbmmc()+"'转移至'"+sta.getSsbmmc()+","+
                        ",操作员："+
                        sysUserInfoService.queryById(getSysUserId()).getName());
                prjApproverecord.setSfsjsh(true);
                prjApproverecord.setSjshr(getSysUserId());
                prjApproverecord.setShsj(format.format(data));
                prjApproverecord.setTjsj(format.format(data));
                prjApproverecord.setTjr(getSysUserId());
                prjApproverecord.setShr(getSysUserId());
                prjApproverecord.setSpcz("项目转移");
                prjApproverecord.setXm(staBudgetapproval.getXmmc());
                prjApproverecord.setZt("已完成");
                prjApproverecord.setWc(true);
                int muns = prjApproverecordService.insert(prjApproverecord);
                if (muns > 0){
                    return  BaseResult.success("'"+staBudgetapproval.getErpbh()+"'部门转移成功！");
                }
            }
        }
            return BaseResult.failure(-1, "数据转移失败！");

    }

}

