package com.liang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseController;
import com.liang.common.base.BaseResult;
import com.liang.common.enums.PostInfoEnum;
import com.liang.common.utils.ExcelPoiUtil;
import com.liang.common.utils.WordUtils;
import com.liang.entity.*;
import com.liang.service.*;
//import com.liang.vo.service.*;
import io.swagger.annotations.ApiOperation;
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.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Date;
import java.util.*;

/**
 * (StaFeasibilityreport)表控制层
 *
 * @author makejava
 * @since 2023-03-03 23:38:19
 */
@Controller
@RequestMapping("reportinfo")
public class StaFeasibilityreportController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaFeasibilityreportService staFeasibilityreportService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private BaseProjecttypeService projecttypeService;
    @Resource
    private StaDirectorService staDirectorService;
    @Resource
    private StaScheduleService staScheduleService;
    @Resource
    private BaseCompanyService baseCompanyService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private StaBudgetService staBudgetService;
    @Resource
    private SysUserInfoService sysUserInfoService;
    @Resource
    private CyyService cyyService;


    final static Logger logger = LoggerFactory.getLogger(StaFeasibilityreportController.class);

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

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

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

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

    /**
     * 页面初始化
     *
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("approveList", approveList);
        List<Map<String, String>> approvedList = sysDictInfoService.queryByCode("approved_status");
        model.addAttribute("approvedList", approvedList);

        model.addAttribute("browseRight", CheckPermissionInfo("myproject:reportlist"));
        model.addAttribute("addRight", true);
        model.addAttribute("delRight", true);
        model.addAttribute("editRight", true);
        model.addAttribute("auditRight", true);

        //当前用户ID
        model.addAttribute("userId", getSysUserId());

        return "reportinfo/list";
    }

    /**
     * 数据查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "MC") String mc,
                           @RequestParam(required = false, defaultValue = "", value = "SPZT") String spzt,
                           @RequestParam(required = false, defaultValue = "", value = "SSBMNAME") String ssbmName,
                           @RequestParam(required = false, defaultValue = "", value = "SQRQStart") String sqrq1,
                           @RequestParam(required = false, defaultValue = "", value = "SQRQEnd") String sqrq2,
                           @RequestParam(required = false, defaultValue = "", value = "YSP") String ysp,
                           @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("mc", mc);
        paraMap.put("spzt", spzt);
        paraMap.put("ssbmName", ssbmName);
        paraMap.put("sqrq1", sqrq1);
        paraMap.put("sqrq2", sqrq2);
        paraMap.put("ysp", ysp);
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);

        List<StaFeasibilityreport> staFeasibilityreport = staFeasibilityreportService.getReportInfoList(paraMap);

        PageInfo<StaFeasibilityreport> pageinfo = new PageInfo<>(staFeasibilityreport);
        // 取出查询结果
        List<StaFeasibilityreport> 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) {
        String fileUrl = "http://" +
                webfileip + ":" + webfileport + "/template/";
        model.addAttribute("mdhyyTemplate", fileUrl + "目的和意义.docx");
        model.addAttribute("yjspTemplate", fileUrl + "研究水平.docx");
        model.addAttribute("llsjyjTemplate", fileUrl + "理论实践依据.docx");
        model.addAttribute("yjnrTemplate", fileUrl + "研究内容.docx");
        model.addAttribute("cddwtjTemplate", fileUrl + "承担单位条件.docx");
        model.addAttribute("scyjTemplate", fileUrl + "审查意见.docx");
        model.addAttribute("fjTemplate", fileUrl + "附件.docx");
        model.addAttribute("ProjectRYTemplate", fileUrl + "可研报告完成人员.xlsx");

        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //登录用户(所属部门)
        SysUserInfo userInfo = sysUserInfoService.queryById(getSysUserId());
        String deptName = userInfo.getDeptName();
        if (userInfo.getDeptName1() != null)
            deptName = userInfo.getDeptName1() + " / " + deptName;
        if (userInfo.getDeptName2() != null)
            deptName = userInfo.getDeptName2() + " / " + deptName;
        userInfo.setDeptName(deptName);
        model.addAttribute("userInfo", userInfo);

        return "reportinfo/add";
    }

    /**
     * 修改页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        String fileUrl = "http://" +
                webfileip + ":" + webfileport + "/template/";
        model.addAttribute("mdhyyTemplate", fileUrl + "目的和意义.docx");
        model.addAttribute("yjspTemplate", fileUrl + "研究水平.docx");
        model.addAttribute("llsjyjTemplate", fileUrl + "理论实践依据.docx");
        model.addAttribute("yjnrTemplate", fileUrl + "研究内容.docx");
        model.addAttribute("cddwtjTemplate", fileUrl + "承担单位条件.docx");
        model.addAttribute("scyjTemplate", fileUrl + "审查意见.docx");
        model.addAttribute("fjTemplate", fileUrl + "附件.docx");
        model.addAttribute("ProjectRYTemplate", fileUrl + "可研报告完成人员.xlsx");

        StaFeasibilityreport report = staFeasibilityreportService.queryById(id);
        if (report.getMdhyy() == null || report.getMdhyy().isEmpty())
            report.setMdhyy("[]");
        if (report.getGnwyjspzs() == null || report.getGnwyjspzs().isEmpty())
            report.setGnwyjspzs("[]");
        if (report.getXmdllhsjyj() == null || report.getXmdllhsjyj().isEmpty())
            report.setXmdllhsjyj("[]");
        if (report.getXmyjnrhssfa() == null || report.getXmyjnrhssfa().isEmpty())
            report.setXmyjnrhssfa("[]");
        if (report.getXmcddwdtj() == null || report.getXmcddwdtj().isEmpty())
            report.setXmcddwdtj("[]");
        if (report.getScyjfj() == null || report.getScyjfj().isEmpty())
            report.setScyjfj("[]");
        if (report.getFj() == null || report.getFj().isEmpty())
            report.setFj("[]");
        if (report.getYgzmwj() == null || report.getYgzmwj().isEmpty())
            report.setYgzmwj("[]");
        BaseCompany company = baseCompanyService.queryById(report.getSqdw());
        if (company != null)
            report.setSqdwName(company.getMc());
        //登录用户(所属部门)
        SysUserInfo userInfo = sysUserInfoService.queryById(report.getCjr());
        String deptName = userInfo.getDeptName();
        if (userInfo.getDeptName1() != null)
            deptName = userInfo.getDeptName1() + " / " + deptName;
        if (userInfo.getDeptName2() != null)
            deptName = userInfo.getDeptName2() + " / " + deptName;
        report.setSsbmName(deptName);

        //项目负责人list转json字符串
        List<StaDirector> directorsList = staDirectorService.queryByZbId(report.getId());
        JSONArray directorArray = new JSONArray();
        for (StaDirector director : directorsList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("xh", director.getXh());
                jsonObject.put("xm", director.getXm());
                jsonObject.put("fzr", director.getFzr());
                jsonObject.put("dwmc", director.getDwmc());
                jsonObject.put("gddh", director.getGddh());
                directorArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        report.setStaDirectorList(directorArray.toString());

        //进度安排list转json字符串
        List<StaSchedule> staScheduleList = staScheduleService.queryByZbId(report.getId());
        JSONArray scheduleArray = new JSONArray();
        for (StaSchedule staSchedule : staScheduleList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("tempId", staSchedule.getId());
                jsonObject.put("yjnr", staSchedule.getYjnr());
                jsonObject.put("qssj", staSchedule.getQssj().toString());
                jsonObject.put("jssj", staSchedule.getJssj().toString());
                scheduleArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        report.setStaScheduleList(scheduleArray.toString());

        model.addAttribute("report", report);

        return "reportinfo/update";
    }


    /**
     * 修改页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        String fileUrl = "http://" + webfileip + ":" + webfileport + "/template/";
        model.addAttribute("mdhyyTemplate", fileUrl + "目的和意义.docx");
        model.addAttribute("yjspTemplate", fileUrl + "研究水平.docx");
        model.addAttribute("llsjyjTemplate", fileUrl + "理论实践依据.docx");
        model.addAttribute("yjnrTemplate", fileUrl + "研究内容.docx");
        model.addAttribute("cddwtjTemplate", fileUrl + "承担单位条件.docx");
        model.addAttribute("scyjTemplate", fileUrl + "审查意见.docx");
        model.addAttribute("fjTemplate", fileUrl + "附件.docx");
        model.addAttribute("ProjectRYTemplate", fileUrl + "可研报告完成人员.xlsx");

        StaFeasibilityreport report = staFeasibilityreportService.queryById(id);
            if (report.getMdhyy() == null || report.getMdhyy().isEmpty())
            report.setMdhyy("[]");
        if (report.getGnwyjspzs() == null || report.getGnwyjspzs().isEmpty())
            report.setGnwyjspzs("[]");
        if (report.getXmdllhsjyj() == null || report.getXmdllhsjyj().isEmpty())
            report.setXmdllhsjyj("[]");
        if (report.getXmyjnrhssfa() == null || report.getXmyjnrhssfa().isEmpty())
            report.setXmyjnrhssfa("[]");
        if (report.getXmcddwdtj() == null || report.getXmcddwdtj().isEmpty())
            report.setXmcddwdtj("[]");
        if (report.getScyjfj() == null || report.getScyjfj().isEmpty())
            report.setScyjfj("[]");
        if (report.getFj() == null || report.getFj().isEmpty())
            report.setFj("[]");
        if (report.getYgzmwj() == null || report.getYgzmwj().isEmpty())
            report.setYgzmwj("[]");
        BaseCompany company = baseCompanyService.queryById(report.getSqdw());
        if (company != null)
            report.setSqdwName(company.getMc());
        //登录用户(所属部门)
        SysUserInfo userInfo = sysUserInfoService.queryById(report.getCjr());
        String deptName = userInfo.getDeptName();
        if (userInfo.getDeptName1() != null)
            deptName = userInfo.getDeptName1() + " / " + deptName;
        if (userInfo.getDeptName2() != null)
            deptName = userInfo.getDeptName2() + " / " + deptName;
        report.setSsbmName(deptName);

        //项目负责人list转json字符串
        List<StaDirector> directorsList = staDirectorService.queryByZbId(report.getId());
        JSONArray directorArray = new JSONArray();
        for (StaDirector director : directorsList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("xh", director.getXh());
                jsonObject.put("xm", director.getXm());
                jsonObject.put("fzr", director.getFzr());
                jsonObject.put("dwmc", director.getDwmc());
                jsonObject.put("gddh", director.getGddh());
                directorArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        report.setStaDirectorList(directorArray.toString());

        //进度安排list转json字符串
        List<StaSchedule> staScheduleList = staScheduleService.queryByZbId(report.getId());
        JSONArray scheduleArray = new JSONArray();
        for (StaSchedule staSchedule : staScheduleList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("tempId", staSchedule.getId());
                jsonObject.put("yjnr", staSchedule.getYjnr());
                jsonObject.put("qssj", staSchedule.getQssj().toString());
                jsonObject.put("jssj", staSchedule.getJssj().toString());
                scheduleArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        report.setStaScheduleList(scheduleArray.toString());

        model.addAttribute("report", report);

        return "reportinfo/view";
    }

    /**
     * 修改页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/getDirectorList/{id}", method = RequestMethod.GET)
    public BaseResult getDirectorList(@PathVariable Integer id) {
        //项目负责人list转json字符串
        List<StaDirector> directorsList = staDirectorService.queryByZbId(id);
        JSONArray directorArray = new JSONArray();
        for (StaDirector director : directorsList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("xm", director.getXm());
                jsonObject.put("memo", "");
                jsonObject.put("fzr", director.getFzr());
                directorArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return BaseResult.success(directorArray);
    }

    /**
     * 添加菜单
     *
     * @return
     */
    @RequestMapping(value = "/addfzr", method = RequestMethod.GET)
    public String addfzr() {
        return "reportinfo/addfzr";
    }

    /**
     * 编辑菜单
     *
     * @return
     */
    @RequestMapping(value = "/updatefzr", method = RequestMethod.GET)
    public String updatefzr() {
        return "reportinfo/updatefzr";
    }

    /***
     * 新建可研报告
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(StaFeasibilityreport staFeasibilityreport) {

        staFeasibilityreport.setCjr(getSysUserId());
        staFeasibilityreport.setYsp(false);
        staFeasibilityreport.setSpzt("未提交");
        staFeasibilityreport.setCjrq(new Date(System.currentTimeMillis()));

        String mc = staFeasibilityreport.getMc();

        int num = staFeasibilityreportService.insert(staFeasibilityreport);
        if (num == -1) {
            return BaseResult.failure("新建可研报告'" + mc + "'失败，该报告已存在!");
        } else if (num == 0) {
            return BaseResult.failure("新建可研报告'" + mc + "'失败!");
        }

        //经费预算项插入
        staBudgetService.insertBatchByXmlx(staFeasibilityreport.getXmlx(), staFeasibilityreport.getId());

        //项目负责人批量插入
        try {
            JSONArray directorArray = new JSONArray(staFeasibilityreport.getStaDirectorList());
            List<StaDirector> staDirectorList = new ArrayList<>();
            for (int i = 0; i < directorArray.length(); i++) {
                JSONObject object = directorArray.getJSONObject(i);
                StaDirector staDirector = new StaDirector();
                staDirector.setZb(num);
//                String xh = String.format("%03d", Integer.parseInt(object.getString("LAY_TABLE_INDEX"))+1);
                staDirector.setXh(Integer.parseInt(object.getString("xh")));
                staDirector.setFzr(Integer.parseInt(object.getString("fzr")));
                staDirector.setXm(object.getString("xm"));
                staDirectorList.add(staDirector);
            }
            if (staDirectorList.size() > 0) {
                staDirectorService.insertBatch(staDirectorList);
            }
        } catch (JSONException e) {
            logger.error("项目负责人json转换异常！", e);
        } catch (Exception e) {
            logger.error("新建可研报告项目负责人出现异常！", e);
        }
        //项目进度安排批量插入
        try {
            JSONArray scheduleArray = new JSONArray(staFeasibilityreport.getStaScheduleList());
            List<StaSchedule> staScheduleList = new ArrayList<>();
            for (int i = 0; i < scheduleArray.length(); i++) {
                JSONObject object = scheduleArray.getJSONObject(i);
                StaSchedule staSchedule = new StaSchedule();
                staSchedule.setZb(num);
                staSchedule.setXh(Integer.parseInt(object.getString("LAY_TABLE_INDEX")) + 1);
                staSchedule.setQssj(Date.valueOf(object.getString("qssj")));
                staSchedule.setJssj(Date.valueOf(object.getString("jssj")));
                staSchedule.setYjnr(object.getString("yjnr"));
                staScheduleList.add(staSchedule);
            }
            if (staScheduleList.size() > 0) {
                staScheduleService.insertBatch(staScheduleList);
            }
        } catch (JSONException e) {
            logger.error("项目进度安排json转换异常！", e);
        } catch (Exception e) {
            logger.error("新建可研报告项目进度安排出现异常！", e);
        }
        return BaseResult.success("新建可研报告'" + mc + "'成功!", staFeasibilityreport);
    }

    /***
     * 编辑可研报告
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(StaFeasibilityreport staFeasibilityreport) {
        String mc = staFeasibilityreport.getMc();

        StaFeasibilityreport report = staFeasibilityreportService.update(staFeasibilityreport);
        if (report == null) {
            return BaseResult.failure("编辑可研报告'" + mc + "'失败!");
        }
        doUpdateJfys(staFeasibilityreport.getStaBudgetList());
        //项目负责人批量插入
        try {
            JSONArray directorArray = new JSONArray(staFeasibilityreport.getStaDirectorList());
            List<StaDirector> staDirectorList = new ArrayList<>();

            for (int i = 0; i < directorArray.length(); i++) {
                JSONObject object = directorArray.getJSONObject(i);
                StaDirector staDirector = new StaDirector();
                staDirector.setZb(staFeasibilityreport.getId());
//                String xh = String.format("%03d", Integer.parseInt(object.getString("LAY_TABLE_INDEX"))+1);
                staDirector.setXh(Integer.parseInt(object.getString("xh")));
                staDirector.setFzr(Integer.parseInt(object.getString("fzr")));
                staDirector.setXm(object.getString("xm"));
                staDirectorList.add(staDirector);
            }
            staDirectorService.deleteByZbId(staFeasibilityreport.getId());
            if (staDirectorList.size() > 0) {
                staDirectorService.insertBatch(staDirectorList);
            }
        } catch (JSONException e) {
            logger.error("项目负责人json转换异常！", e);
        } catch (Exception e) {
            logger.error("编辑可研报告项目负责人出现异常！", e);
        }
        //项目进度安排批量插入
        try {
            JSONArray scheduleArray = new JSONArray(staFeasibilityreport.getStaScheduleList());
            List<StaSchedule> staScheduleList = new ArrayList<>();
            for (int i = 0; i < scheduleArray.length(); i++) {
                JSONObject object = scheduleArray.getJSONObject(i);
                StaSchedule staSchedule = new StaSchedule();
                staSchedule.setZb(staFeasibilityreport.getId());
                staSchedule.setXh(Integer.parseInt(object.getString("LAY_TABLE_INDEX")) + 1);
                staSchedule.setQssj(Date.valueOf(object.getString("qssj")));
                staSchedule.setJssj(Date.valueOf(object.getString("jssj")));
                staSchedule.setYjnr(object.getString("yjnr"));
                staScheduleList.add(staSchedule);
            }
            staScheduleService.deleteByZbId(staFeasibilityreport.getId());
            if (staScheduleList.size() > 0) {
                staScheduleService.insertBatch(staScheduleList);
            }
        } catch (JSONException e) {
            logger.error("项目进度安排json转换异常！", e);
        } catch (Exception e) {
            logger.error("编辑可研报告项目进度安排出现异常！", e);
        }
        return BaseResult.success("编辑可研报告'" + mc + "'成功!");
    }


    /**
     * 删除一条可研报告
     *
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult delete(@PathVariable Integer id) {
        boolean flag = staFeasibilityreportService.deleteById(id);
        if (flag) {
            staDirectorService.deleteByZbId(id);
            staScheduleService.deleteByZbId(id);
            staBudgetService.deleteByXm(id);
            return BaseResult.success("删除成功!");
        } else {
            return BaseResult.failure("删除失败!");
        }
    }

    /**
     * 批量删除可研报告
     *
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data) {

        List<Integer> idList = JsonTool.parseArray(data, Integer.class);
        int num = 0;
        for (Integer id : idList) {
            boolean flag = staFeasibilityreportService.deleteById(id);
            if (flag) {
                staDirectorService.deleteByZbId(id);
                staScheduleService.deleteByZbId(id);
                staBudgetService.deleteByXm(id);
                num++;
            }
        }
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }

    /**
     * 获取项目可研报告
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/kybgList", method = RequestMethod.POST)
    public BaseResult kybgList(@RequestParam("page") Integer pageNum,
                               @RequestParam("limit") Integer pageSize,
                               @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                               @RequestParam(required = false, defaultValue = "", value = "mc") String mc,
                               @RequestParam(required = false, defaultValue = "", value = "ssbmName") String ssbmName,
                               @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                               @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("mc", mc);
        paraMap.put("ssbmName", ssbmName);
        paraMap.put("xmlx", xmlx);
        List<StaFeasibilityreport> list = staFeasibilityreportService.getRwsKybgList(paraMap);

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


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


    /**
     * 编辑数据(提交审批)
     *
     * @return
     */
