package com.liang.controller;

import cn.hutool.json.JSON;
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.constants.CommonConstant;
import com.liang.common.enums.PostInfoEnum;
import com.liang.common.enums.ProjectTypeEnnum;
import com.liang.common.exception.CustomDivException;
import com.liang.common.exception.CustomException;
import com.liang.common.utils.*;
import com.liang.dao.PrjAnnualbudgetdetailDao;
import com.liang.dao.PrjCompletecompanyDao;
import com.liang.entity.*;
import com.liang.entity.baobiao.UtilEntity;
import com.liang.service.*;
//import com.liang.vo.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections4.CollectionUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.liang.common.utils.SecurityUtil.getSysUserInfo;

/**
 * 项目(PrjProject)表控制层
 *
 * @author makejava
 * @since 2023-03-08 14:54:52
 */
@Controller
@RequestMapping("prjProject")
public class PrjProjectController extends BaseController {
    final static Logger logger = LoggerFactory.getLogger(com.liang.controller.BasePersonController.class);
    /**
     * 服务对象
     */
    @Resource
    private PrjProjectService prjProjectService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private BaseProjecttypeService projecttypeService;
    @Resource
    private PrjBudgetService prjBudgetService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private PrjCompletecompanyService prjCompletecompanyService;
    @Resource
    private PrjFeeschemeService prjFeeschemeService;
    @Resource
    private PrjMemberService prjMemberService;
    @Resource
    private CyyService cyyService;
    @Resource
    private PrjDivisioncompanyService prjDivisioncompanyService;

    @Resource
    private BasePersonService basePersonService;
    @Resource
    private PrjUndertakecompanyService prjUndertakecompanyService;
    @Resource
    private PrjSubtopicService prjSubtopicService;
    @Resource
    private BaseTitleService baseTitleService;
    @Resource
    private PrjSubtopicplanService prjSubtopicplanService;
    @Resource
    private BaseCompanyService baseCompanyService;
    @Resource
    private PrjContactsService prjContactsService;
    @Resource
    private SysUserInfoService sysUserInfoService;
    @Resource
    private PrjAnnualbudgetdetailDao prjAnnualbudgetdetailDao;
    @Resource
    private PrjProjectXgjlService prjProjectXgjlService;
    @Resource
    private SysUserPostService sysUserPostService;


    private final static List oldCddwList = new ArrayList();
    private final static List newCddwList = new ArrayList();


