package com.liang.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseController;
import com.liang.common.base.BaseResult;
import com.liang.common.enums.PostInfoEnum;
import com.liang.common.enums.ProjectTypeEnnum;
import com.liang.common.utils.ExcelPoiUtil;
import com.liang.common.utils.StringUtils;
import com.liang.dao.PrjAnnualbudgetDao;
import com.liang.dao.StaReimbursementDao;
import com.liang.entity.*;
import com.liang.service.*;
//import com.liang.vo.service.*;
import com.liang.vo.dto.StaReimbursementDto;
import com.liang.vo.dto.StaReimbursementVo;
import com.liang.vo.dto.ViewFileVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.extern.flogger.Flogger;
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.*;

/**
 * 报账(StaReimbursement)表控制层
 *
 * @author makejava
 * @since 2023-05-16 13:06:38
 */
@Controller
@RequestMapping("staReimbursement")
public class StaReimbursementController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaReimbursementService staReimbursementService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private StaBudgetapprovalService staBudgetapprovalService;
    @Resource
    private SysPostInfoService sysPostInfoService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private CyyService cyyService;
    @Resource
    private SysUserInfoService sysUserInfoService;

    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;
    @Resource
    private SysUserPostService sysUserPostService;

    @Resource
    private BaseProjecttypeService projecttypeService;





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

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

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

    /**
     * 列表初始化
     *
     * @param model
     * @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);
        //当前用户ID
        model.addAttribute("userId", getSysUserId());
        //年份
        List<String> yearList = staReimbursementDao.getYearList();
        model.addAttribute("yearList", yearList);

        return "reimburse/list";
    }

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

        //费用类别
        List<String> xmlx = staBudgetapprovalService.getXmlx();
        model.addAttribute("fylb", xmlx);
        //年份
        List<String> yearList = staReimbursementDao.getYearList();
        model.addAttribute("yearList", yearList);
        model.addAttribute("userId", getSysUserId());
        return "reimburse/mylist";
    }
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "fysqbh") String fysqbh,
                           @RequestParam(required = false, defaultValue = "", value = "mc") String mc,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "bzr") String bzr,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,


                           @RequestParam(required = false, defaultValue = "", value = "xmmc")String xmmc,
                           @RequestParam(required = false, defaultValue = "", value = "erpbh")String erpbh,
                           @RequestParam(required = false, defaultValue = "", value = "bh")String bh,
                           @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                           @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                           @RequestParam(required = false, defaultValue = "", value = "fylb")String fylb,
                           @RequestParam(required = false, defaultValue = "", value = "xmlx")String xmlx,
                           @RequestParam(required = false, defaultValue = "", value = "sqr")String sqr,
                           @RequestParam(required = false, defaultValue = "", value = "sfbyj")String sfbyj,
                           @RequestParam(required = false, defaultValue = "", value = "ly")Integer ly) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, String> paraMap = new HashMap<>();

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

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

            }else {
                paraMap.put("nf",nf);
            }
        }
        if (ly != null && ly.equals(1)){
            SysUserInfo userInfo = getSysUserInfo();
            if (userInfo.getDeptName().contains("电源")){
                paraMap.put("ssbm","电源技术中心");
            }else {
                paraMap.put("ssbm", userInfo.getDeptName());
            }
        }
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);
        paraMap.put("fysqbh", fysqbh);
        paraMap.put("spzt", spzt);
        paraMap.put("mc", mc);
        paraMap.put("bzr", bzr);
        paraMap.put("sqr", sqr);
        paraMap.put("xmmc",xmmc);
        paraMap.put("erpbh",erpbh);
        paraMap.put("bh",bh);
        paraMap.put("fylb",fylb);
        paraMap.put("xmlx",xmlx);
        paraMap.put("bzr",sqr);
        paraMap.put("sfbyj",sfbyj);
        List<StaReimbursement> list = staReimbursementService.getReimburseList(paraMap);
        PageInfo<StaReimbursement> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaReimbursement> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    @ResponseBody
    @RequestMapping(value = "/mylist", method = RequestMethod.POST)
    public BaseResult mylist(@RequestParam("page") Integer pageNum,
                             @RequestParam("limit") Integer pageSize,
                             @RequestParam(required = false, defaultValue = "", value = "fysqbh") String fysqbh,
                             @RequestParam(required = false, defaultValue = "", value = "spzt") String spzt,
                             @RequestParam(required = false, defaultValue = "", value = "mc") String mc,
                             @RequestParam(required = false, defaultValue = "", value = "nf") String nf,
                             @RequestParam(required = false, defaultValue = "", value = "bzr") String bzr,
                             @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                             @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder,
                             @RequestParam(required = false,defaultValue = "",value = "xmmc")String xmmc,
                             @RequestParam(required = false, defaultValue = "", value = "erpbh")String erpbh
    ) {
        SysUserInfo userInfo = getSysUserInfo();
        List<String> postName = sysUserInfoService.getPostNameByUserId(userInfo.getUserId());
        String post = "";
        if (postName.size() > 0) {
            for (int i = 0; i < postName.size(); i++) {
                if (PostInfoEnum.KYZZ.postName().equals(postName.get(i))) {
                    post = "过";
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

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

        if (!userInfo.getAccount().equals("admin")) {
            if (!"过".equals(post)) {
                paraMap.put("userId", userInfo.getUserId().toString());
            }
        }
        List<StaReimbursement> list = staReimbursementService.getReimburseList(paraMap);
        PageInfo<StaReimbursement> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaReimbursement> 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);
    }

    /**
     * 修改报账 GST
     *
     * @param staReimbursement 直接使用pojo对象作为参数
     * @return 受影响行数
     */

    @RequestMapping(value = "/updateMoney", method = RequestMethod.GET)
    @ResponseBody
    public String updateMoney(StaReimbursement staReimbursement) {
        System.out.println("StaReimbursementController.updateMoney");
        int n = staReimbursementService.updateBZJE(staReimbursement);
        if (n > 0) {
            return "修改成功";
        }
        return "修改失败";
    }





    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model, @RequestParam Integer fysq) {

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("id",fysq);
        // 将当前json 解析成 对象
        List <StaBudgetapproval> list = staBudgetapprovalService.getFysqList(paraMap);
        if (list.size()==1){
            model.addAttribute("budgetapproval",list.get(0));
            List<Map<String, String>> dictList = sysDictInfoService.queryByCode("tax_rate");
            model.addAttribute("dictList", dictList);

/*            // 获取当前项目总预算值
            Map<String, String> paraMaps = new HashMap<>();

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


            return "reimburse/add";
        }
        return "";
    }

    /**
     * 撤销数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/TJrevokeApprove", method = RequestMethod.POST)
    public BaseResult TJrevokeApprove(@RequestBody String data) {

        StaReimbursement bzrxm = JsonTool.parseObject(data, StaReimbursement.class);
        int num;
        int temp;
        num = staReimbursementService.tjrevokeApprove(bzrxm);
        //修改审批列表里的状态为完成
        temp = prjApproverecordService.updateRevokeRecord(bzrxm.getId());
        //return BaseResult.success(num+"撤销成功!");
        if (num > 0 && temp > 0) {
            return BaseResult.success("撤销成功!");
        } else {
            return BaseResult.failure("撤销失败!");
        }
    }
    /**
     * 逐步撤销审批（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/TJrevokeApprove1", method = RequestMethod.POST)
    @Transactional
    public BaseResult TJrevokeApprove1(@RequestBody String data) {
        int num;
        int temp;
        StaReimbursement bzrxm = JsonTool.parseObject(data, StaReimbursement.class);
        String spzt = bzrxm.getSpzt();
        Map<String, String> paraMap = new HashMap<>();
//        修改审批状态
        switch (spzt) {
            case "科技项目管理专责审批":
                bzrxm.setSpzt("未提交");
                paraMap.put("postName",null);
                break;
            case "审批结束":
                bzrxm.setSpzt("科技项目管理专责审批");
                paraMap.put("postName", "科技项目管理专责");
                paraMap.put("postId","39");
                break;
        }
        //        修改审批状态
        num = staReimbursementService.tjrevokeApprove1(bzrxm);
//修改审批列表里的状态为完成
        temp = prjApproverecordService.updateRevokeRecord(bzrxm.getId());

        if (paraMap.get("postName")!=null){
            //获取默认审核人
            List<SysUserPost> userPostList = sysUserPostService.getPostUserList(paraMap);
            Integer shr = userPostList.get(0).getUserId();
            //审批列表中新增一条数据
            //先获取上条数据中的默认信息
            PrjApproverecord record = prjApproverecordService.getOldApproveRecord(bzrxm.getId());
            PrjApproverecord record1 =new PrjApproverecord();
            record1.setTablename(record.getTablename());
            record1.setXm(record.getXm());
            record1.setXmid(record.getXmid());
            record1.setZt(bzrxm.getSpzt());
            record1.setTjr(record.getTjr());
            record1.setTjsj(record.getTjsj());
            record1.setShr(shr);
            record1.setSfsjsh(true);//是否需要上级审核
            record1.setSjshr(record.getShr());
            record1.setSjshgw(record.getShgw());//上级审核岗位
            record1.setSffh(false);//是否返回
            record1.setYcshr(false);//隐藏审核人
            record1.setWc(false);//完成
            prjApproverecordService.insert(record1);
        }
        if (num > 0 && temp > 0) {
            return BaseResult.success("撤销成功!");
        } else {
            return BaseResult.failure("撤销失败!");
        }
    }

    /**
     * 保存数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(StaReimbursement reimbursement) {
        java.sql.Date cjsj = new java.sql.Date(System.currentTimeMillis());

        reimbursement.setBzr(getSysUserId());
        reimbursement.setCjsj(cjsj);
        reimbursement.setSpzt("未提交");
        int num = staReimbursementService.insert(reimbursement);
        if (num > 0) {
            StaBudgetapproval budgetapproval = new StaBudgetapproval();
            budgetapproval.setId(reimbursement.getFysq());
            budgetapproval.setSfbz(true);
            budgetapproval.setBxpz(reimbursement.getBxpz());
            budgetapproval.setBzje(reimbursement.getBzje());
            budgetapproval.setBhsje(reimbursement.getBhsje());
            budgetapproval.setSf(reimbursement.getSf());
            staBudgetapprovalService.updateReimburse(budgetapproval);

            return BaseResult.success("保存成功!", reimbursement);
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据（基本信息）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(StaReimbursement reimbursement) {
        // 获取当前人员账户
        SysUserInfo  sysUserInfo = getSysUserInfo();
        StaBudgetapproval staBudgetapproval =  staBudgetapprovalService.getBayID(reimbursement.getFysq());
        StaReimbursement reimbursement1 = staReimbursementService.queryById(reimbursement.getId());
        staBudgetapproval.setBzje(reimbursement.getBzje());
        staBudgetapproval.setBhsje(reimbursement.getBhsje());
        // 修改后改变当前审批状态
        // 同步修改审批列表  sta_Reimbursement
        // 获取当前人员登录 id
        // 意见模板 ： xx 修改报账金额 原报账金额为xx ，现金额为 xx 税率(原)：XX，税率（现）：XX，不含税金额(原)： XX ，不含税金额（现）：税费（原）：xx， 税费（现）：XX ，状态提交至
        //
        int nm = staBudgetapprovalService.update(staBudgetapproval);
        // 这个只修改了 保障表 未同步修改费用申请表
        // prj_ApproveRecord 审批表

/*        StaReimbursement staReimbursement = staReimbursementService.queryById(reimbursement.getId());
        PrjApproverecord prjApproverecord = new PrjApproverecord();

        prjApproverecord.setYj(
                sysUserInfo.getName()
                +"修改报账金额,报账金额（现）："
                +reimbursement.getBzje()
                +"报账金额（原）："
                +staReimbursement.getBzje()
                +"税率（现）"
                + reimbursement.getSl()
                +"税率（原）"
                + staReimbursement.getSl()
                + "不含税金额（现）"
                + reimbursement.getBhsje()
                + "不含税金额（原）"
                + staReimbursement.getBhsje()
                + "税费（现）："
                + reimbursement.getSf()
                + "税费（原）"
                + staReimbursement.getSf()
        );
        prjApproverecord.setSpzt("未提交（返回）");
        prjApproverecord.setWc();
        prjApproverecordService.update();

        reimbursement.setSpzt("未提交(返回)");*/
        reimbursement.setSpzt(reimbursement1.getSpzt());
        int num = staReimbursementService.update(reimbursement);
        if (num > 0 || nm > 0 ) {
            return BaseResult.success("保存成功!");
        } else {
            return BaseResult.failure("保存失败!");
        }
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{id}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer id) {
        StaReimbursement reimbursement = staReimbursementService.queryById(id);
        model.addAttribute("reimbursement", reimbursement);
        //税率
        List<Map<String, String>> dictList = sysDictInfoService.queryByCode("tax_rate");
        model.addAttribute("dictList", dictList);

        return "reimburse/update";
    }

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

        return "reimburse/view";
    }

    /**
     * 批量删除
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data,
                                  @RequestParam(required = false, defaultValue = "",value = "Id")Integer id) {
        List<StaReimbursement> prjList = JsonTool.parseArray(data, StaReimbursement.class);
        List<Integer> idList = new ArrayList<>();
        List<Integer> fysqList = new ArrayList<>();
        prjList.forEach(item -> {
            idList.add(item.getId());
            if (!fysqList.contains(item.getFysq())) {
                fysqList.add(item.getFysq());
            }
        });
        // 首先清除报账申请中的 报账金额 不含税金额 ，还有报账状态
        StaBudgetapproval staBudgetapproval = staBudgetapprovalService.queryById(id);
        staBudgetapproval.setBzje(0.00);
        staBudgetapproval.setBhsje(0.00);
        staBudgetapproval.setSf(0.00);
        staBudgetapproval.setSfbz(false);
        int mums = staBudgetapprovalService.update(staBudgetapproval);
        if (mums >0){
            int num = staReimbursementService.batchDelete(idList);
            if (num > 0) {
                staBudgetapprovalService.clearReimburse(fysqList);
                return BaseResult.success("批量删除成功!");
            }
        }
            return BaseResult.failure("批量删除失败!");
    }

    /**
     * 新建数据(提交审批)
     *
     * @return
     */
    @RequestMapping(value = "/forApproveAdd", method = RequestMethod.GET)
    public String forApproveAdd(Model model) {
        //部门主任岗位
        Map<String, String> paraMap = new HashMap<>();

        paraMap.put("postName", PostInfoEnum.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 "reimburse/add_approve";
    }

    @Resource
    private PrjAnnualbudgetDao prjAnnualbudgetDao;
    @Resource
    private StaReimbursementDao staReimbursementDao;

    @Resource
    private StaPayapprovalService staPayapprovalService;

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSpzt", method = RequestMethod.POST)
    public BaseResult updateSpzt(@RequestBody String strData,
                                 @RequestParam(required = false, defaultValue = "",value = "Id")Integer id) {
        // 解析Json
        StaReimbursement fybz = JsonTool.parseObject(strData, StaReimbursement.class);
        // 获取付款申请中的 费用申请Id 数据
        Map<String, Object> maps = new HashMap<>();
        maps.put("fysq",id);
        List<StaPayapproval> staPayapproval = staPayapprovalService.getFksq(maps);
        if (staPayapproval != null){
            if (staPayapproval.size() ==1 ){
                staPayapproval.get(0).setSpzt("作废");
                int mun =  staPayapprovalService.updateSpzt(staPayapproval.get(0));
                if (mun > 0){
                    System.out.println("成功");
                }else {
                    for (int i = 0; i<staPayapproval.size();i++){
                        staPayapproval.get(i).setSpzt("作废");
                       int muns = staPayapprovalService.updateSpzt(staPayapproval.get(i));
                       if (muns > 0){
                           System.out.println("成功");

                       }else {
                           System.out.println(staPayapproval.get(i)+"：数据作废失败！");
                       }

                    }
                }
            // 清空集合

           }
            System.out.println("失败");
        }
        // 首先清除报账申请中的 报账金额 不含税金额 ，还有报账状态
        // 查询付款表 作废付款申请中的已付款
        if (fybz.getSpzt().equals("作废")){
            StaBudgetapproval staBudgetapproval = staBudgetapprovalService.queryById(id);
            staBudgetapproval.setBzje(0.00);
            staBudgetapproval.setBhsje(0.00);
            staBudgetapproval.setSf(0.00);
            staBudgetapproval.setSfbz(false);
            int mums = staBudgetapprovalService.update(staBudgetapproval);
            if (mums > 0){
                int num = staReimbursementService.updateSpzt(fybz);
                if (num > 0) {
                    return BaseResult.success("数据作废成功!");
                }
            }
        }else {
            int num = staReimbursementService.updateSpzt(fybz);
            if (num > 0) {
                return BaseResult.success("数据作废成功!");
            }else{
                return BaseResult.failure("数据作废失败!");
            }
        }

            return BaseResult.failure("数据异常，请联系管理员!");
    }

    /**
     * 编辑数据（提交审批）
     *
     * @return
     */
    @RequestMapping(value = "/forApproveUpdate/{xmid}/{bzje}", method = RequestMethod.GET)
    public String forApproveUpdate(Model model,
                                   @PathVariable Integer xmid,
                                   @PathVariable(required = false) Double bzje,
                                   @RequestParam String spzt) {
       // 基本信息
        StaReimbursement reimbursement = staReimbursementService.queryById(xmid);
        model.addAttribute("reimbursement", reimbursement);

        //系统当前用户
        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 {
            StaReimbursement approve = staReimbursementService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(approve.getMc());
            approveInfo.setZt("数据不匹配");
            model.addAttribute("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();
            }
            model.addAttribute("postInfo", postInfo);
            model.addAttribute("xmid",xmid);

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

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

        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid.toString());
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            res.put("approveInfo", approveList.get(0));
        } else {
            StaReimbursement approve = staReimbursementService.queryById(xmid);
            PrjApproverecord approveInfo = new PrjApproverecord();
            approveInfo.setXmid(xmid);
            approveInfo.setXm(approve.getMc());
            approveInfo.setZt("数据不匹配");
            res.put("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();
            }
            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 "reimburse/list_approve";
    }

    /**
     * 导出列表到excel
     *
     * @param response
     */
    @ApiOperation(value = "导出全部数据到excel", notes = "导出全部数据到excel")
    @RequestMapping(value = "/exportExcel/{fromdata}", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletResponse response,@PathVariable(required = false) String fromdata)throws  Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        StaReimbursement formData = objectMapper.readValue(fromdata, StaReimbursement.class);
        Map<String, Object> paraMap = new HashMap<>();
        if (formData.getNf().equals("0")){
                    paraMap.put("nf","");
            }else {
                paraMap.put("nf",formData.getNf());
            }
        paraMap.put("fysqbh", formData.getFysqbh());
        paraMap.put("spzt", formData.getSpzt());
        paraMap.put("mc", formData.getMc());
        paraMap.put("bzr", formData.getBzr());
        paraMap.put("xmmc",formData.getXmmc());
        paraMap.put("erpbh",formData.getErpbh());
        List<StaReimbursement> reimburseList = staReimbursementService.getReimburseList(paraMap);
        List<String> listName = Arrays.asList("名称", "审批状态", "费用申请编号","ERP编号", "报账金额(元)", "不含税金额(元)", "税费(元)", "报账人", "创建时间", "费用申请名称");
        List<Map<String, String>> list = new ArrayList<>();
        for (StaReimbursement reimbursement : reimburseList) {
            Map<String, String> map = new HashMap<>();
            map.put("名称", reimbursement.getMc());
            map.put("审批状态", reimbursement.getSpzt());
            map.put("费用申请编号", reimbursement.getBh());
            map.put("ERP编号",reimbursement.getErpbh());
            if (reimbursement.getBzje() != null){
                map.put("报账金额(元)", reimbursement.getBzje().toString());
            }else {
                map.put("报账金额(元)", "0.00");
            }
            if (reimbursement.getBhsje() != null){
                map.put("不含税金额(元)", reimbursement.getBhsje().toString());
            } else{
                map.put("不含税金额(元)", "0.00");
            }
            if (reimbursement.getSf() != null){
                map.put("税费(元)", reimbursement.getSf().toString());
            }else {
                map.put("税费(元)", "0.00");
            }
            map.put("报账人", reimbursement.getBzrxm());
            map.put("创建时间", reimbursement.getCjsj().toString());
            map.put("费用申请名称", reimbursement.getFysqmc());
            list.add(map);
        }
        ExcelPoiUtil.excelPort("报账", listName, list, null, response);
    }

    /**
     * 更新审批状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/viewFile", method = RequestMethod.POST)
    public BaseResult viewFile(@RequestBody StaReimbursementDto reimbursementDto) {

        List<ViewFileVo> vo = staReimbursementService.viewFile(reimbursementDto.getBzId());
        return BaseResult.success(vo);
    }

    /**
     * 获取该年度项目总预算和已报账金额,该科目细目组预算，科目已申请报账金额
     *
     * @param fysq
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getZbjje/{fysq}/{fylb}", method = RequestMethod.POST)
    public BaseResult getZbjje(@PathVariable Integer fysq,@PathVariable Integer fylb) {
    // 获取该报账的年度预算id
        StaBudgetapproval sb = staBudgetapprovalService.queryById(fysq);
        Integer nys = sb.getNys();
//        通过年度预算id获取该年度已报账金额和项目总预算
        StaBudgetapproval staBudgetapproval =staBudgetapprovalService.getZbjje(nys,fylb);
        return BaseResult.success(staBudgetapproval);
    }
}

