package com.liang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
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.config.SFTYProperties;
import com.liang.common.constants.CommonConstant;
import com.liang.common.enums.PostInfoEnum;
import com.liang.common.enums.ProjectTypeEnnum;
import com.liang.common.utils.ExcelPoiUtil;
import com.liang.common.utils.FileUtil;
import com.liang.common.utils.Tools;
import com.liang.dao.PrjAnnualbudgetdetailDao;
import com.liang.entity.*;
import com.liang.service.*;
import com.liang.vo.PrjAnnualbudgetNfVo;
import com.liang.vo.PrjAnnualbudgetYzxqkVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 年度预算(PrjAnnualbudget)表控制层
 *
 * @author makejava
 * @since 2023-05-17 08:56:49
 */
@Controller
@Slf4j
@RequestMapping("prjAnnualbudget")
public class PrjAnnualbudgetController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private BaseProjecttypeService projecttypeService;
    @Resource
    private PrjAnnualbudgetdetailService prjAnnualbudgetdetailService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private PrjProjectService prjProjectService;
    @Resource
    private PrjFeeschemeService prjFeeschemeService;
    @Resource
    private StaBudgetapprovalService staBudgetapprovalService;
    @Resource
    private CyyService cyyService;

    @Resource
    private SysUserInfoService sysUserInfoService;
    @Resource
    private  PrjAnnualBudgetRecordService prjAnnualBudgetRecordService;
    @Resource
    private PrjCompletecompanyService prjCompletecompanyService;


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

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

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

    /**
     * 列表初始化
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);
        //审批状态
        List<Map<String, String>> approveList = sysDictInfoService.queryByCode("xm_status");
        model.addAttribute("approveList", approveList);
        //年份
        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        // 此处是一个测试代码
        return "annualbudget/list";
    }

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

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

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

            }else {
                paraMap.put("nf",nf);
            }
        }
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("xmmc", xmmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("ssbmmc", ssbmmc);
        paraMap.put("spzt", spzt);
        paraMap.put("rwsmc", rwsmc);
        paraMap.put("sfxg", sfxg);

        List<PrjAnnualbudget> list = prjAnnualbudgetService.getNdysList(paraMap);

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

        return BaseResult.success(result);
    }

    @Resource
    private SysDeptInfoService sysDeptInfoService;

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

        model.addAttribute("dept",sysDeptInfoService.getDeptName());
        return "annualbudget/mylist";
    }
        @RequestMapping(value = "/ViewXGSQ", method = RequestMethod.GET)
        public String ViewXGSQ(Model model) {
//            获取待审批修改申请列表
//            prjAnnualBudgetRecordService.getSpList();

            return "annualbudget/view_xgsq";
        }

    @ResponseBody
    @RequestMapping(value = "/mylist", method = RequestMethod.POST)
    public BaseResult mylist(@RequestParam("page") Integer pageNum,
                             @RequestParam("limit") Integer pageSize,
                             @RequestParam(required = false, defaultValue = "", value = "xmmc") String xmmc,
                             @RequestParam(required = false, defaultValue = "", value = "erpbh") String erpbh,
                             @RequestParam(required = false, defaultValue = "", value = "xmlx") String xmlx,
                             @RequestParam(required = false, defaultValue = "", value = "ssbmmc") String ssbmmc,
                             @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                             @RequestParam(required = false, defaultValue = "", value = "rwsmc") String rwsmc,
                             @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                             @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                             @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                             @RequestParam(required = false, defaultValue = "", value = "add") String add) {
        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 = "过";
//                }
                if (PostInfoEnum.KYFZR.postName().equals(postName.get(i))||PostInfoEnum.KJBBMZR.equals(postName.get(i))||PostInfoEnum.KJXMGLZZ
                        .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("xmmc", xmmc);
        paraMap.put("erpbh", erpbh);
        paraMap.put("xmlx", xmlx);
        paraMap.put("ssbmmc", ssbmmc);
        paraMap.put("spzt", spzt);
        paraMap.put("rwsmc", rwsmc);
        paraMap.put("nf", nf);
        paraMap.put("add",add);
         if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
                if (userInfo.getDeptName().contains("电源")){
                    paraMap.put("deptName","电源技术中心");
                }else {
                    paraMap.put("deptName", userInfo.getDeptName());
                }
            }
        }
        List<PrjAnnualbudget> list = prjAnnualbudgetService.getNdysList(paraMap);
        PageInfo<PrjAnnualbudget> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjAnnualbudget> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }
    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);
        return "annualbudget/add_annualbudget";
    }

    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init_project", method = RequestMethod.GET)
    public String init_rws(Model model) {
        //项目类型
        List<Map<String, String>> xmlxList = projecttypeService.getXMLX();
        model.addAttribute("xmlxList", xmlxList);

        return "annualbudget/list_project";
    }

    @Resource
    private PrjAnnualbudgetdetailDao prjAnnualbudgetdetailDao;

    /**
     * 获取项目预算年份
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getNf/{nys}", method = RequestMethod.POST)
    public Object getNf(@PathVariable Integer nys) {
        List<PrjAnnualbudgetYzxqkVo> yzxqkVos = prjAnnualbudgetdetailDao.getNf(nys);
        List<PrjAnnualbudgetNfVo> nfVos = yzxqkVos.stream().map(item -> {
            return PrjAnnualbudgetNfVo.builder().title(item.getNf()).width("12%").field("yzxqk" + item.getNf()).build();
        }).collect(Collectors.toList());
        return JsonTool.toJsonString(nfVos);
    }

    /**
     * 获取项目预算列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{nys}", method = RequestMethod.POST)
    public Object list(@PathVariable Integer nys) {
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getBudgetList(nys);
        //获取已执行情况
        List<PrjAnnualbudgetYzxqkVo> yzxqkVos = prjAnnualbudgetdetailDao.getYzxqk(nys);
        //获取所有的年度预算
        List<PrjAnnualbudgetdetail> allBudgetDetails = prjAnnualbudgetdetailService.listAllBudgetDetail(nys);
        String res = "";
        try {
            List<Map<String, Object>> readValue = JsonTool.getObjectMapper().readValue(JsonTool.toJsonString(list), List.class);
            if (!Tools.isEmpty(yzxqkVos)) {
                yzxqkVos.forEach(yzxItem -> {
                    readValue.stream().filter(item -> item.get("fymc").equals(yzxItem.getFymc())).forEach(item -> item.put("yzxqk" + yzxItem.getNf(), yzxItem.getBzje()));
                });

                Set<String> nf = yzxqkVos.stream().map(PrjAnnualbudgetYzxqkVo::getNf).collect(Collectors.toSet());
                //后端对已执行情况的父级求和
                sumYzxqk(readValue, nf, yzxqkVos.get(0).getXmlx());
                nf.forEach(nfItem -> {
                    readValue.stream().forEach(item -> {
                        Double ysje = allBudgetDetails.stream().filter(allBudgetDetailItem -> allBudgetDetailItem.getFymc().equals(item.get("fymc")) && nfItem.equals(String.valueOf(allBudgetDetailItem.getNf()))).collect(Collectors.toList()).get(0).getYsje();

                        item.put("yzxqk" + nfItem, (ysje == null ? 0 : ysje) + "(" + (item.get("yzxqk" + nfItem) == null ? 0 : item.get("yzxqk" + nfItem)) + ")");
                    });
                });
            }
            res = JsonTool.toJsonString(readValue);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return res;
    }
    /**
     * 获取项目修改预算列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list_xg/{nys}", method = RequestMethod.POST)
    public Object xglist(@PathVariable Integer nys) {
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getSptgZt(nys);
        //获取已执行情况
        List<PrjAnnualbudgetYzxqkVo> yzxqkVos = prjAnnualbudgetdetailDao.getYzxqk(nys);
        //获取所有的年度预算
        List<PrjAnnualbudgetdetail> allBudgetDetails = prjAnnualbudgetdetailService.listAllBudgetDetail(nys);
        String res = "";
        try {
            List<Map<String, Object>> readValue = JsonTool.getObjectMapper().readValue(JsonTool.toJsonString(list), List.class);
            if (!Tools.isEmpty(yzxqkVos)) {
                yzxqkVos.forEach(yzxItem -> {
                    readValue.stream().filter(item -> item.get("fymc").equals(yzxItem.getFymc())).forEach(item -> item.put("yzxqk" + yzxItem.getNf(), yzxItem.getBzje()));
                });

                Set<String> nf = yzxqkVos.stream().map(PrjAnnualbudgetYzxqkVo::getNf).collect(Collectors.toSet());
                //后端对已执行情况的父级求和
                sumYzxqk(readValue, nf, yzxqkVos.get(0).getXmlx());
                nf.forEach(nfItem -> {
                    readValue.stream().forEach(item -> {
                        Double ysje = allBudgetDetails.stream().filter(allBudgetDetailItem -> allBudgetDetailItem.getFymc().equals(item.get("fymc")) && nfItem.equals(String.valueOf(allBudgetDetailItem.getNf()))).collect(Collectors.toList()).get(0).getYsje();

                        item.put("yzxqk" + nfItem, (ysje == null ? 0 : ysje) + "(" + (item.get("yzxqk" + nfItem) == null ? 0 : item.get("yzxqk" + nfItem)) + ")");
                    });
                });
            }
            res = JsonTool.toJsonString(readValue);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(Math.floor(3.6799999999));
        BigDecimal bd;

    }

    private void sumYzxqk(List<Map<String, Object>> readValue, Set<String> nf, String xmlx) {
     /*   for (String n : nf) {
            String rgfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.RGF);
            //更新人工费
            if (Tools.notEmpty(rgfbm)) {
                List<Map<String, Object>> rgfs = readValue.stream().filter(item -> {
                    return Tools.notEmpty(rgfbm) && rgfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null;
                }).collect(Collectors.toList());
                if (Tools.notEmpty(rgfs)) {
                    BigDecimal rgf = rgfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> rgfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, rgf.setScale(2, 4)));
                }
            }
            //更新设备费
            String sbfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.SBF);
            if (Tools.notEmpty(sbfbm)) {
                List<Map<String, Object>> sbfs = readValue.stream().filter(item -> {
                    return Tools.notEmpty(sbfbm) && sbfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null;
                }).collect(Collectors.toList());
                if (Tools.notEmpty(sbfs)) {
                    BigDecimal sbf = sbfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> sbfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, sbf.setScale(2, 4)));
                }
            }
            //更新设备使用费
            String sbsyfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.SBSYF);
            if (Tools.notEmpty(sbsyfbm)) {
                List<Map<String, Object>> sbsyfs = readValue.stream().filter(item -> sbsyfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(sbsyfs)) {
                    BigDecimal sbsyf = sbsyfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> sbsyfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(sbsyf)));
                }
            }
            //更新业务费
            String ywfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.YWF);
            if (Tools.notEmpty(ywfbm)) {
                List<Map<String, Object>> yfws = readValue.stream().filter(item -> ywfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(yfws)) {
                    BigDecimal ywf = yfws.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> ywfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(ywf)));
                }
            }
            //更新场地使用费
            String cdsyfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.CDSYF);
            if (Tools.notEmpty(cdsyfbm)) {
                List<Map<String, Object>> cdsyfs = readValue.stream().filter(item -> cdsyfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(cdsyfs)) {
                    BigDecimal cdsyf = cdsyfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> cdsyfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(cdsyf)));
                }
            }

            //更新外委支出费
            String wwzcfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.WWZCF);
            if (Tools.notEmpty(wwzcfbm)) {
                List<Map<String, Object>> wwzcfs = readValue.stream().filter(item -> wwzcfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(wwzcfs)) {
                    BigDecimal wwzcf = wwzcfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> wwzcfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(wwzcf)));
                }
            }

            //更新直接费
            String zjfbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.ZJF);
            if (Tools.notEmpty(zjfbm)) {
                List<Map<String, Object>> zjfs = readValue.stream().filter(item -> zjfbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(zjfs)) {
                    BigDecimal zjf = zjfs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> zjfbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(zjf)));
                }
            }
            //更新总计
            String zjbm = SFTYProperties.getNDYSBM(xmlx, CommonConstant.ZJ);
            if (Tools.notEmpty(zjbm)) {
                List<Map<String, Object>> zjs = readValue.stream().filter(item -> zjbm.equals(item.get("fj")) && item.get("yzxqk" + n) != null).collect(Collectors.toList());
                if (Tools.notEmpty(zjs)) {
                    BigDecimal zj = zjs.stream().map(item -> new BigDecimal(String.valueOf(item.get("yzxqk" + n)))).reduce(BigDecimal.ZERO, BigDecimal::add);
                    readValue.stream().filter(item -> zjbm.equals(item.get("bm"))).forEach(item -> item.put("yzxqk" + n, String.valueOf(zj)));
                }
            }

        }*/
    }

    /**
     * 保存数据（我的年度预算：基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public BaseResult doAdd(PrjAnnualbudget annualbudget) {
        annualbudget.setSpzt("未提交");
        annualbudget.setSfxg(0);
        int num = prjAnnualbudgetService.insert(annualbudget);
        if (num > 0) {
            //经费预算项插入
            prjAnnualbudgetdetailService.insertBatchByXm(annualbudget.getRws(), annualbudget.getId());
            prjProjectService.updatePrj_AnnualBudgetDetail(annualbudget.getRws());
            //更新 系统计算执行 和 实际已执行
            prjAnnualbudgetService.updateSJYZXAndXTJSYZX(annualbudget.getRws());
            return BaseResult.success("保存成功!", annualbudget);
        } else if (num == -1) {
            return BaseResult.failure("该项目 " + annualbudget.getNf() + " 年度预算已存在！");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据（我的年度预算：基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(PrjAnnualbudget annualbudget) {
        int num = prjAnnualbudgetService.update(annualbudget);
        if (num > 0) {
            return BaseResult.success("保存成功!");
        } else if (num == -1) {
            return BaseResult.failure("该项目 " + annualbudget.getNf() + " 年度预算已存在！");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

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

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

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

//    /**
//     * 编辑数据
//     *
//     * @return
//     */
//    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
//    public String forUpdate(Model model, @PathVariable Integer id)
//    {
//        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(id);
//        model.addAttribute("annualbudget", annualbudget);
//
//        String xmzxq = annualbudget.getXmzxq();
//        model.addAttribute("qs", xmzxq.substring(0, 4));
//        int index = xmzxq.trim().indexOf("至") + 2;
//        model.addAttribute("wc", xmzxq.substring(index, index + 4));
//
//        PrjProject project = prjProjectService.queryById(annualbudget.getRws());
//        model.addAttribute("rwsys", project.getYsje());
//
//       Map<String, String> paraMap = new HashMap<>();
//       paraMap.put("xm", annualbudget.getRws().toString());
//       paraMap.put("nf", annualbudget.getNf());
//       BigDecimal ndczje = prjFeeschemeService.getNdFeeScheme(paraMap);
//       model.addAttribute("ndczje", ndczje);
//
//
//        return "annualbudget/update_annualbudget";
//    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(id);
        model.addAttribute("annualbudget", annualbudget);

        String xmzxq = annualbudget.getXmzxq();
        model.addAttribute("qs", xmzxq.substring(0, 4));
        int index = xmzxq.trim().indexOf("至") + 2;
        model.addAttribute("wc", xmzxq.substring(index, index + 4));

        PrjProject project = prjProjectService.queryById(annualbudget.getRws());
        model.addAttribute("rwsys", project.getYsje());

        Map<String, String> paraMap = new HashMap<>();
        if (ProjectTypeEnnum.ZFLXM.msg().equals(annualbudget.getXmlxmc())) {
            List<Integer> nfList = prjFeeschemeService.getYearList(annualbudget.getRws());
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", nfList.get(nfList.size() - 1).toString());
        } else {
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", annualbudget.getNf());
        }
        Double ndczje;
        if (ProjectTypeEnnum.GWGSKJXM.msg().equals((annualbudget.getXmlxmc()))) {
            ndczje = prjFeeschemeService.getNdFeeSchemeofDKY(paraMap);
        } else {
            ndczje = prjFeeschemeService.getNdFeeScheme(paraMap);

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

        return "annualbudget/update_annualbudget";
    }
    /**
     * 修改申请
     *
     * @return
     */
    @RequestMapping(value = "/forUpdateApply/{id}", method = RequestMethod.GET)
    public String forUpdateApply(Model model, @PathVariable Integer id) {
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(id);
        model.addAttribute("annualbudget", annualbudget);

        String xmzxq = annualbudget.getXmzxq();
        model.addAttribute("qs", xmzxq.substring(0, 4));
        int index = xmzxq.trim().indexOf("至") + 2;
        model.addAttribute("wc", xmzxq.substring(index, index + 4));

        PrjProject project = prjProjectService.queryById(annualbudget.getRws());
        model.addAttribute("rwsys", project.getYsje());

        Map<String, String> paraMap = new HashMap<>();
        if (ProjectTypeEnnum.ZFLXM.msg().equals(annualbudget.getXmlxmc())) {
            List<Integer> nfList = prjFeeschemeService.getYearList(annualbudget.getRws());
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", nfList.get(nfList.size() - 1).toString());
        } else {
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", annualbudget.getNf());
        }
        Double ndczje;
        if (ProjectTypeEnnum.GWGSKJXM.msg().equals((annualbudget.getXmlxmc()))) {
            ndczje = prjFeeschemeService.getNdFeeSchemeofDKY(paraMap);
        } else {
            ndczje = prjFeeschemeService.getNdFeeScheme(paraMap);

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

        return "annualbudget/updateApply_annualbudget";
    }


    /**
     * 查看数据
     *
     * @return
     */
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(id);
        model.addAttribute("annualbudget", annualbudget);

        PrjProject project = prjProjectService.queryById(annualbudget.getRws());
        model.addAttribute("rwsys", project.getYsje());

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

        if (ProjectTypeEnnum.ZFLXM.msg().equals(annualbudget.getXmlxmc())) {
            List<Integer> nfList = prjFeeschemeService.getYearList(annualbudget.getRws());
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", nfList.get(nfList.size() - 1).toString());
        } else {
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", annualbudget.getNf());
        }
        Double ndczje;
        if (ProjectTypeEnnum.GWGSKJXM.msg().equals(annualbudget.getXmlxmc())) {
            ndczje = prjFeeschemeService.getNdFeeSchemeofDKY(paraMap);
            model.addAttribute("ysmc", "陕西公司出资总额");
        } else {
            ndczje = prjFeeschemeService.getNdFeeScheme(paraMap);
            model.addAttribute("ysmc", "项目总预算");
        }
        model.addAttribute("ndczje", ndczje);

        return "annualbudget/view_annualbudget";
    }

    /**
     * 查看数据(根据任务书ID)
     *
     * @return
     */
    @RequestMapping(value = "/forNdysView/{rws}", method = RequestMethod.GET)
    public String forNdysView(Model model, @PathVariable Integer rws) {
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryByRws(rws);
        model.addAttribute("annualbudget", annualbudget);
        if (ProjectTypeEnnum.GWGSKJXM.msg().equals(annualbudget.getXmlxmc())) {
            model.addAttribute("ysmc", "陕西公司出资总额");
        } else {
            model.addAttribute("ysmc", "项目总预算");
        }
        return "annualbudget/view_annualbudget";
    }

    @RequestMapping(value = "/forNdysView1/{rws}/{nf}", method = RequestMethod.GET)
    public String forNdysView1(Model model, @PathVariable Integer rws, @PathVariable Integer nf) {
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryByRws1(rws, nf);
        model.addAttribute("annualbudget", annualbudget);
        Double ndczje;
        Map<String, String>paraMap = new HashMap<>();
        paraMap.put("xm",String.valueOf(rws));
        paraMap.put("nf",String.valueOf(nf));
        ndczje = prjFeeschemeService.getNdFeeSchemeofDKY(paraMap);
        model.addAttribute("ndczje",ndczje);

        if (ProjectTypeEnnum.GWGSKJXM.msg().equals(annualbudget.getXmlxmc())) {
            model.addAttribute("ysmc", "陕西公司出资总额");
        } else {
            model.addAttribute("ysmc", "项目总预算");
        }
        return "annualbudget/view_annualbudgets";
    }

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

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

        return "annualbudget/add_approve";
    }

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    public BaseResult updateSpzt(@RequestBody String strData) {
        PrjAnnualbudget annualbudget = JsonTool.parseObject(strData, PrjAnnualbudget.class);
        int num = prjAnnualbudgetService.updateSpzt(annualbudget);
        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
    ) {
        // 费用申请查看
        PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(xmid);
        model.addAttribute("annualbudget", annualbudget);

        PrjProject project = prjProjectService.queryById(annualbudget.getRws());
        model.addAttribute("rwsys", project.getYsje());

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

        if (ProjectTypeEnnum.ZFLXM.msg().equals(annualbudget.getXmlxmc())) {
            List<Integer> nfList = prjFeeschemeService.getYearList(annualbudget.getRws());
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", nfList.get(nfList.size() - 1).toString());
        } else {
            paraMap.put("xm", annualbudget.getRws().toString());
            paraMap.put("nf", annualbudget.getNf());
        }
        Double ndczje;
        if (ProjectTypeEnnum.GWGSKJXM.msg().equals(annualbudget.getXmlxmc())) {
            ndczje = prjFeeschemeService.getNdFeeSchemeofDKY(paraMap);
            model.addAttribute("ysmc", "陕西公司出资总额");
        } else {
            ndczje = prjFeeschemeService.getNdFeeScheme(paraMap);
            model.addAttribute("ysmc", "项目总预算");
        }
        model.addAttribute("ndczje", ndczje);

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

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

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

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

    @ResponseBody
    @RequestMapping(value = "/getshr",method = RequestMethod.GET)
    public BaseResult getshr(@RequestParam Integer xmid,
                             @RequestParam String spzt){
        Map<String, Object> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid);
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        Integer id = getSysUserId();
        if (approveList.size() == 1){
            if (approveList.get(0).getShr().equals(id)){
                return BaseResult.success("OK");
            }
        }else {
            return BaseResult.failure(-1,"数据异常，请联系管理员!");
        }
        return BaseResult.failure(-2,"你不是当前项目审核人");
    }



    @ResponseBody
    @RequestMapping(value = "/bathUpdate/{xmid}", method = RequestMethod.GET)
    public Map<Object, Object> bathUpdate(Model model, @PathVariable Integer xmid, @RequestParam String spzt) {
        Map<Object, Object> res = new HashMap<>();
        //系统当前用户
        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)
            res.put("approveInfo", approveList.get(0));
        else {
            PrjAnnualbudget annualbudget = prjAnnualbudgetService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(annualbudget.getMc());
            approveInfo.setZt("数据不匹配");
            res.put("approveInfo", approveInfo);
        }
