package com.liang.controller;
//import java.util.Date;
import com.google.common.collect.Lists;

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.dao.PrjAnnualbudgetdetailDao;
import com.liang.entity.*;
import com.liang.service.*;
import com.liang.vo.PrjAnnualbudgetYzxqkVo;
import org.apache.ibatis.annotations.Select;
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 java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 年度预算修改记录控制器
 */
@Controller
@RequestMapping("/PrjAnnualBudgetRecord")
public class PrjAnnualBudgetRecordController extends BaseController {

    @Resource
    private PrjAnnualBudgetRecordService prjAnnualBudgetRecordService;
    @Resource
    private  PrjAnnualbudgetdetailService prjAnnualbudgetdetailService;

    @Resource
    private PrjAnnualbudgetXgjlService prjAnnualbudgetXgjlService;

    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;
    @Resource
    private PrjApproverecordService prjApproverecordService;
    @Resource
    private PrjAnnualbudgetdetailDao prjAnnualbudgetdetailDao;


    /**
     * 在年度预算修改记录表中添加修改前的数据（年度预算明细）
     *
     * @param nys 年度预算ID
     * @return
     */
    @ResponseBody
    @PostMapping("/addBudgetRecord/{ysId}")
    @Transactional
    public BaseResult addBudgetRecord(@PathVariable("ysId") Integer nys) {
//        1.获取年度预算明细列表中的数据
        List<PrjAnnualbudgetdetail> xgjl = prjAnnualbudgetdetailService.getXGJL(nys);
//        查询当前为第几次记录
        List<PrjAnnualbudgetXgjl> xgjls = prjAnnualbudgetXgjlService.getXGJL(nys);
//        获取当前年度预算审批状态
        PrjAnnualbudget prjAnnualbudget = prjAnnualbudgetService.queryById(nys);
        int xh = xgjls.size()+1;
        List<PrjAnnualbudgetXgjl> prjAnnualbudgetXgjlList = new ArrayList<>();
        for (int i = 0; i < xgjl.size(); i++) {
            PrjAnnualbudgetXgjl prjAnnualbudgetXgjl= new PrjAnnualbudgetXgjl();
            prjAnnualbudgetXgjl.setNys(nys);
            prjAnnualbudgetXgjl.setFymc(xgjl.get(i).getFymc());
            prjAnnualbudgetXgjl.setXg(xgjl.get(i).getXgjlxz());
            prjAnnualbudgetXgjl.setXgrq(new Date(System.currentTimeMillis()).toString());
            prjAnnualbudgetXgjl.setXh(xh);
            prjAnnualbudgetXgjlList.add(prjAnnualbudgetXgjl);
        }
        if (prjAnnualbudget.getSpzt().equals("审批结束")){
            prjAnnualbudgetXgjlService.batchinsertXGJL(prjAnnualbudgetXgjlList);
        }
        return BaseResult.success();
    }

    /**
     * 年度预算修改记录查看页面
     *
     * @return
     */
    @GetMapping("/viewRecord")
    public String viewRecord() {
        return "annualbudget/view_record";
    }