//    @RequestMapping(value = "/forApproveUpdate/{xmid}", method = RequestMethod.GET)
//    public String forApproveUpdate(Model model, @PathVariable Integer xmid, @RequestParam String spzt)
    @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("spzt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            model.addAttribute("approveInfo", approveList.get(approveList.size() - 1));
        } else {
            StaFeasibilityreport report = staFeasibilityreportService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(report.getMc());
            approveInfo.setZt("数据不匹配");
            model.addAttribute("approveInfo", approveInfo);
        }
        //gst
//        List<CyyEntriy> cyyList =cyyService.queryByAccount(String.valueOf(userInfo.getUserId()));
//        model.addAttribute("cyyList", cyyList);


        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 "reportinfo/back_approve";
        } else {
            return "reportinfo/finish_approve";
        }
    }

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

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

    /**
     * 保存数据（经费预算）
     *
     * @return
     */
    public BaseResult doUpdateJfys(String data) {
        List<StaBudget> staBudgets = JsonTool.parseArray(data, StaBudget.class);
        int num = staBudgetService.updateBatch(staBudgets);
        if (num > 0) {
            return BaseResult.success("经费预算保存成功!");
        } else {
            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<StaFeasibilityreport> reportInfoList = staFeasibilityreportService.getReportInfoList(new HashMap<>());

        List<String> listName = Arrays.asList("中文名称", "审批状态", "ERP编号", "项目类型", "起始", "完成", "创建人", "创建时间");
        List<Map<String, String>> list = new ArrayList<>();
        for (StaFeasibilityreport report : reportInfoList) {
            Map<String, String> map = new HashMap<>();
            map.put("名称", report.getMc());
            map.put("审批状态", report.getSpzt());
            map.put("申请单位", report.getSqdwName());
            map.put("项目类型", report.getXmlxmc());
            map.put("起始", report.getQs().toString());
            map.put("完成", report.getWc().toString());
            map.put("创建人", report.getCjrName());
            map.put("创建时间", report.getCjrq().toString());
            list.add(map);
        }

        ExcelPoiUtil.excelPort("可研报告", listName, list, null, response);
    }

    /***
     * 新建可研报告(基本信息)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAddNormal", method = RequestMethod.POST)
    public BaseResult doAddNormal(StaFeasibilityreport feasibilityreport) {
        feasibilityreport.setSpzt("未提交");
        feasibilityreport.setCjr(getSysUserId());

        int num = staFeasibilityreportService.insertNormal(feasibilityreport);
        if (num > 0) {
            //经费预算项插入
            staBudgetService.insertBatchByXmlx(feasibilityreport.getXmlx(), feasibilityreport.getId());
            return BaseResult.success("常规信息保存成功!", feasibilityreport);
        } else {
            return BaseResult.failure("常规信息保存失败!");
        }
    }

    /**
     * 编辑数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateNormal", method = RequestMethod.POST)
    public BaseResult doUpdateNormal(StaFeasibilityreport feasibilityreport) {
        int num = staFeasibilityreportService.updateNormal(feasibilityreport);
        if (num > 0) {
            //经费预算项插入
            int count = staBudgetService.insertBatchByXmlx(feasibilityreport.getXmlx(), feasibilityreport.getId());
            return BaseResult.success("常规信息保存成功!", feasibilityreport);
        } else {
            return BaseResult.failure("常规信息保存失败!");
        }
    }

    /**
     * 编辑数据（目的和意义）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateMdhyy", method = RequestMethod.POST)
    public BaseResult doUpdateMdhyy(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateMdhyy(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("目的和意义保存成功!");
        } else {
            return BaseResult.failure("目的和意义保存失败!");
        }
    }

    /**
     * 编辑数据（研究水平）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateYjsp", method = RequestMethod.POST)
    public BaseResult doUpdateYjsp(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateYjsp(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("研究水平保存成功!");
        } else {
            return BaseResult.failure("研究水平保存失败!");
        }
    }

    /**
     * 编辑数据（理论实践依据）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateLlsjyj", method = RequestMethod.POST)
    public BaseResult doUpdateLlsjyj(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateLlsjyj(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("理论实践依据保存成功!");
        } else {
            return BaseResult.failure("理论实践依据保存失败!");
        }
    }

    /**
     * 编辑数据（研究内容）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateYjnr", method = RequestMethod.POST)
    public BaseResult doUpdateYjnr(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateYjnr(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("研究内容保存成功!");
        } else {
            return BaseResult.failure("研究内容保存失败!");
        }
    }

    /**
     * 编辑数据（经济性财务合规性）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateJjxycwhgx", method = RequestMethod.POST)
    public BaseResult doUpdateJjxycwhgx(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateJjxcwhgx(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("经济性财务合规性保存成功!");
        } else {
            return BaseResult.failure("经济性财务合规性保存失败!");
        }
    }

    /**
     * 编辑数据（预期目标）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateYqmb", method = RequestMethod.POST)
    public BaseResult doUpdateYqmb(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateYqmb(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("预期目标保存成功!");
        } else {
            return BaseResult.failure("预期目标保存失败!");
        }
    }

    /**
     * 编辑数据（合作单位）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateHzdw", method = RequestMethod.POST)
    public BaseResult doUpdateHzdw(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateHzdw(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("合作单位保存成功!");
        } else {
            return BaseResult.failure("合作单位保存失败!");
        }
    }

    /**
     * 编辑数据（承担单位条件）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateCddw", method = RequestMethod.POST)
    public BaseResult doUpdateCddw(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateCddw(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("承担单位条件保存成功!");
        } else {
            return BaseResult.failure("承担单位条件保存失败!");
        }
    }

    /**
     * 编辑数据（审查意见）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateScyj", method = RequestMethod.POST)
    public BaseResult doUpdateScyj(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateScyj(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("审查意见保存成功!");
        } else {
            return BaseResult.failure("审查意见保存失败!");
        }
    }

    /**
     * 编辑数据（附件）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateFj", method = RequestMethod.POST)
    public BaseResult doUpdateFj(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateFj(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("附件保存成功!");
        } else {
            return BaseResult.failure("附件保存失败!");
        }
    }

    /**
     * 编辑数据（签名盖章）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateQmgz", method = RequestMethod.POST)
    public BaseResult doUpdateQmgz(@RequestBody String data) {
        StaFeasibilityreport feasibilityreport = JsonTool.parseObject(data, StaFeasibilityreport.class);
        int num = staFeasibilityreportService.updateQmgz(feasibilityreport);
        if (num > 0) {
            return BaseResult.success("签名盖章保存成功!");
        } else {
            return BaseResult.failure("签名盖章保存失败!");
        }
    }

    /**
     * 页面初始化
     *
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_myProject", method = RequestMethod.GET)
    public String init_myProject(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("approveList", approveList);
        List<Map<String, String>> approvedList = sysDictInfoService.queryByCode("approved_status");
        model.addAttribute("approvedList", approvedList);

        model.addAttribute("browseRight", CheckPermissionInfo("myproject:reportlist"));
        model.addAttribute("addRight", true);
        model.addAttribute("delRight", true);
        model.addAttribute("editRight", true);
        model.addAttribute("auditRight", true);
        //当前用户Id
        model.addAttribute("userId", getSysUserId());
        return "reportinfo/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 = "MC") String mc,
                                     @RequestParam(required = false, defaultValue = "", value = "SPZT") String spzt,
                                     @RequestParam(required = false, defaultValue = "", value = "SSBMNAME") String ssbmName,
                                     @RequestParam(required = false, defaultValue = "", value = "SQRQStart") String sqrq1,
                                     @RequestParam(required = false, defaultValue = "", value = "SQRQEnd") String sqrq2,
                                     @RequestParam(required = false, defaultValue = "", value = "YSP") String ysp,
                                     @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 = "过";
                    System.out.println("ppppppppppppppppp" + post + i);
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("mc", mc);
        paraMap.put("spzt", spzt);
        paraMap.put("ssbmName", ssbmName);
        paraMap.put("sqrq1", sqrq1);
        paraMap.put("sqrq2", sqrq2);
        paraMap.put("ysp", ysp);
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }
        }

        List<StaFeasibilityreport> staFeasibilityreport = staFeasibilityreportService.getReportInfoList(paraMap);

        PageInfo<StaFeasibilityreport> pageinfo = new PageInfo<>(staFeasibilityreport);
        // 取出查询结果
        List<StaFeasibilityreport> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    /**
     * 页面初始化
     *
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_deptProject", method = RequestMethod.GET)
    public String init_deptProject(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("approveList", approveList);
        List<Map<String, String>> approvedList = sysDictInfoService.queryByCode("approved_status");
        model.addAttribute("approvedList", approvedList);

        model.addAttribute("browseRight", CheckPermissionInfo("myproject:reportlist"));
        model.addAttribute("addRight", true);
        model.addAttribute("delRight", true);
        model.addAttribute("editRight", true);
        model.addAttribute("auditRight", true);

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

        return "reportinfo/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 = "MC") String mc,
                                       @RequestParam(required = false, defaultValue = "", value = "SPZT") String spzt,
                                       @RequestParam(required = false, defaultValue = "", value = "SSBMNAME") String ssbmName,
                                       @RequestParam(required = false, defaultValue = "", value = "SQRQStart") String sqrq1,
                                       @RequestParam(required = false, defaultValue = "", value = "SQRQEnd") String sqrq2,
                                       @RequestParam(required = false, defaultValue = "", value = "YSP") String ysp,
                                       @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 = "过";
                    System.out.println("ppppppppppppppppp" + post + i);
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("mc", mc);
        paraMap.put("spzt", spzt);
        paraMap.put("ssbmName", ssbmName);
        paraMap.put("sqrq1", sqrq1);
        paraMap.put("sqrq2", sqrq2);
        paraMap.put("ysp", ysp);
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("deptId", userInfo.getDeptId());
            }
        }

        List<StaFeasibilityreport> staFeasibilityreport = staFeasibilityreportService.getReportInfoList(paraMap);

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

    /**
     * 生成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 outFile = uploadFolder + "/template/temp/" + fileName + ".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 {
        StaFeasibilityreport report = staFeasibilityreportService.queryById(id);
        BaseCompany company = baseCompanyService.queryById(report.getSqdw());
        report.setSqdwName(company.getMc());
        List<StaDirector> directors = staDirectorService.queryByZbId(id);
        if (directors != null && directors.size() > 0) {
            report.setXmfzrName(directors.get(0).getXm());
        }
        String fileName = report.getMc();
        String templatePath = uploadFolder + "/template";

        String coverDoc = uploadFolder + "/template/temp/first_" + report.getId() + ".docx";
        Map<String, Object> mapData = WordUtils.getWord(report);
        coverDoc = WordUtils.genWord(coverDoc, templatePath, "first.ftl", mapData);

        List<String> list = new ArrayList<>();
        if (coverDoc != "")
            list.add(coverDoc);
        List<String> mdhyyList = GenTempFile(report.getId(), report.getMdhyy(), report.getMdhyywb(), "mdhyy", "mdhyywb");
        for (int i = 0; i < mdhyyList.size(); i++) {
            if (mdhyyList.get(i) != "")
                list.add(mdhyyList.get(i));
        }
        List<String> yjspList = GenTempFile(report.getId(), report.getGnwyjspzs(), report.getGnwyjspzswb(), "yjsp", "gnwyjspzswb");
        for (int i = 0; i < yjspList.size(); i++) {
            if (yjspList.get(i) != "")
                list.add(yjspList.get(i));
        }
        List<String> llsjyjList = GenTempFile(report.getId(), report.getXmdllhsjyj(), report.getXmdllhsjyjwb(), "llsjyj", "xmdllhsjyjwb");
        for (int i = 0; i < llsjyjList.size(); i++) {
            if (llsjyjList.get(i) != "")
                list.add(llsjyjList.get(i));
        }
        List<String> yjnrList = GenTempFile(report.getId(), report.getXmyjnrhssfa(), report.getXmyjnrhssfawb(), "yjnr", "xmyjnrhssfawb");
        for (int i = 0; i < yjnrList.size(); i++) {
            if (yjnrList.get(i) != "")
                list.add(yjnrList.get(i));
        }

        Map<String, Object> midData = new HashMap<String, Object>();
        if (report.getJjxycwhgx() != null)
            midData.put("jjxycwhgx", report.getJjxycwhgx());
        else
            midData.put("jjxycwhgx", "");
        if (report.getYqmbhcgxs() != null)
            midData.put("yqmbhcgxs", report.getYqmbhcgxs());
        else
            midData.put("yqmbhcgxs", "");
        if (report.getHzdwhytgcdwlsqk() != null)
            midData.put("hzdwhytgcdwlsqk", report.getHzdwhytgcdwlsqk());
        else
            midData.put("hzdwhytgcdwlsqk", "");

        String midDoc = uploadFolder + "/template/temp/middle_" + report.getId() + ".docx";
        midDoc = WordUtils.genWord(midDoc, templatePath, "middle.ftl", midData);

        if (midDoc != "")
            list.add(midDoc);
        List<String> cddwtjList = GenTempFile(report.getId(), report.getXmcddwdtj(), "", "cddwtj", "xmcddwdtj");
        for (int i = 0; i < cddwtjList.size(); i++) {
            if (cddwtjList.get(i) != "")
                list.add(cddwtjList.get(i));
        }

        Map<String, Object> lastData = new HashMap<String, Object>();
        String lastDoc = uploadFolder + "/template/temp/last_" + report.getId() + ".docx";
        if (report.getSqdwldscyj1() != null)
            lastData.put("sqdwldscyj1", report.getSqdwldscyj1());
        else
            lastData.put("sqdwldscyj1", "");

        List<StaSchedule> staScheduleList = staScheduleService.queryByZbId(report.getId());
        List<Map<String, String>> scheduleData = new ArrayList<>();
        for (int i = 0; i < staScheduleList.size(); i++) {
            StaSchedule schedule = staScheduleList.get(i);
            Map<String, String> map = new HashMap<>();
            Integer xh = i + 1;
            map.put("xh", xh.toString());
            map.put("time", schedule.getQssj().toString().replace('-', '.') + "-" + schedule.getJssj().toString().replace('-', '.'));
            map.put("yjnr", schedule.getYjnr());
            scheduleData.add(map);
        }
        lastData.put("staScheduleList", scheduleData);

        List<StaBudget> budgetList = staBudgetService.getBudgetList(report.getId());
        List<Map<String, String>> budgetData = new ArrayList<>();
        for (int i = 0; i < budgetList.size(); i++) {
            StaBudget budget = budgetList.get(i);
            Map<String, String> map = new HashMap<>();
            map.put("mc", budget.getMc());
            String ysje = "";
            if (budget.getYsje() == null)
                ysje = "";
            else
                ysje = String.format("%.2f", budget.getYsje());
            map.put("ysje", ysje);
            String dw1 = "";
            if (budget.getDw1() == null)
                dw1 = "";
            else
                dw1 = String.format("%.2f", budget.getDw1());
            map.put("dw1", dw1);
            String dw2 = "";
            Double _dw2 = 0d;
            if (budget.getYsje() != null) {
                if (budget.getDw1() != null)
                    _dw2 = budget.getYsje() - budget.getDw1();
                else
                    _dw2 = budget.getYsje();
                if (_dw2 > 0)
                    dw2 = String.format("%.2f", _dw2);
                else
                    dw2 = "";
            }
            map.put("dw2", dw2);
            String bz = "";
            if (budget.getBz() == null)
                bz = "";
            else
                bz = budget.getBz();
            map.put("bz", bz);
            budgetData.add(map);
        }
        lastData.put("staBudgetList", budgetData);
        lastDoc = WordUtils.genWord(lastDoc, templatePath, "last.ftl", lastData);
        if (lastDoc != "")
            list.add(lastDoc);

        String outFile = uploadFolder + "/template/temp/" + fileName + ".docx";
        boolean ret = WordUtils.appendDocx(outFile, list);
        list.add(coverDoc);
        for (String filePath : list) {
            if (filePath.indexOf("/template/temp/") > 0) {
                File file = new File(filePath);
                if (file.exists() && file.isFile())
                    file.delete();
            }
        }
        if (ret)
            return fileName;
        else
            return "";
    }


    private List<String> GenTempFile(Integer id, String strJson, String strText, String ftlName, String lblName) throws IOException, JSONException {
        List<String> list = new ArrayList<>();
        String templatePath = uploadFolder + "/template";
        String doc = uploadFolder + "/template/temp/" + ftlName + "_" + id + ".docx";
        if (strJson == null || strJson.isEmpty()) {
            Map<String, Object> data = new HashMap<String, Object>();
            if (strText != null)
                data.put(lblName, strText);
            else
                data.put(lblName, "");
            doc = WordUtils.genWord(doc, templatePath, ftlName + ".ftl", data);

            if (doc != "")
                list.add(doc);
        } else {
            JSONArray jsonArray = new JSONArray(strJson);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                String url = jsonObj.getString("Url");
                if (url.indexOf("http") > -1) {
                    url = url.substring(8);
                    url = url.substring(url.indexOf('/'));
                }
                doc = uploadFolder + "/" + url;
                list.add(doc);
            }
        }
        return list;
    }
}