//        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.KJXMGLZZ.postName());

            SysPostInfo postInfo = sysPostInfoService.getSysPostInfo(paraMap2);
            if (postInfo == null)
                postInfo = new SysPostInfo();
            res.put("postInfo", postInfo);

            return res;
        } else {
            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 "annualbudget/list_approve";
    }

    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forApplyAdd/{id}", method = RequestMethod.GET)
    public String forApplyAdd(Model model, @PathVariable Integer id) {
        //登录用户
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);
        //当前预算
        PrjAnnualbudget annualbudget = this.prjAnnualbudgetService.queryById(id);
        model.addAttribute("annualbudget", annualbudget);
        //项目总体费用信息
        StaBudgetapproval xmFyInfo = staBudgetapprovalService.getXmFyInfo(id);
        if (xmFyInfo == null) {
            xmFyInfo = new StaBudgetapproval();
            xmFyInfo.setSqje(0.0);
            xmFyInfo.setBzje(0.0);
        } else {
            if (xmFyInfo.getSqje() == null) {
                xmFyInfo.setSqje(0.0);
            } else if (xmFyInfo.getBzje() == null) {
                xmFyInfo.setBzje(xmFyInfo.getSqje());
            }
            if (xmFyInfo.getBzje() == null)
                xmFyInfo.setBzje(0.0);

        }
        xmFyInfo.setYsje(annualbudget.getYsje());
        model.addAttribute("xmFyInfo", xmFyInfo);

        return "annualbudget/add_apply";
    }

    /**
     * 导出列表到excel
     *
     * @param response
     */
    @ApiOperation(value = "导出全部数据到excel", notes = "导出全部数据到excel")
    @RequestMapping(value = "/exportExcel/{fromdata}", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletResponse response,@PathVariable(required = false) String fromdata) throws  Exception{

        // 解析前台传过来
        Map<String, Object> paraMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        PrjAnnualbudget formDatas = objectMapper.readValue(fromdata, PrjAnnualbudget.class);
        if (formDatas.getNf().equals("0")){

            paraMap.put("nf","");
            }else {
                paraMap.put("nf",formDatas.getNf());
            }
        paraMap.put("xmmc", formDatas.getXmmc());
        paraMap.put("erpbh", formDatas.getErpbh());
        paraMap.put("xmlx", formDatas.getXmlx());
        paraMap.put("ssbmmc", formDatas.getSsbmmc());
        paraMap.put("spzt", formDatas.getSpzt());
        paraMap.put("rwsmc", formDatas.getRwsmc());
        List<PrjAnnualbudget> annualBudgets = prjAnnualbudgetService.getNdysList(paraMap);

        List<String> listName = Arrays.asList("名称", "审批状态", "ERP编号", "项目类型", "可研报告", "任务书", "年份", "创建人", "创建时间", "说明");
        List<Map<String, String>> list = new ArrayList<>();
        for (PrjAnnualbudget budget : annualBudgets) {
            Map<String, String> map = new HashMap<>();
            map.put("名称", budget.getMc());
            map.put("审批状态", budget.getSpzt());
            map.put("ERP编号", budget.getErpbh());
            map.put("项目类型", budget.getXmlxmc());
            map.put("可研报告", budget.getXmmc());
            map.put("任务书", budget.getRwsmc());
            map.put("年份", budget.getNf());
            map.put("创建人", budget.getSqrxm());
            map.put("创建时间", budget.getSqsj().toString());
            map.put("说明", budget.getSm());
            list.add(map);
        }

        ExcelPoiUtil.excelPort("年度预算", listName, list, null, response);
    }

}