    private DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月");
    private DateFormat dateFormat1 = new SimpleDateFormat("yyyy.MM");

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

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

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        //审批状态
        List<Map<String, String>> dictList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("dictList", dictList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        //获取当前用户的信息
        List<SysUserPost> list = sysUserPostService.getPostId(getSysUserId());
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getPostId() == 19 || list.get(i).getPostId() == 39){
                model.addAttribute("postId",list.get(i).getPostId());
            }
        }

        return "prjproject/list";
    }

    /**
     * 页面初始化
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc,
                           @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                           @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                           @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                           @RequestParam(required = false, defaultValue = "", value = "sfxg") String sfxg,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("zwmc", zwmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("spzt", spzt);
        paraMap.put("xmlx", xmlx);
        paraMap.put("sfxg", sfxg);

        List<PrjProject> list = prjProjectService.getProjectList(paraMap);

        PageInfo<PrjProject> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjProject> 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 = "/ndyslist", method = RequestMethod.POST)
    public BaseResult ndyslist(@RequestParam("page") Integer pageNum,
                               @RequestParam("limit") Integer pageSize,
                               @RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc,
                               @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                               @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                               @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                               @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("zwmc", zwmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);

        List<PrjProject> list = prjProjectService.getNdysProjectList(paraMap);
        if (Tools.notEmpty(list)) {
            list.stream().filter(item -> ProjectTypeEnnum.GWGSKJXM.getCode().equals(item.getXmlx())).forEach(item -> item.setYsje(item.getWGYSJE()));
            list.stream().filter(item -> ProjectTypeEnnum.SXGSKJXM.getCode().equals(item.getXmlx())).forEach(item -> item.setYsje(item.getSXYSJE()));
        }
        PageInfo<PrjProject> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjProject> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ReportRYTemplate", fileUrl + "任务书主要完成人.xlsx");
        model.addAttribute("ReportRYTemplate1", fileUrl + "任务书主要完成人1.xlsx");
        SysUserInfo userInfo = sysUserInfoService.queryById(getSysUserId());
        model.addAttribute("userInfo", userInfo);

        return "prjproject/add";
    }

    /**
     * 保存数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAddNormal", method = RequestMethod.POST)
    public BaseResult doAddNormal(PrjProject project) {
        project.setSpzt("未提交");
        project.setCjr(getSysUserId());
        project.setSfxg(0);
        if (project.getSfgjmmjsxm() == null) {
            project.setSfgjmmjsxm(false);
        }
        // 添加判断条件，一个项目编号只能提一个任务书

        List<PrjProject> list = prjProjectService.getErpBh(project.getErpbh());
        if (list.size() == 0) {
            int num = prjProjectService.insertNormal(project);
            if (num > 0) {
                //项目预算内容插入
                prjBudgetService.insertBatchByXmlx(project.getXmlx(), project.getId());
                return BaseResult.success("基本信息保存成功!", project);
            } else {
                return BaseResult.failure("基本信息保存失败!");
            }
        }
        return BaseResult.failure(2000, "任务书ERP编号已存在，请不要重复创建！");


    }

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

    /**
     * 编辑数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateNormal", method = RequestMethod.POST)
    public BaseResult doUpdateNormal(PrjProject project) {
        if (project.getSfgjmmjsxm() == null)
            project.setSfgjmmjsxm(false);

        int num = prjProjectService.updateNormal(project);
        if (num > 0) {
            return BaseResult.success("基本信息保存成功!", project);
        } else {
            return BaseResult.failure("基本信息保存失败!");
        }
    }

    /**
     * 保存数据（填写说明）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateTxsm", method = RequestMethod.POST)
    public BaseResult doUpdateTxsm(@RequestBody String data) {
        PrjProject project = JsonTool.parseObject(data, PrjProject.class);
        int num = prjProjectService.updateTXSM(project.getTxsm(), project.getId());
        if (num > 0) {
            return BaseResult.success("填写说明保存成功!");
        } else {
            return BaseResult.failure("填写说明保存失败!");
        }
    }

    /**
     * 保存数据（研究内容及考核指标）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateContent", method = RequestMethod.POST)
    public BaseResult updateContent(@RequestBody String data) {
        PrjProject project = JsonTool.parseObject(data, PrjProject.class);
        int num = prjProjectService.updateContent(project.getYjnrjkhzb(), project.getId());
        if (num > 0) {
            return BaseResult.success("研究内容保存成功!");
        } else {
            return BaseResult.failure("研究内容保存失败!");
        }
    }

    @Resource
    private PrjCompletecompanyDao prjCompletecompanyDao;
    @Resource
    private com.liang.dao.PrjBudgetDao prjBudgetDao;

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    public BaseResult updateSpzt(@RequestBody String strData) {
        PrjProject rws = JsonTool.parseObject(strData, PrjProject.class);
        int num = prjProjectService.updateSpzt(rws);

        //审批结束时 更新年度预算
        if (StringUtils.isNotBlank(rws.getSpzt())
                && "审批结束".equals(rws.getSpzt())) {
            prjProjectService.updatePrj_AnnualBudgetDetail(rws.getId());
        //更新审批通过状态
            prjProjectService.updateSPTGZT(rws);
        }
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

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

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

    @ApiOperation(value = "修改任务书当前审批状态", notes = "修改任务书当前审批状态")
    @RequestMapping(value = "/upDataSpzt/{id}", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult upDataSpzt(@RequestBody String data, @PathVariable Integer id) {

        System.out.println("当前操作人员ID：" + id);
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String dateTimeStr = currentTime.format(formatter);
        if (data.isEmpty()) {
            return BaseResult.failure("回退失败");
        }
        PrjProject prs = new PrjProject();
        System.out.println(data);
        try {
            // 将String json 字符串 转换为  数组
            JSONArray jsonArray = new JSONArray(data);
            Integer id1 = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                id1 = jsonObject.getInt("id");
                System.out.println("ID: " + id1);
            }
            System.out.println("这是新建的bean" + prs);
            PrjProject project = prjProjectService.queryById(id1);

            project.setSpzt("未提交");
            Integer pr = prjProjectService.update(project);

            // 获取当前账户人员信息
            SysUserInfo sysUserInfo = sysUserInfoService.queryById(id);

            // 创建一个审批bean，用于存储数据
            PrjApproverecord prjApproverecord = new PrjApproverecord();
            // 审批状态、提交时间、完成、审核人、审核时间、审批操作、意见

            prjApproverecord.setSpcz("审批回退");
            prjApproverecord.setTjsj(currentTime.format(formatter));
            prjApproverecord.setShr(id);
            prjApproverecord.setZt("管理员回退任务书至-未提交");
            prjApproverecord.setShsj(currentTime.format(formatter));
            prjApproverecord.setXmid(id1);
            prjApproverecord.setWc(true);


            prjApproverecordService.insert(prjApproverecord);


            if (pr < 1) {

                return BaseResult.failure("回退失败");
            }

            return BaseResult.success("回退成功");
        } catch (Exception a) {
            a.printStackTrace();
        }

        return BaseResult.failure("");
    }


    /**
     * 导出项目任务书到excel
     *
     * @param response
     */
    @ApiOperation(value = "导出全部数据到excel", notes = "导出全部数据到excel")
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletResponse response) {
        if (logger.isInfoEnabled()) {
            logger.info("PrjProjectController -- exportExcel -- start");
        }
        List<PrjProject> projectList = prjProjectService.getProjectList(new HashMap<>());

        List<String> listName = Arrays.asList("中文名称", "审批状态", "ERP编号", "项目类型", "起始", "完成", "创建人", "创建时间");
        List<Map<String, String>> list = new ArrayList<>();
        for (PrjProject project : projectList) {
            Map<String, String> map = new HashMap<>();
            map.put("中文名称", project.getZwmc());
            map.put("审批状态", project.getSpzt());
            map.put("ERP编号", project.getErpbh());
            map.put("项目类型", project.getXmlxmc());
            map.put("起始", project.getQs().toString());
            map.put("完成", project.getWc().toString());
            map.put("创建人", project.getCjrxm());
            map.put("创建时间", project.getCjrq().toString());
            list.add(map);
        }

        ExcelPoiUtil.excelPort("项目任务书", listName, list, null, response);
    }

    @ResponseBody
    @RequestMapping(value = "/getAll/{fromdata}",method = RequestMethod.POST)
    public BaseResult getAll(@PathVariable(required = false) String fromdata) throws  Exception{
        Map<String, String> paraMap = new HashMap<>();
        if (fromdata == null){
            List<PrjProject> projectList = prjProjectService.getProjectList(paraMap);
            return BaseResult.success("导出成功",projectList);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        PrjProject formDatas = objectMapper.readValue(fromdata, PrjProject.class);
        paraMap.put("zwmc", formDatas.getZwmc());
        paraMap.put("erpbh", formDatas.getErpbh());
        paraMap.put("spzt", formDatas.getSpzt());
        paraMap.put("xmlx", formDatas.getXmlx());
        List<PrjProject> list = prjProjectService.getProjectList(paraMap);

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

    }

    /**
     * 学科分类
     *
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/xkfl", method = RequestMethod.GET)
    public String xkfl() {
        return "prjproject/xkfl";
    }

    /**
     * 国民经济行业
     *
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/gmjjhy", method = RequestMethod.GET)
    public String gmjjhy() {
        return "prjproject/gmjjhy";
    }

    /**
     * 跳转至转移页面
     * @return
     */
    
    @Resource
    private SysDeptInfoService sysDeptInfoService;
    
    @ApiOperation(value = "项目转移",notes = "项目转移")
    @RequestMapping(value = "/updateSsbm/{id}")
    public String updareSsbm(Model model,@PathVariable Integer id){
        //  获取部门所有部门信息
        Map<String, String> map = new HashMap<>();
        List<SysDeptInfo> list = sysDeptInfoService.queryAll();
        model.addAttribute("dept",list);
        // 根据id 查询单条数据
        PrjProject project = prjProjectService.queryById(id);
        if (project != null){
            model.addAttribute("project",project);
        }
        // 电科院负责人
/*        List<BasePerson> list1 = basePersonService.getBasePersonList(map);
        model.addAttribute("dkyfzr",list1);*/
/*        // 申请人
        List<SysUserInfo> list2 = sysUserInfoService.getSysUserInfoList(map);
        model.addAttribute("cjr",list2);*/
        return "prjproject/updateSsbm";
    }

    @ApiOperation(value = "查看页面初始化", notes = "查看页面初始化")
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        PrjProject project = prjProjectService.queryById(id);
        model.addAttribute("project", project);

        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ReportRYTemplate", fileUrl + "任务书主要完成人.xlsx");
        return "prjproject/view";
    }

    @ApiOperation(value = "编辑页面初始化", notes = "编辑页面初始化")
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        SysUserInfo user = getSysUserInfo();
        if (user == null) {
            throw new CustomException("登录失效,请重新登录");
        }

        //当前项目
        PrjProject project = prjProjectService.queryById(id);
        if (!"科技部".equals(user.getDeptName())) {
            if ((!CommonConstant.WTJFH.equals(project.getSpzt()) && !CommonConstant.WTJ.equals(project.getSpzt()))) {
                throw new CustomDivException("该任务正在审批不能编辑");
            } else if (!user.getUserId().equals(project.getCjr())) {
                throw new CustomDivException("您不是该任务创建人");
            }

        }
        model.addAttribute("project", project);

        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ReportRYTemplate", fileUrl + "任务书主要完成人.xlsx");

        return "prjproject/update";
    }
    @RequestMapping(value = "/forXgUpdate/{id}", method = RequestMethod.GET)
    public String forXgUpdate(Model model, @PathVariable Integer id) {
        SysUserInfo user = getSysUserInfo();
        if (user == null) {
            throw new CustomException("登录失效,请重新登录");
        }

        //当前项目
        PrjProject project = prjProjectService.queryById(id);
        if (!"科技部".equals(user.getDeptName())) {
            if (!user.getUserId().equals(project.getCjr())) {
                throw new CustomDivException("您不是该任务创建人");
            }

        }
        //获取子科目中各公司的总经费
        List<PrjCompletecompany>prjCompletecompanyListFy=prjCompletecompanyService.getCompanyListFy(id);
        model.addAttribute("prjCompletecompanyListFy",prjCompletecompanyListFy);
        model.addAttribute("project", project);

        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("ReportRYTemplate", fileUrl + "任务书主要完成人.xlsx");

        return "prjproject/xg_update";
    }

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

    /**
     * 保存数据（项目预算）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateXmys", method = RequestMethod.POST)
    public BaseResult doUpdateXmys(@RequestBody String data) {
        List<PrjBudget> prjBudgets = JsonTool.parseArray(data, PrjBudget.class);
        int num = prjBudgetService.updateBatch(prjBudgets);
        if (num > 0) {
            return BaseResult.success("项目预算保存成功!");
        } else {
            return BaseResult.failure("项目预算保存失败!");
        }
    }

    /**
     * 保存数据（有关问题说明）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateYgwtsm", method = RequestMethod.POST)
    public BaseResult doUpdateYgwtsm(@RequestBody String data) {
        PrjProject project = JsonTool.parseObject(data, PrjProject.class);
        int num = prjProjectService.updateYGWTSM(project.getYgwtsm(), project.getId());
        if (num > 0) {
            return BaseResult.success("有关问题说明保存成功!");
        } else {
            return BaseResult.failure("有关问题说明保存失败!");
        }
    }

    /**
     * 保存数据（附件）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateFJ", method = RequestMethod.POST)
    public BaseResult doUpdateFJ(@RequestBody String data) {
        PrjProject project = JsonTool.parseObject(data, PrjProject.class);
        int num = prjProjectService.updateFJ(project.getFj(), project.getId());
        if (num > 0) {
            return BaseResult.success("附件保存成功!");
        } else {
            return BaseResult.failure("附件保存失败!");
        }
    }

    /**
     * 根据用户名获取常用语
     */
    @ResponseBody
    @RequestMapping(value = "/forCyy", method = RequestMethod.GET)
    public Object forCyy(@RequestParam(required = false, defaultValue = "", value = "zwmc") String cyy) {

        Map<String, String> map = new HashMap<>();
        map.put("zwmc", cyy);
        List<PrjProject> list = prjProjectService.getRwsList(map);

        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 = "/rwsList", method = RequestMethod.GET)
    public Object rwsList(@RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc) {

        Map<String, String> map = new HashMap<>();
        map.put("zwmc", zwmc);
        List<PrjProject> list = prjProjectService.getRwsList(map);

        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
     */
    @RequestMapping(value = "/forApplyAdd/{id}", method = RequestMethod.GET)
    public String forApplyAdd(Model model, @PathVariable Integer id) {
        PrjProject project = prjProjectService.queryById(id);
        model.addAttribute("project", project);

        return "prjproject/add_apply";
    }

    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd", method = RequestMethod.GET)
    public String forApproveAdd(Model model) {
        //科研计划专责
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("postName", PostInfoEnum.KYJHZZ.postName());
        SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap);
        if (postInfo == null)
            postInfo = new SysPostInfo();
        model.addAttribute("postInfo", postInfo);

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

        return "prjproject/add_approve";
    }


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

        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid.toString());
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            model.addAttribute("approveInfo", approveList.get(approveList.size() - 1));
        }else {
            PrjProject project = prjProjectService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(project.getZwmc());
            approveInfo.setZt("数据不匹配");
            model.addAttribute("approveInfo", approveInfo);
        }
        if (spzt.contains("未提交")) {
            Map<String, String> paraMap2 = new HashMap<>();
            paraMap2.put("postName", PostInfoEnum.KYJHZZ.postName());

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

            return "prjproject/back_approve";
        } else {
            return "prjproject/finish_approve";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/bathUpdate/{xmid}/{ysje}", method = RequestMethod.GET)
    public Map<Object, Object> bathUpdate(@PathVariable Integer xmid, @PathVariable Double
            ysje, @RequestParam String spzt) {
        Map<Object, Object> res = new HashMap<>();
        //系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        res.put("userInfo", userInfo);

        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid.toString());
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            PrjApproverecord prjApproverecord = approveList.get(approveList.size() - 1);
            res.put("approveInfo", prjApproverecord);
        } else {
            PrjProject project = prjProjectService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(project.getZwmc());
            approveInfo.setZt("数据不匹配");
            res.put("approveInfo", approveInfo);
        }

        return res;
    }


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

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

    @RequestMapping(value = "/forAddBudget", method = RequestMethod.GET)
    public String forAddBudget(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);

        return "prjproject/add_annualbudget";
    }

    @RequestMapping(value = "/init_kybg", method = RequestMethod.GET)
    public String init_kybg(Model model, @RequestParam String xmlx) {
        model.addAttribute("xmlx", xmlx);
        return "prjproject/list_kybg";
    }

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_myProject", method = RequestMethod.GET)
    public String init_myProject(Model model) {
        //审批状态
        List<Map<String, String>> dictList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("dictList", dictList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        model.addAttribute("userId", getSysUserId());

        return "prjproject/list_myproject";
    }

    /**
     * 数据查询(我的项目)
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_myproject", method = RequestMethod.POST)
    public BaseResult list_myproject(@RequestParam("page") Integer pageNum,
                                     @RequestParam("limit") Integer pageSize,
                                     @RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc,
                                     @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                     @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                     @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                     @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                     @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        SysUserInfo userInfo = getSysUserInfo();
        List<String> postName = sysUserInfoService.getPostNameByUserId(userInfo.getUserId());
        String post = "";
        if (postName.size() > 0) {
            for (int i = 0; i < postName.size(); i++) {
                if (PostInfoEnum.KYZZ.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("zwmc", zwmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("spzt", spzt);
        paraMap.put("xmlx", xmlx);
        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }
        }

        List<PrjProject> list = prjProjectService.getProjectList(paraMap);

        PageInfo<PrjProject> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjProject> 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_deptProject", method = RequestMethod.GET)
    public String init_deptProject(Model model) {
        //审批状态
        List<Map<String, String>> dictList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("dictList", dictList);
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);

        model.addAttribute("userId", getSysUserId());

        return "prjproject/list_deptproject";
    }

    /**
     * 数据查询(部门项目)
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_deptproject", method = RequestMethod.POST)
    public BaseResult list_deptproject(@RequestParam("page") Integer pageNum,
                                       @RequestParam("limit") Integer pageSize,
                                       @RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc,
                                       @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                                       @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                                       @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                                       @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                                       @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        SysUserInfo userInfo = getSysUserInfo();
        List<String> postName = sysUserInfoService.getPostNameByUserId(userInfo.getUserId());
        String post = "";
        if (postName.size() > 0) {
            for (int i = 0; i < postName.size(); i++) {
                if (PostInfoEnum.KYZZ.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("zwmc", zwmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("spzt", spzt);
        paraMap.put("xmlx", xmlx);

        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("deptId", userInfo.getDeptId());
            }
        }

        List<PrjProject> list = prjProjectService.getProjectList(paraMap);

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

    /**
     * 导入excel
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping("importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        if (file.isEmpty()) {
            return "文件为空！";
        }
        try {
            List<PrjMember> list = ExcelPoiUtil.memberImport(file);
            //循环展示导入的数据，实际应用中应该校验并存入数据库
//            for (Excel excel : list) {
//                System.out.println("ID:"+excel.getId()+" "+"姓名："+excel.getName()+" "+"年龄："+excel.getAge()+" "+"日期"+excel.getCreateDate());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "导入成功!";
    }

    /**
     * 生成word
     *
     * @param id
     */
    @ApiOperation(value = "导出任务书word", notes = "导出任务书word")
    @RequestMapping(value = "/exportWord/{id}", method = RequestMethod.GET)
    public void exportWord(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer id) throws
            IOException, JSONException {

        String fileName = GenAndMergerWord(id);
        String cleanId = fileName.replaceAll("[/\\\\:*?|]", ".");
        String clean = cleanId.replaceAll("[\"<>]", "'");
        String outFile = uploadFolder + "/template/temp/" + clean + ".docx";
        if (!fileName.isEmpty() && fileName != "") {
            File dwFile = new File(outFile);
            InputStream fis = new BufferedInputStream(new FileInputStream(outFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".docx").getBytes(), "ISO-8859-1"));
            response.addHeader("Content-Length", "" + dwFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }
    }

    private String GenAndMergerWord(Integer id) throws IOException, JSONException {
        PrjProject report = prjProjectService.queryById(id);
        String zwmc = report.getZwmc();

        String templatePath = uploadFolder + "/template";
        Map<String, Object> mapData = getWord(report);
        String cleanId = String.valueOf(report.getId()).replaceAll("[/\\\\:*?|]", ".");
        String clean = cleanId.replaceAll("[\"<>]", "'");
        String taskDoc = uploadFolder + "/template/temp/zwmc_" + clean + ".docx";

        taskDoc = WordUtils.genWord(taskDoc, templatePath, "task.ftl", mapData);


        String cleanId1 = zwmc.replaceAll("[/\\\\:*?|]", ".");
        String clean1 = cleanId1.replaceAll("[\"<>]", "'");
        String outFile = uploadFolder + "/template/temp/" + clean1 + ".docx";
        List<String> list = new ArrayList<>();
        list.add(taskDoc);
        boolean ret = WordUtils.appendDocx(outFile, list);

        File file = new File(taskDoc);
        if (file.exists() && file.isFile())
            file.delete();
        if (ret)
            return zwmc;
        else
            return "";
    }

    /***
     * 生成word
     * @param report
     * @return
     */
    public Map<String, Object> getWord(PrjProject report) {
        Map<String, String> paraMap = new HashMap<>();
        Integer id = report.getId();
        paraMap.put("xm", id.toString());

        List<PrjCompletecompany> wclist = prjCompletecompanyService.getCompanyList(paraMap);
        List<PrjUndertakecompany> cdlist = prjUndertakecompanyService.getXmUtCompanyList(paraMap);
        List<PrjFeescheme> czlist = prjFeeschemeService.getFeeSchemeList(paraMap);
        List<PrjMember> memberList = prjMemberService.getMemberInfoList(id);
        List<PrjBudget> budgetList = prjBudgetService.getBudgetList(id);
        List<PrjSubtopic> subtopicList = prjSubtopicService.getSubtopicList(id);
        List<PrjContacts> gldwList = prjContactsService.getContactList(id);

        Map<String, Object> data = new HashMap<String, Object>();

        data = getBaseInfo(memberList, cdlist, report, data);
        data = getXmCddw(budgetList, wclist, data);
        data = getXmjfys(budgetList, wclist, data);
        data = getProjectSubject(subtopicList, data);
        data = GetCzfaList(czlist, data);
        data = getKtFzrAndGzr(memberList, data);
        data = getXmgldw(gldwList, data);
        data = getXmcddwLast(gldwList, data);
        data = getXmczdw(czlist, data);

        return data;
    }

    /***
     * 课题负责人与主要工作人
     * @param memberList
     * @param data
     * @return
     */
    private Map<String, Object> getKtFzrAndGzr(List<PrjMember> memberList, Map<String, Object> data) {
        List<PrjMember> xmfzrList = new ArrayList<>();
        List<PrjMember> fzrList = new ArrayList<>();
        List<PrjMember> gzrList = new ArrayList<>();
        PrjProject prjProject = new PrjProject();
        if (memberList != null) {
            if (memberList.get(0).getXm() != null && memberList.get(0).getRy() != null) {
                prjProject = prjProjectService.queryById(memberList.get(0).getXm());
                String dkyfzr = prjProject.getDkyfzr();
                String[] split = dkyfzr.split(",");
                for (int i = 0; i < split.length; i++) {
                    int i1 = Integer.parseInt(split[i]);
                    BasePerson basePerson = basePersonService.queryById(i1);
                    if (basePerson != null) {
                        PrjMember prjMember = prjMemberService.queryByRyAndXm(basePerson.getXm(), memberList.get(0).getXm());
                        xmfzrList.add(prjMember);
                    }
                }
            }
        }
        for (PrjMember member : memberList) {
//            if(member.getRyxm().indexOf("拟合作")<0){
            if (member.getXmjs().equals("1") || member.getXmjs().equals("2"))
                fzrList.add(member);
            else
                gzrList.add(member);
//            }
        }
        List<Map<String, Object>> ktfzrList0 = getFzrInfo(xmfzrList, 5);
        List<Map<String, Object>> ktfzrList = getFzrInfo(fzrList, 1);
        List<Map<String, Object>> ktfzrList1 = getFzrInfo(gzrList, 0);
        if (ktfzrList != null) {
            ktfzrList0.addAll(ktfzrList);
        }
        if (ktfzrList1 != null) {
            ktfzrList0.addAll(ktfzrList1);
        }
        data.put("ktfzrList", ktfzrList0);
        return data;
    }

    /***
     * 基本信息
     * @param memberList
     * @param cdlist
     * @param report
     * @param data
     * @return
     */
    private Map<String, Object> getBaseInfo(List<PrjMember> memberList,
                                            List<PrjUndertakecompany> cdlist,
                                            PrjProject report, Map<String, Object> data) {
        List<Map<String, Object>> personList = new ArrayList<>();

        if (memberList != null && memberList.size() > 0) {
            for (int i = 0, j = 0; i < memberList.size(); i++) {
                Map<String, Object> personMap = new HashMap<>();
                BasePerson person;
                if (memberList.get(i).getRy() != null && "1".equals(memberList.get(i).getXmjs())) {
                    person = basePersonService.queryById(memberList.get(i).getRy());
                    if (null != person) {
                        if (person.getZc() != null) {
                            BaseTitle title = baseTitleService.queryById(person.getZc());
                            if (title != null) {
                                if (title.getName() != null) {
                                    person.setZc(title.getName().toString());
                                } else {
                                    person.setZc("");
                                }
                            } else {
                                person.setZc("");
                            }
                        } else {
                            person.setZc("");
                        }


                        if (j == 0) {
                            String xmfzrxm = person.getXm();
                            if (xmfzrxm != null)
                                data.put("xmfzrxm", xmfzrxm);
                            else
                                data.put("xmfzrxm", "");
                            String xmfzrdw = person.getDwmc();
                            if (xmfzrdw != null)
                                data.put("xmfzrdw", xmfzrdw);
                            else
                                data.put("xmfzrdw", "");

                            String xmfzrxb = person.getXb();
                            if (xmfzrxb != null) {
                                if (xmfzrxb.equals("male"))
                                    xmfzrxb = "男";
                                if (xmfzrxb.equals("female"))
                                    xmfzrxb = "女";
                                data.put("xmfzrxb", xmfzrxb);
                            } else
                                data.put("xmfzrxb", "");
                            Date csrq = person.getCsrq();
                            String xmfzrnl = "";
                            if (csrq != null) {
                                Integer nl = (new Date()).getYear() - csrq.getYear() + 1;
                                xmfzrnl = nl.toString();
                            }
                            data.put("xmfzrnl", xmfzrnl);

                            String xmfzrzy = person.getZyzc();
                            if (xmfzrzy != null)
                                data.put("xmfzrzy", xmfzrzy);
                            else
                                data.put("xmfzrzy", "");

                            String xmfzrzc = person.getZc();
                            if (xmfzrzc != null)
                                data.put("xmfzrzc", xmfzrzc);
                            else
                                data.put("xmfzrzc", "");
                            j = j + 1;
                        } else if (j > 0) {
                            String xmfzrxm = person.getXm();
                            if (xmfzrxm != null)
                                personMap.put("xmfzrxm", xmfzrxm);
                            else
                                personMap.put("xmfzrxm", "");
                            String xmfzrdw = person.getDwmc();
                            if (xmfzrdw != null)
                                personMap.put("xmfzrdw", xmfzrdw);
                            else
                                personMap.put("xmfzrdw", "");

                            String xmfzrxb = person.getXb();
                            if (xmfzrxb != null) {
                                if (xmfzrxb.equals("male"))
                                    xmfzrxb = "男";
                                if (xmfzrxb.equals("female"))
                                    xmfzrxb = "女";
                                personMap.put("xmfzrxb", xmfzrxb);
                            } else
                                personMap.put("xmfzrxb", "");
                            Date csrq = person.getCsrq();
                            String xmfzrnl = "";
                            if (csrq != null) {
                                Integer nl = (new Date()).getYear() - csrq.getYear() + 1;
                                xmfzrnl = nl.toString();
                            }
                            personMap.put("xmfzrnl", xmfzrnl);

                            String xmfzrzy = person.getZyzc();
                            if (xmfzrzy != null)
                                personMap.put("xmfzrzy", xmfzrzy);
                            else
                                personMap.put("xmfzrzy", "");

                            String xmfzrzc = person.getZc();
                            if (xmfzrzc != null)
                                personMap.put("xmfzrzc", xmfzrzc);
                            else
                                personMap.put("xmfzrzc", "");
                            personList.add(personMap);
                        }
                    } else {
                        data.put("xmfzrxm", "");
                        data.put("xmfzrdw", "");
                        data.put("xmfzrxb", "");
                        data.put("xmfzrnl", "");
                        data.put("xmfzrzy", "");
                        data.put("xmfzrzc", "");
                    }
                }
            }
        } else {
            data.put("xmfzrxm", "");
            data.put("xmfzrdw", "");
            data.put("xmfzrxb", "");
            data.put("xmfzrnl", "");
            data.put("xmfzrzy", "");
            data.put("xmfzrzc", "");
        }

        String zwmc = report.getZwmc();
        if (zwmc != null)
            data.put("zwmc", zwmc);
        else
            data.put("zwmc", "");

        if (cdlist != null && cdlist.size() > 0) {
            String zycddw = cdlist.get(0).getDwmc();
            int cddws = cdlist.size();
            data.put("cddws", cddws);
            if (zwmc != null)
                data.put("zycddw", zycddw);
        } else {
            data.put("zycddw", "");
            data.put("cddws", "");
        }

        if (report.getQs() != null && report.getWc() != null) {

            String qzsj = dateFormat.format(report.getQs()) + "  至  " + dateFormat.format(report.getWc());
            data.put("qzsj", qzsj);
            String ssqx = dateFormat1.format(report.getQs()) + "~" + dateFormat1.format(report.getWc());
            data.put("ssqx", ssqx);
        } else {
            data.put("qzsj", "");
            data.put("ssqx", "");
        }

        Integer yjryzrs = report.getZrs();
        if (yjryzrs != null)
            data.put("yjryzrs", yjryzrs);
        else
            data.put("yjryzrs", "");

        Integer gjzc = report.getGjzc();
        if (gjzc != null)
            data.put("gjzc", gjzc);
        else
            data.put("gjzc", "");

        Integer zjzc = report.getZjzc();
        if (zjzc != null)
            data.put("zjzc", zjzc);
        else
            data.put("zjzc", "");

        Integer cjzc = report.getCjzc();
        if (cjzc != null)
            data.put("cjzc", cjzc);
        else
            data.put("cjzc", "");

        Integer yjs = report.getYjs();
        if (yjs != null)
            data.put("yjs", yjs);
        else
            data.put("yjs", "");

        String yjnr = report.getYjnrjkhzb();
        if (yjnr != null) {
            String s = WordUtils.XMLOrHTMLEnc(yjnr);
            data.put("yjnr", s);
        } else
            data.put("yjnr", "");

        String ygwtsm = report.getYgwtsm();
        if (ygwtsm != null)
            data.put("ygwtsm", ygwtsm);
        else
            data.put("ygwtsm", "");

        data.put("personList", personList);
        return data;
    }

    /***
     * 经费预算
     * @param budgetList
     * @param wclist
     * @param data
     * @return
     */
    private Map<String, Object> getXmjfys(List<PrjBudget> budgetList,
                                          List<PrjCompletecompany> wclist,
                                          Map<String, Object> data) {

        String zjf = "";
        String dwTmp = "<w:tc><w:tcPr><w:tcW w:w=\"1230\" w:type=\"dxa\"/>" +
                "       <w:tcBorders><w:top w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"000000\"/>" +
                "       <w:left w:val=\"nil\"/><w:bottom w:val=\"single\" w:sz=\"6\" w:space=\"0\" w:color=\"000000\"/>" +
                "       <w:right w:val=\"single\" w:sz=\"6\" w:space=\"0\" w:color=\"000000\"/>" +
                "       </w:tcBorders><w:vAlign w:val=\"center\"/></w:tcPr>" +
                "       <w:p w:rsidR=\"007C4A48\" w:rsidRDefault=\"007C4A48\" w:rsidP=\"007C4A48\">" +
                "       <w:pPr><w:widowControl/><w:jc w:val=\"center\"/><w:rPr>" +
                "       <w:rFonts w:ascii=\"仿宋\" w:eastAsia=\"仿宋\" w:hAnsi=\"仿宋\"/>" +
                "       <w:kern w:val=\"0\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/></w:rPr></w:pPr>\n" +
                "       <w:r><w:rPr><w:rFonts w:ascii=\"华文宋体\" w:eastAsia=\"华文宋体\" w:hAnsi=\"华文宋体\" w:hint=\"eastAsia\"/>" +
                "       <w:kern w:val=\"0\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/></w:rPr>" +
                "       <w:t>xxxxxx</w:t></w:r></w:p></w:tc>";

        List<Map<String, Object>> jfysdwList = new ArrayList<>();
//        int j = 0;
        for (int i = 0; i < wclist.size(); i++) {
            Map<String, Object> dwMap = new HashMap<>();
            PrjCompletecompany cp = wclist.get(i);
            if (cp.getDwmc() != null) {
                if (newCddwList != null) {
                    dwMap.put("mc", newCddwList.get(i));
                } else {
                    dwMap.put("mc", "");
                }
//                if ("国网陕西省电力公司".equals(cp.getDwmc()) || "国网陕西省电力有限公司".equals(cp.getDwmc()) || "国网陕西省电力公司电力科学研究院".equals(cp.getDwmc()) || "国网陕西省电力有限公司电力科学研究院".equals(cp.getDwmc())) {
//                    dwMap.put("mc", cp.getDwmc());
//                } else {
//                    dwMap.put("mc", "拟合作单位" + (j + 1));
//                    j++;
//                }
            } else
                dwMap.put("mc", "");
            jfysdwList.add(dwMap);
        }
        data.put("jfysdwList", jfysdwList);

        List<Map<String, Object>> jfysList = new ArrayList<>();
        if (budgetList != null) {
            int idx = -1;
            for (int i = 0; i < budgetList.size(); i++) {
                Map<String, Object> jfMap = new HashMap<>();

                PrjBudget obj = budgetList.get(i);
                if (obj.getFj() == null || obj.getFj().isEmpty()) {
                    if (obj.getYsje() != null) {
                        String format = String.format("%.2f", obj.getYsje());
                        DecimalFormat dt = new DecimalFormat("0.##");
                        zjf = dt.format(Double.parseDouble(format));
                        idx = i;
                    }
                }
                if (obj.getMc() != null)
                    jfMap.put("mc", obj.getMc());
                else
                    jfMap.put("mc", "");
                if (obj.getYsje() != null)
                    jfMap.put("ysje", String.format("%.2f", obj.getYsje()));
                else
                    jfMap.put("ysje", "");
//                if (obj.getBz() != null)
////                    jfMap.put("bz", obj.getBz());
////                else
////                    jfMap.put("bz", "");

                String dwjf = "";
                if (wclist.size() >= 10) {
                    String dw10 = dwTmp;
                    String _replace = "";
                    if (obj.getDw10() != null)
                        _replace = String.format("%.2f", obj.getDw10());
                    dwjf = dwjf.replace("xxxxxx", _replace);
                }
                if (wclist.size() >= 9) {
                    String dw9 = dwTmp;
                    String _replace = "";
                    if (obj.getDw9() != null)
                        _replace = String.format("%.2f", obj.getDw9());
                    dwjf = dw9.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 8) {
                    String dw8 = dwTmp;
                    String _replace = "";
                    if (obj.getDw8() != null)
                        _replace = String.format("%.2f", obj.getDw8());
                    dwjf = dw8.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 7) {
                    String dw7 = dwTmp;
                    String _replace = "";
                    if (obj.getDw7() != null)
                        _replace = String.format("%.2f", obj.getDw7());
                    dwjf = dw7.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 6) {
                    String dw6 = dwTmp;
                    String _replace = "";
                    if (obj.getDw6() != null)
                        _replace = String.format("%.2f", obj.getDw6());
                    dwjf = dw6.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 5) {
                    String dw5 = dwTmp;
                    String _replace = "";
                    if (obj.getDw5() != null)
                        _replace = String.format("%.2f", obj.getDw5());
                    dwjf = dw5.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 4) {
                    String dw4 = dwTmp;
                    String _replace = "";
                    if (obj.getDw4() != null)
                        _replace = String.format("%.2f", obj.getDw4());
                    dwjf = dw4.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 3) {
                    String dw3 = dwTmp;
                    String _replace = "";
                    if (obj.getDw3() != null)
                        _replace = String.format("%.2f", obj.getDw3());
                    dwjf = dw3.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 2) {
                    String dw2 = dwTmp;
                    String _replace = "";
                    if (obj.getDw2() != null)
                        _replace = String.format("%.2f", obj.getDw2());
                    dwjf = dw2.replace("xxxxxx", _replace) + dwjf;
                }
                if (wclist.size() >= 1) {
                    String dw1 = dwTmp;
                    String _replace = "";
                    if (obj.getDw1() != null)
                        _replace = String.format("%.2f", obj.getDw1());
                    dwjf = dw1.replace("xxxxxx", _replace) + dwjf;
                }
                jfMap.put("dw", dwjf);
                jfysList.add(jfMap);
            }
            if (idx != -1) {
                Map<String, Object> zMap = jfysList.get(idx);
                jfysList.remove(idx);
                jfysList.add(zMap);
            }
        }
        data.put("jfysList", jfysList);
        data.put("zjf", zjf);
        return data;
    }

    /***
     * 获取项目课题
     * @param subtopicList
     * @param data
     * @return
     */
    private Map<String, Object> getProjectSubject
    (List<PrjSubtopic> subtopicList, Map<String, Object> data) {
        List<Map<String, Object>> ktList = new ArrayList<>();
        List<Map<String, Object>> subKtList = new ArrayList<>();
        List<Map<String, Object>> xmjdjhList = new ArrayList<>();
        List<Map<String, Object>> ktjdjhykhyqList = new ArrayList<>();
        for (int i = 0; i < subtopicList.size(); i++) {
            PrjSubtopic obj = subtopicList.get(i);
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> mapkt0 = new HashMap<>();
            mapkt0.put("mc", "");
            mapkt0.put("yjnr", "");
            mapkt0.put("cddw", "");
            mapkt0.put("jf", "");
            Map<String, Object> mapplan = new HashMap<>();
            int xh = i + 1;
            map.put("xh", xh);
            mapplan.put("xh", xh);
            if (obj.getKtmc() != null) {
                map.put("mc", obj.getKtmc());
                mapplan.put("ktmc", obj.getKtmc());
            } else {
                map.put("mc", "");
                mapplan.put("ktmc", "");
            }
            if (obj.getId() != null) {
                List<PrjDivisioncompany> companyList = prjDivisioncompanyService.getCompanyList(obj.getId());
                if (companyList != null) {
                    for (int j = 0; j < companyList.size(); j++) {
                        Map<String, Object> mapkt = new HashMap<>();
                        String zyyjnr = companyList.get(j).getZyyjnr();
                        String dwmc = companyList.get(j).getDwmc();
                        Double jf = companyList.get(j).getJf();
                        if (obj.getKtmc() != null) {
                            mapkt.put("mc", obj.getKtmc());
                        } else {
                            mapkt.put("mc", "");
                        }
                        if (j == 0)
                            mapkt.put("merge", "<w:vMerge w:val=\"restart\"/>");
                        else
                            mapkt.put("merge", "<w:vMerge/>");
                        if (zyyjnr != null) {
                            mapkt.put("yjnr", zyyjnr);
                        } else {
                            mapkt.put("yjnr", "");
                        }
                        if (dwmc != null) {
                            if (newCddwList != null && oldCddwList != null) {
                                for (int k = 0; k < oldCddwList.size(); k++) {
                                    if ((oldCddwList.get(k)).equals(dwmc.trim())) {
                                        if (newCddwList.get(k) != null) {
                                            mapkt.put("cddw", newCddwList.get(k));
                                        } else {
                                            mapkt.put("cddw", "");
                                        }
                                    }
                                    if (mapkt.get("cddw") == null) {
                                        mapkt.put("cddw", dwmc);
                                    }
                                }
                            } else {
                                mapkt.put("cddw", "");
                            }
                        } else {
                            mapkt.put("cddw", "");
                        }
                        if (jf != null) {
                            mapkt.put("jf", jf);
                        } else {
                            mapkt.put("jf", "");
                        }

                        subKtList.add(mapkt);
                    }
                } else {
                    subKtList.add(mapkt0);
                }
            } else {
                subKtList.add(mapkt0);
            }
            if (obj.getQssj() != null && obj.getJssj() != null) {
                String qzsj = dateFormat1.format(obj.getQssj()) + "~" + dateFormat1.format(obj.getJssj());
                mapplan.put("qzsj", qzsj);
            } else
                mapplan.put("qzsj", "");

            BasePerson bp = basePersonService.queryById(obj.getFzr());
            if (bp != null && bp.getXm() != null) {
                map.put("fzr", bp.getXm());
            } else {
                map.put("fzr", "");
            }

            if (bp != null && bp.getDwmc() != null) {
                map.put("dw", bp.getDwmc());
            } else {
                map.put("dw", "");
            }

            ktList.add(map);
            xmjdjhList.add(mapplan);

            List<PrjSubtopicplan> subPlanList = prjSubtopicplanService.getSubtopicPlanList(obj.getId());

            if (subPlanList != null) {
                for (int j = 0; j < subPlanList.size(); j++) {
                    Map<String, Object> submapplan = new HashMap<>();
                    PrjSubtopicplan objPlan = subPlanList.get(j);
                    if (obj.getKtmc() != null) {
                        submapplan.put("mc", obj.getKtmc());
                    } else {
                        submapplan.put("mc", "");
                    }
                    if (j == 0)
                        submapplan.put("merge", "<w:vMerge w:val=\"restart\"/>");
                    else
                        submapplan.put("merge", "<w:vMerge/>");
                    if (objPlan.getQssj() != null && objPlan.getJssj() != null) {
                        String qzsj = dateFormat1.format(objPlan.getQssj()) + "~" + dateFormat1.format(objPlan.getJssj());
                        submapplan.put("qzsj", qzsj);
                    } else
                        submapplan.put("qzsj", "");

                    if (objPlan.getYjnr() != null)
                        submapplan.put("yjnr", objPlan.getYjnr());
                    else
                        submapplan.put("yjnr", "");

                    if (objPlan.getKhzb() != null)
                        submapplan.put("khzb", objPlan.getKhzb());
                    else
                        submapplan.put("khzb", "");

                    ktjdjhykhyqList.add(submapplan);
                }
            }
        }
        data.put("ktList", ktList);
        data.put("subKtList", subKtList);
        data.put("xmjdjhList", xmjdjhList);
        data.put("ktjdjhykhyqList", ktjdjhykhyqList);
        return data;
    }

    /***
     * 项目承担单位
     * @param data
     * @return
     */
    private Map<String, Object> getXmCddw
    (List<PrjBudget> budgetList, List<PrjCompletecompany> wclist, Map<String, Object> data) {
        List<Map<String, Object>> cddwList = new ArrayList<>();
        int mcjf = -1;
        if (budgetList != null) {
            for (int i = 0; i < budgetList.size(); i++) {
                PrjBudget obj = budgetList.get(i);

                if (obj.getMc() != null) {
                    if ("总计".equals(obj.getMc())) {
                        mcjf = i;
                    }
                }
            }
        }
        int f = 0;
        for (int i = 0; i < wclist.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            int xh = i + 1;
            map.put("xh", xh);
            PrjCompletecompany cp = wclist.get(i);
            if (cp.getDwmc() != null) {
                if ("国网陕西省电力公司".equals(cp.getDwmc()) || "国网陕西省电力有限公司".equals(cp.getDwmc()) || "国网陕西省电力公司电力科学研究院".equals(cp.getDwmc()) || "国网陕西省电力有限公司电力科学研究院".equals(cp.getDwmc())) {
                    map.put("mc", cp.getDwmc());
                    oldCddwList.add(cp.getDwmc());
                    newCddwList.add(cp.getDwmc());
                } else {
                    oldCddwList.add(cp.getDwmc());
                    map.put("mc", "拟合作单位" + (f + 1));
                    newCddwList.add("拟合作单位" + (f + 1));
                    f++;
                }
            } else
                map.put("mc", "");
            String jf = "";
            if (mcjf > -1) {
                switch (i) {
                    case 0:
                        if (budgetList.get(mcjf).getDw1() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw1());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 1:
                        if (budgetList.get(mcjf).getDw2() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw2());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 2:
                        if (budgetList.get(mcjf).getDw3() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw3());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 3:
                        if (budgetList.get(mcjf).getDw4() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw4());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 4:
                        if (budgetList.get(mcjf).getDw5() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw5());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 5:
                        if (budgetList.get(mcjf).getDw6() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw6());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 6:
                        if (budgetList.get(mcjf).getDw7() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw7());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 7:
                        if (budgetList.get(mcjf).getDw8() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw8());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 8:
                        if (budgetList.get(mcjf).getDw9() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw9());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    case 9:
                        if (budgetList.get(mcjf).getDw10() != null) {
                            String format = String.format("%.2f", budgetList.get(mcjf).getDw10());
                            DecimalFormat dt = new DecimalFormat("0.##");
                            jf = dt.format(Double.parseDouble(format));
                        }
                        break;
                    default:
                        System.out.println("flagflag:" + mcjf);
                        break;
                }
                map.put("jf", jf);
            }
            cddwList.add(map);
        }
        data.put("cddwList", cddwList);
//        List<Map<String, Object>> cddwList = new ArrayList<>();
//        for (int i = 0; i < cdlist.size(); i++) {
//            PrjUndertakecompany obj = cdlist.get(i);
//            Map<String, Object> map = new HashMap<>();
//            int xh = i + 1;
//            map.put("xh", xh);
//            if (obj.getDwmc() != null)
//                map.put("mc", obj.getDwmc());
//            else
//                map.put("mc", "");
//            String jf = "";
//            if (obj.getSkje() != null) {
//                jf = String.format("%.2f", obj.getSkje());
//            }
//            map.put("jf", jf);
//            cddwList.add(map);
//        }
        return data;
    }

    /***
     * 出资方案
     * @param czlist
     * @param data
     * @return
     */
    private Map<String, Object> GetCzfaList(List<PrjFeescheme> czlist, Map<String, Object> data) {
        List<Map<String, Object>> czfajzfjhList = new ArrayList<>();
        String czdw = "";
        double czjeTotal = 0;
        Integer czYear = 0;
        Integer idx = 1;
        for (int i = 0; i < czlist.size(); i++) {
            List<Map<String, Object>> subList = new ArrayList<>();
            Integer _czYear = 0;
            Map<String, Object> czfaMap = new HashMap<>();
            PrjFeescheme feeScheme = czlist.get(i);

            if (feeScheme.getCzje() != null)
                czjeTotal += feeScheme.getCzje();

            if (feeScheme.getNf() != null) {
                czfaMap.put("year", feeScheme.getNf().toString());
                _czYear = feeScheme.getNf();
            } else {
                czfaMap.put("year", "");
                _czYear = 0;
            }
            String strMerge = "<w:vMerge w:val=\"restart\"/>";

            if (feeScheme.getDwmc() != null)
                czdw += "、" + feeScheme.getDwmc();
            if (!czYear.equals(_czYear)) {
                idx = 1;
                czYear = _czYear;
                czfaMap.put("flag", "1");
            } else {
                idx += 1;
                czfaMap.put("flag", "0");
            }
            List<PrjUndertakecompany> _underList = prjUndertakecompanyService.getUtCompanyList(feeScheme.getId());
            for (int j = 0; j < _underList.size(); j++) {
                Map<String, Object> subczfaMap = new HashMap<>();
                PrjUndertakecompany obj = _underList.get(j);
                if (feeScheme.getDwmc() != null) {
                    subczfaMap.put("czdw", feeScheme.getDwmc());
                } else
                    subczfaMap.put("czdw", "");

                subczfaMap.put("merge", strMerge);
                subczfaMap.put("xh", idx);

                if (feeScheme.getCzje() != null) {
                    subczfaMap.put("czje", String.format("%.2f", feeScheme.getCzje()));
                } else
                    subczfaMap.put("czje", "");

                if (obj.getDwmc() != null)
                    subczfaMap.put("cddw", obj.getDwmc());
                else
                    subczfaMap.put("cddw", "");

                if (obj.getSkje() != null)
                    subczfaMap.put("skje", String.format("%.2f", obj.getSkje()));
                else
                    subczfaMap.put("skje", "");

                subList.add(subczfaMap);
                strMerge = "<w:vMerge/>";
            }
            czfaMap.put("contentList", subList);
            czfajzfjhList.add(czfaMap);
        }
        data.put("czfajzfjhList", czfajzfjhList);

        if (czdw.length() > 1)
            czdw = czdw.substring(1);
        data.put("czdw", czdw);

        data.put("xmjfdx", MoneyToChineseUtil.convert(String.format("%.2f", czjeTotal * 10000)));
        data.put("xmjfxx", String.format("%.2f", czjeTotal * 10000));
        return data;
    }

    /***
     * 主要完成人员
     * @param list
     * @param personType
     * @return
     */

    int f1 = 0;

    private List<Map<String, Object>> getFzrInfo(List<PrjMember> list, int personType) {
        List<Map<String, Object>> ktfzrList = new ArrayList<>();
        String rylx = "项目负责人";
        if (personType == 5) {
            rylx = "项目负责人";
        } else if (personType == 1) {
            rylx = "课题负责人";
        } else {
            rylx = "主要工作人员";
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> ktfzrMap = new HashMap<>();
            PrjMember prjMember = list.get(i);
            if (i == 0)
                ktfzrMap.put("merger", "<w:vMerge w:val=\"restart\"/>");
            else
                ktfzrMap.put("merger", "<w:vMerge/>");

            ktfzrMap.put("rylx", rylx);

            if (prjMember != null) {
                if (prjMember.getBxmfg() != null)
                    ktfzrMap.put("xmfg", prjMember.getBxmfg());
                else
                    ktfzrMap.put("xmfg", "");

                if (prjMember.getTrgzzys() != null)
                    ktfzrMap.put("trgzzys", prjMember.getTrgzzys());
                else
                    ktfzrMap.put("trgzzys", "");

                BasePerson basePerson = basePersonService.queryById(prjMember.getRy());
                String fzrXm = "";
                String fzrCSNY = "";
                String fzrDW = "";
                String fzrZY = "";
                String fzrZC = "";
                if (basePerson != null) {
                    if (basePerson.getXm() != null)
                        fzrXm = basePerson.getXm();
                    if (basePerson.getCsrq() != null)
                        fzrCSNY = dateFormat1.format(basePerson.getCsrq());
                    if (basePerson.getZyzc() != null)
                        fzrZY = basePerson.getZyzc();
                    if (basePerson.getZcmc() != null)
                        fzrZC = basePerson.getZcmc();
                    if (basePerson.getXlmc() != null)
                        fzrZC += "  " + basePerson.getXlmc();
                    if (basePerson.getDwmc() != null)
                        fzrDW = basePerson.getDwmc();
                    if (newCddwList != null && oldCddwList != null) {
//                        for (int j = 0; j < oldCddwList.size(); j++) {
//                            if ((oldCddwList.get(j)).equals(basePerson.getDwmc())) {
//                                String gzdw = (String) newCddwList.get(j);
////                                    String sub1 = gzdw.substring(gzdw.length() - 1);
//                                String sub2 = gzdw.substring(0, gzdw.length() - 1);
////                                    String xm=sub2+"人员"+sub1;
//                                String xm = sub2 + "人员" + (f1 + 1);
//                                ktfzrMap.remove("xmfg");
//                                ktfzrMap.remove("trgzzys");
//                                ktfzrMap.remove("zcxl");
//                                ktfzrMap.remove("xm");
//                                ktfzrMap.remove("csny");
//                                ktfzrMap.remove("zytc");
//                                ktfzrMap.remove("gzdw");
//                                ktfzrMap.put("xmfg", "");
//                                ktfzrMap.put("trgzzys", "");
//                                fzrXm = xm;
//                                fzrZC = "";
//                                fzrCSNY = "";
//                                fzrZY = "";
//                                fzrDW = gzdw;
//                                f1++;
//                            }
//                        }
                    }
                }

                ktfzrMap.put("xm", fzrXm);
                ktfzrMap.put("zcxl", fzrZC);
                ktfzrMap.put("csny", fzrCSNY);
                ktfzrMap.put("zytc", fzrZY);
                ktfzrMap.put("gzdw", fzrDW);

                ktfzrList.add(ktfzrMap);
            } else {
                ktfzrMap.put("xmfg", "");
                ktfzrMap.put("trgzzys", "");
                ktfzrMap.put("xm", "");
                ktfzrMap.put("zcxl", "");
                ktfzrMap.put("csny", "");
                ktfzrMap.put("zytc", "");
                ktfzrMap.put("gzdw", "");

                ktfzrList.add(ktfzrMap);
            }
        }
        return ktfzrList;
    }

    /***
     * 项目出资单位
     * @param czdwList
     * @param data
     * @return
     */
    private Map<String, Object> getXmczdw(List<PrjFeescheme> czdwList, Map<String, Object> data) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < czdwList.size(); i++) {
            if (!list.contains(czdwList.get(i).getCzdw())) {
                list.add(czdwList.get(i).getCzdw());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> czfaMap = new HashMap<>();
            Integer dwId = list.get(i);

            BaseCompany baseCompany = baseCompanyService.queryById(dwId);
            Integer idx = i + 1;
            czfaMap.put("xh", idx);
            if (baseCompany == null) {
                czfaMap.put("lxr", "");
                czfaMap.put("mc", "");
                czfaMap.put("gddh", "");
                czfaMap.put("dzyj", "");
                czfaMap.put("yddh", "");
                czfaMap.put("yzbm", "");
                czfaMap.put("cz", "");
                czfaMap.put("yjdz", "");
                continue;
            }
            if (baseCompany.getLxrxm() != null)
                czfaMap.put("lxr", baseCompany.getLxrxm());
            else
                czfaMap.put("lxr", "");

            if (baseCompany.getMc() != null)
                czfaMap.put("mc", baseCompany.getMc());
            else
                czfaMap.put("mc", "");

            if (baseCompany.getGddh() != null)
                czfaMap.put("gddh", baseCompany.getGddh());
            else
                czfaMap.put("gddh", "");

            if (baseCompany.getDzyj() != null)
                czfaMap.put("dzyj", baseCompany.getDzyj());
            else
                czfaMap.put("dzyj", "");

            if (baseCompany.getYddh() != null)
                czfaMap.put("yddh", baseCompany.getYddh());
            else
                czfaMap.put("yddh", "");

            if (baseCompany.getYzbm() != null)
                czfaMap.put("yzbm", baseCompany.getYzbm());
            else
                czfaMap.put("yzbm", "");

            if (baseCompany.getCz() != null)
                czfaMap.put("cz", baseCompany.getCz());
            else
                czfaMap.put("cz", "");

            if (baseCompany.getTxdz() != null)
                czfaMap.put("yjdz", baseCompany.getTxdz());
            else
                czfaMap.put("yjdz", "");
            mapList.add(czfaMap);
        }
        data.put("xmczdwList", mapList);
        return data;
    }

    /***
     * 项目承担单位
     * @param cddwList
     * @param data
     * @return
     */
    private Map<String, Object> getXmcddwLast(List<PrjContacts> cddwList, Map<String, Object> data) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (cddwList == null) {
            Map<String, Object> czMap = new HashMap<>();
            czMap.put("lxr", "");
            czMap.put("mc", "");
            czMap.put("gddh", "");
            czMap.put("dzyj", "");
            czMap.put("yddh", "");
            czMap.put("yzbm", "");
            czMap.put("cz", "");
            czMap.put("yjdz", "");
            mapList.add(czMap);
            data.put("xmcddwList", mapList);
            return data;
        }
        for (int i = 0; i < cddwList.size(); i++) {
            Map<String, Object> czfaMap = new HashMap<>();
            PrjContacts prjContacts = cddwList.get(i);

            Integer idx = i + 1;

            if ("t3".equals(prjContacts.getLx())) {
                czfaMap.put("xh", idx);
                if (prjContacts.getLxrxm() != null)
                    czfaMap.put("lxr", prjContacts.getLxrxm());
                else
                    czfaMap.put("lxr", "");

                if (prjContacts.getDwmc() != null)
                    czfaMap.put("mc", prjContacts.getDwmc());
                else
                    czfaMap.put("mc", "");

                if (prjContacts.getGddh() != null)
                    czfaMap.put("gddh", prjContacts.getGddh());
                else
                    czfaMap.put("gddh", "");

                if (prjContacts.getDzyj() != null)
                    czfaMap.put("dzyj", prjContacts.getDzyj());
                else
                    czfaMap.put("dzyj", "");

                if (prjContacts.getYddh() != null)
                    czfaMap.put("yddh", prjContacts.getYddh());
                else
                    czfaMap.put("yddh", "");

                if (prjContacts.getYzbm() != null)
                    czfaMap.put("yzbm", prjContacts.getYzbm());
                else
                    czfaMap.put("yzbm", "");

                if (prjContacts.getCz() != null)
                    czfaMap.put("cz", prjContacts.getCz());
                else
                    czfaMap.put("cz", "");

                if (prjContacts.getYjdz() != null)
                    czfaMap.put("yjdz", prjContacts.getYjdz());
                else
                    czfaMap.put("yjdz", "");
                mapList.add(czfaMap);
            }
        }