    @ResponseBody
    @RequestMapping(value = "/redordData/{xmid}", method = RequestMethod.POST)
    public BaseResult spList(@PathVariable int xmid,
                             @RequestParam("page") Integer pageNum,
                             @RequestParam("limit") Integer pageSize,
                             @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                             @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        PageHelper.startPage(pageNum, pageSize);
        List<PrjAnnualbudgetdetail> list = prjAnnualbudgetdetailService.getXGJL(xmid);
        List<PrjAnnualbudgetdetail> sortedList = new ArrayList<>();

        Map<String, List<PrjAnnualbudgetdetail>> treeMap = new HashMap<>();
        for (PrjAnnualbudgetdetail prjAnnualbudgetdetail : list) {
            treeMap.computeIfAbsent(prjAnnualbudgetdetail.getFj(), k -> new ArrayList<>()).add(prjAnnualbudgetdetail);
        }
        buildTree(treeMap, "", sortedList);



        PageInfo<PrjAnnualbudgetdetail> pageinfo = new PageInfo<>(sortedList);
        //取出查询结果
        List<PrjAnnualbudgetdetail> 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 = "/addUpdateApplyRecord", method = RequestMethod.POST)
    public BaseResult addUpdateApplyRecord(
            @RequestBody String data) {
        List<PrjAnnualBudgetRecord> record =new ArrayList<>();
        List<PrjAnnualbudgetdetail> budgetDetails = JsonTool.parseArray(data, PrjAnnualbudgetdetail.class);
        for (int i = 0; i <budgetDetails.size() ; i++) {
            PrjAnnualBudgetRecord prjAnnualBudgetRecord =new PrjAnnualBudgetRecord();
            prjAnnualBudgetRecord.setFymc(budgetDetails.get(i).getFymc());
            prjAnnualBudgetRecord.setYsje(budgetDetails.get(i).getYsje());
            prjAnnualBudgetRecord.setNys(budgetDetails.get(i).getNys());
            prjAnnualBudgetRecord.setBm(budgetDetails.get(i).getBm());
            prjAnnualBudgetRecord.setFj(budgetDetails.get(i).getFj());
            prjAnnualBudgetRecord.setNf(budgetDetails.get(i).getNf());
            prjAnnualBudgetRecord.setXmz(budgetDetails.get(i).getXmz());
            prjAnnualBudgetRecord.setByj(budgetDetails.get(i).getByj());
            prjAnnualBudgetRecord.setXmzys(budgetDetails.get(i).getXmzys());
            prjAnnualBudgetRecord.setBjsj(new Date(System.currentTimeMillis()));
            prjAnnualBudgetRecord.setXgr(getSysUserId());
            record.add(prjAnnualBudgetRecord);
        }
//先删除表中的预留数据（只能保存一份）
        prjAnnualBudgetRecordService.deleteHistoryRecord(budgetDetails.get(0).getNys());
//插入到修改申请表中(临时保存表)
        int i = prjAnnualBudgetRecordService.addHistoryRecord(record);
        if (i>0){
            return BaseResult.success();
        }else {
            return BaseResult.failure("");
        }
    }
    /**
     * 审批列表
     *
     * @return
     */
    @RequestMapping(value = "/forApproveList", method = RequestMethod.GET)
    public String forApproveList() {
        return "annualbudget/xglist_approve";
    }
    /**
     * 查看数据
     *
     * @return
     */
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        List<PrjAnnualbudgetdetail> budgetList = prjAnnualbudgetdetailService.getSptgZt(id);
        //获取已执行情况
//        List<PrjAnnualbudgetYzxqkVo> yzxqkVos = prjAnnualbudgetdetailDao.getYzxqk(id);
        List<PrjAnnualBudgetRecord> record = prjAnnualBudgetRecordService.queryRecordByNdysid(id);
        model.addAttribute("prjAnnualbudget",budgetList);
        model.addAttribute("prjAnnualbudgetRecord",record);
        model.addAttribute("ysId",id);
        return "annualbudget/xgview_record";
    }

    /**
     * 将中间表中的数据同步到年度预算列表中
     * */
    @ResponseBody
    @RequestMapping(value = "/doUpdate/{xmid}", method = RequestMethod.POST)
    @Transactional
    public BaseResult bathUpdate( @PathVariable Integer xmid) {
//  1.获取年度预算中间表情数据
        List<PrjAnnualBudgetRecord> record = prjAnnualBudgetRecordService.queryRecordByNdysid(xmid);
//  2.修改年度预算明细表的内容
        int  i =prjAnnualbudgetdetailService.updateXg(record);
        if (i>0){
// 3.保存成功后删除中间表中的数据
            prjAnnualBudgetRecordService.deleteHistoryRecord(xmid);
//  4.修改年度预算表中的sfsp状态
            prjAnnualbudgetService.updateSFXG(xmid);
            return BaseResult.success();
        }else {
            return BaseResult.failure("记录保存失败");
        }


    }

    @RequestMapping(value = "/forApproveUpdate/{xmid}", method = RequestMethod.GET)
    public String forApproveUpdate(Model model, @PathVariable Integer xmid, @RequestParam String spzt) {
        //系统当前用户
        SysUserInfo userInfo = getSysUserInfo();
        model.addAttribute("userInfo", userInfo);

        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("xmid", xmid.toString());
        paraMap1.put("zt", spzt);
        paraMap1.put("wc", "0");
        List<PrjApproverecord> approveList = prjApproverecordService.getApproveByXmId(paraMap1);
        if (approveList.size() > 0) {
            model.addAttribute("approveInfo", approveList.get(0));
        }
        return "annualbudget/finish_xg_approve";
    }

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