//        List<Map<String, Object>> mapList = new ArrayList<>();
//        List<Integer> list = new ArrayList<>();
//        for (int i = 0; i < cddwList.size(); i++) {
//            if (!list.contains(cddwList.get(i).getDw())) {
//                list.add(cddwList.get(i).getDw());
//            }
//        }
//
//        for (int i = 0; i < list.size(); i++) {
//            Map<String, Object> czfaMap = new HashMap<>();
//            Integer dwId = list.get(i);
//
//            BaseCompany baseCompany = baseCompanyService.queryById(dwId);
//            Integer idx = i + 1;
//            czfaMap.put("xh", idx);
//            if (baseCompany == null) {
//                czfaMap.put("lxr", "");
//                czfaMap.put("mc", "");
//                czfaMap.put("gddh", "");
//                czfaMap.put("dzyj", "");
//                czfaMap.put("yddh", "");
//                czfaMap.put("yzbm", "");
//                czfaMap.put("cz", "");
//                czfaMap.put("yjdz", "");
//                continue;
//            }
//            if (baseCompany.getLxrxm() != null)
//                czfaMap.put("lxr", baseCompany.getLxrxm());
//            else
//                czfaMap.put("lxr", "");
//
//            if (baseCompany.getMc() != null)
//                czfaMap.put("mc", baseCompany.getMc());
//            else
//                czfaMap.put("mc", "");
//
//            if (baseCompany.getGddh() != null)
//                czfaMap.put("gddh", baseCompany.getGddh());
//            else
//                czfaMap.put("gddh", "");
//
//            if (baseCompany.getDzyj() != null)
//                czfaMap.put("dzyj", baseCompany.getDzyj());
//            else
//                czfaMap.put("dzyj", "");
//
//            if (baseCompany.getYddh() != null)
//                czfaMap.put("yddh", baseCompany.getYddh());
//            else
//                czfaMap.put("yddh", "");
//
//            if (baseCompany.getYzbm() != null)
//                czfaMap.put("yzbm", baseCompany.getYzbm());
//            else
//                czfaMap.put("yzbm", "");
//
//            if (baseCompany.getCz() != null)
//                czfaMap.put("cz", baseCompany.getCz());
//            else
//                czfaMap.put("cz", "");
//
//            if (baseCompany.getTxdz() != null)
//                czfaMap.put("yjdz", baseCompany.getTxdz());
//            else
//                czfaMap.put("yjdz", "");
//            mapList.add(czfaMap);
//        }
        data.put("xmcddwList", mapList);
        return data;
    }

    /***
     * 项目管理单位
     * @param xmgldwList
     * @param data
     * @return
     */
    private Map<String, Object> getXmgldw(List<PrjContacts> xmgldwList, Map<String, Object> data) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (xmgldwList == null) {
            Map<String, Object> czMap = new HashMap<>();
            czMap.put("lxr", "");
            czMap.put("mc", "");
            czMap.put("gddh", "");
            czMap.put("dzyj", "");
            czMap.put("yddh", "");
            czMap.put("yzbm", "");
            czMap.put("cz", "");
            czMap.put("yjdz", "");
            mapList.add(czMap);
            data.put("xmgldwList", mapList);
            return data;
        }
        for (int i = 0; i < xmgldwList.size(); i++) {
            Map<String, Object> czfaMap = new HashMap<>();
            PrjContacts prjContacts = xmgldwList.get(i);

            Integer idx = i + 1;
            if ("t1".equals(prjContacts.getLx())) {
                czfaMap.put("xh", idx);
                if (prjContacts.getLxrxm() != null)
                    czfaMap.put("lxr", prjContacts.getLxrxm());
                else
                    czfaMap.put("lxr", "");

                if (prjContacts.getDwmc() != null)
                    czfaMap.put("mc", prjContacts.getDwmc());
                else
                    czfaMap.put("mc", "");

                if (prjContacts.getGddh() != null)
                    czfaMap.put("gddh", prjContacts.getGddh());
                else
                    czfaMap.put("gddh", "");

                if (prjContacts.getDzyj() != null)
                    czfaMap.put("dzyj", prjContacts.getDzyj());
                else
                    czfaMap.put("dzyj", "");

                if (prjContacts.getYddh() != null)
                    czfaMap.put("yddh", prjContacts.getYddh());
                else
                    czfaMap.put("yddh", "");

                if (prjContacts.getYzbm() != null)
                    czfaMap.put("yzbm", prjContacts.getYzbm());
                else
                    czfaMap.put("yzbm", "");

                if (prjContacts.getCz() != null)
                    czfaMap.put("cz", prjContacts.getCz());
                else
                    czfaMap.put("cz", "");

                if (prjContacts.getYjdz() != null)
                    czfaMap.put("yjdz", prjContacts.getYjdz());
                else
                    czfaMap.put("yjdz", "");
                mapList.add(czfaMap);
            }
        }
        data.put("xmgldwList", mapList);
        return data;
    }

    /**
     * 在记录表中添加修改前的数据
     * @return
     */
    @RequestMapping(value = "/addPrjProjectRecord/{xmid}",method =RequestMethod.POST)
    @ResponseBody
    public BaseResult addBudgetRecord(@PathVariable  Integer xmid) {
//        1.获取年度预算明细列表中的数据
        List<PrjBudget> xgjl = prjBudgetService.getXGJL(xmid);
//        查询当前为第几次记录
        List<PrjProjectXgjl> xgjls = prjProjectXgjlService.getXGJL(xmid);
//        获取当前年度预算审批状态
        PrjProject prjProject = prjProjectService.queryById(xmid);
        int xh = xgjls.size()+1;
        List<PrjProjectXgjl> prjProjectXgjlList = new ArrayList<>();
        for (int i = 0; i < xgjl.size(); i++) {
            PrjProjectXgjl prjProjectXgjl= new PrjProjectXgjl();
            prjProjectXgjl.setXmid(xmid);
            prjProjectXgjl.setMc(xgjl.get(i).getMc());
            prjProjectXgjl.setXg(xgjl.get(i).getXg());
            prjProjectXgjl.setXgrq(new java.sql.Date(System.currentTimeMillis()).toString());
            prjProjectXgjl.setXh(xh);
            prjProjectXgjlList.add(prjProjectXgjl);
        }
        if (prjProject.getSpzt().equals("审批结束")){
            prjProjectXgjlService.batchinsertXGJL(prjProjectXgjlList);
            prjProjectService.updateSFXG(xmid);
        }
        return BaseResult.success("成功");
    }

    @Resource
    private StaBudgetapprovalService staBudgetapprovalService;
    @Resource
    private PrjAnnualbudgetdetailService prjAnnualbudgetdetailService;

    @ResponseBody
    @RequestMapping(value = "/byjlist/{nf}", method = RequestMethod.POST)
    public BaseResult byjlist(@RequestParam("page") Integer pageNum,
                              @RequestParam("limit") Integer pageSize,
                              @PathVariable("nf") String nf,
                              @RequestParam(required = false, defaultValue = "", value = "zwmc") String zwmc,
                              @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                              @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                              @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                              @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Map<String, String> maps = new HashMap<>();
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("zwmc", zwmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("nf", nf);
        List<PrjProject> list = prjProjectService.getByjProjectList(paraMap);
        for(int i = 0 ;i<list.size();i++){
            map.put("nys",list.get(i).getNys());
            maps.put("erpbh",list.get(i).getErpbh());
            maps.put("nf",nf);
            // 获取erpbh 根据ERP编号 查询 当前数据 的 备用金 传入参数 年份 及 erpbh
            // 获取年度预算表备用金
            System.out.println(map);
            Double p1 = prjAnnualbudgetdetailService.getByj(map).getByj()*10000;
            Double p2 = staBudgetapprovalService.getSqje(maps).getSqje();
            if (p1 != null){
                list.get(i).setByj(p1);
            }else {
                list.get(i).setByj(0.00);
            }
            if (p2 != null){
                list.get(i).setYsqbyj(p2);
            }else {
                list.get(i).setYsqbyj(0.00);
            }
            // 费用申请已申请备用金
            list.get(i).setYe(p1-p2);
        }
        PageInfo<PrjProject> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjProject> 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
     */
    @GetMapping("/viewRecord")
    public String viewRecord() {
        return "prjproject/view_record";
    }

    @ResponseBody
    @RequestMapping(value = "/redordData/{xmid}", method = RequestMethod.POST)
    public BaseResult spList(@PathVariable int xmid,
                             @RequestParam(value = "page", required = false, defaultValue = "1") int pageNum,
                             @RequestParam(value = "limit", required = false, defaultValue = "30") int pageSize
                           ) {
        PageHelper.startPage(pageNum, pageSize);
        List<PrjBudget> list = prjBudgetService.getXGJL(xmid);
        Map<String, List<PrjBudget>> treeMap = new HashMap<>();
        for (PrjBudget budget : list) {
            treeMap.computeIfAbsent(budget.getFj(), k -> new ArrayList<>()).add(budget);
        }
        List<PrjBudget> sortedList = new ArrayList<>();
        buildTree(treeMap, "", sortedList);

        PageInfo<PrjBudget> pageinfo = new PageInfo<>(sortedList);
        //取出查询结果
        List<PrjBudget> 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 = "/upssbm",method = RequestMethod.POST)
    public BaseResult upssbm(@RequestBody String formData){
        // 创建一个Object
            // 开始解析 formData 将其解析成 Prjproject 对象
        PrjProjects prjProjects = JsonTool.parseObject(formData,PrjProjects.class);
        PrjProjects pr = new PrjProjects();
        PrjProject prjProject = prjProjectService.queryById(prjProjects.getId());
        SysDeptInfo sysDeptInfo = sysDeptInfoService.queryById(prjProjects.getSsbmmc());
        // 获取当前系统时间
        Date data = new Date();
        // 转换时间格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 审批列表记录
        PrjApproverecord prjApproverecord = new PrjApproverecord();
        prjApproverecord.setTablename("prj_Project");
        prjApproverecord.setXmid(prjProjects.getId());
        prjApproverecord.setYj( "项目名称："+prjProjects.getXmmc()+",ERP编号："+prjProjects.getErpbh()+","+"'部门'从'"+
                prjProject.getSsbmmc()+"'转移至'"+sysDeptInfo.getDeptName()+"'电科院负责人从'"+prjProject.getDkyfzrxm()+"'转移为："
                +prjProjects.getDkyfzrxm() +",创建人从'"+
                prjProject.getCjrxm()+"'转移为："+
                prjProjects.getSqrxm()+",操作员："+
                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(prjProjects.getXmmc());
        prjApproverecord.setZt("已完成");
        prjApproverecord.setWc(true);
        int mun = prjApproverecordService.insert(prjApproverecord);
            if (mun > 0 ){
                pr.setSsbm(prjProjects.getSsbmmc());
                pr.setDkyfzr(prjProjects.getDkyfzr());
                pr.setCjr(prjProjects.getSqr());
                pr.setId(prjProjects.getId());
                int num = prjProjectService.updateZy(pr);
                if (num > 0){
                    return BaseResult.success("项目已成功转移!");
                }
            }
            // 审批列表增加
        return BaseResult.failure(-1,"项目转移失败！");
    }

    @RequestMapping(value = "/ViewXGSQ", method = RequestMethod.GET)
    public String ViewXGSQ(Model model) {

        return "prjproject/view_xgsq";
    }

    private static void buildTree(Map<String, List<PrjBudget>> treeMap, String parentFj, List<PrjBudget> sortedList) {
        List<PrjBudget> children = treeMap.get(parentFj);
        if (children != null) {
            for (PrjBudget child : children) {
                sortedList.add(child);
                buildTree(treeMap, child.getBm(), sortedList);
            }
        }
    }
}

