/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.project.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.sg.managementcenter.materialInventory.service.MaterialInventoryService;
import com.jeeplus.modules.sg.managementcenter.project.entity.BasicInformation;
import com.jeeplus.modules.sg.managementcenter.project.entity.CapitalPlan;
import com.jeeplus.modules.sg.managementcenter.project.entity.ImportErp;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.CapitalPlanService;
import com.jeeplus.modules.sg.managementcenter.project.service.PickingRequisitionService;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.project.util.CapitalImportUtil;
import com.jeeplus.modules.sg.managementcenter.project.util.ProjectImportUtil;
import com.jeeplus.modules.sys.service.SystemService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 资金计划管理
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/capitalPlan")
public class CapitalPlanController extends BaseController {

    @Autowired
    private CapitalPlanService capitalPlanService;


    @ModelAttribute
    public CapitalPlan get(@RequestParam(required = false) String id) {
        CapitalPlan entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = capitalPlanService.get(id);
        }
        if (entity == null) {
            entity = new CapitalPlan();
        }
        return entity;
    }

    /**
     * 资金计划管理页面
     */
    @RequestMapping(value = "capitalPlanList")
    @RequiresPermissions("sg:managementcenter:capitalPlanList:list")
    public String capitalPlanList(CapitalPlan capitalPlan, Model model) {
        model.addAttribute("capitalPlan", capitalPlan);
        return "modules/sg/capitalPlan/capitalPlanList";
    }

    /**
     * 修改项目费率页面
     */
    @RequestMapping(value = "editRate")
    public String editRate(CapitalPlan capitalPlan, Model model) {
        model.addAttribute("capitalPlan", capitalPlan);
        return "modules/sg/capitalPlan/editRate";
    }



    /**
     * 资金计划管理 数据列表
     */
    @ResponseBody
    @RequestMapping(value = "capitalPlanData")
    public Map<String, Object> basicData(CapitalPlan capitalPlan, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<CapitalPlan> page = capitalPlanService.findPage(new Page<CapitalPlan>(request, response), capitalPlan);
        List<CapitalPlan> list = page.getList();
        for (CapitalPlan c:list) {
            //项目预算
            String projectBudget = c.getProjectBudget();
            //项目实际费用
            String actualCost = c.getActualCost();
            //施工费
            String constructionCost = c.getConstructionCost();
            //实际施工费
            String actualConstructionCost = c.getActualConstructionCost();
            //物资费
            String materialCost = c.getMaterialCost();
            //项目实际物资费
            String actualMaterialCost = c.getActualMaterialCost();
            //设计费
            String designFee = c.getDesignFee();
            //项目实际设计费
            String actualDesignCost = c.getActualDesignCost();
            //监理费
            String supervisionFee = c.getSupervisionFee();
            //应付监理费
            String supervisionPayFee = c.getSupervisionPayFee();
            //项目实际监理费
            String actualSupervisionCost = c.getActualSupervisionCost();
            //政策处理费用
            String policyProcessingFee = c.getPolicyProcessingFee();
            //项目实际管理费
            String actualManagementFee = c.getActualManagementFee();
            //其他费用
            String otherExpenses = c.getOtherExpenses();
            //实际其他费用
            String actualOtherCost = c.getActualOtherCost();
            //设计费费率
            String designRate = c.getDesignRate();
            //监理费费率
            String supervisionRate = c.getSupervisionRate();
            //判断费率是否为空值，为空值，自动配置为0
            if (null == designRate || "".equals(designRate)) {
                designRate = "0";
            }
            if (null==supervisionRate || "".equals(supervisionRate)) {
                supervisionRate = "0";
            }

            //将空值初始化
            projectBudget = getString(projectBudget);
            actualCost = getString(actualCost);
            constructionCost = getString(constructionCost);
            actualConstructionCost = getString(actualConstructionCost);
            materialCost = getString(materialCost);
            actualMaterialCost = getString(actualMaterialCost);
            designFee = getString(designFee);
            actualDesignCost = getString(actualDesignCost);
            supervisionPayFee = getString(supervisionPayFee);
            actualSupervisionCost = getString(actualSupervisionCost);
            policyProcessingFee = getString(policyProcessingFee);
            actualManagementFee = getString(actualManagementFee);
            otherExpenses = getString(otherExpenses);
            actualOtherCost = getString(actualOtherCost);
            supervisionFee = getString(supervisionFee);


            BigDecimal projectDifference = new BigDecimal(projectBudget);
            BigDecimal constructionDifference = new BigDecimal(constructionCost);
            BigDecimal costDifference = new BigDecimal(materialCost);
            //设计费
            BigDecimal designFeeDiff = new BigDecimal(designFee);
            //监理费
            BigDecimal supervisionPayFeeDiff = new BigDecimal(supervisionPayFee);
            BigDecimal policyDifference = new BigDecimal(policyProcessingFee);
            BigDecimal otherDifference = new BigDecimal(otherExpenses);
            //设计费费率
            BigDecimal designRateDiff = new BigDecimal(designRate);
            //监理费费率
            BigDecimal supervisionRateDiff = new BigDecimal(supervisionRate);
            //监理费
            BigDecimal supervisionFeeDiff = new BigDecimal(supervisionFee);

            //项目预算-项目实际费用
            projectDifference = projectDifference.subtract(new BigDecimal(actualCost));
            //施工费-实际施工费
            constructionDifference = constructionDifference.subtract(new BigDecimal(actualConstructionCost));
            //物资费-项目实际物资费
            costDifference = costDifference.subtract(new BigDecimal(actualMaterialCost));
            //应付设计费=设计费*费率
            BigDecimal multiply = designRateDiff.multiply(designFeeDiff);
            //应付设计费-实际设计费
            BigDecimal designDifference = multiply.subtract(new BigDecimal(actualDesignCost));
//            supervisionDifference = supervisionDifference.subtract();
            policyDifference = policyDifference.subtract(new BigDecimal(actualManagementFee));
            otherDifference = otherDifference.subtract(new BigDecimal(actualOtherCost));
            designRateDiff = designRateDiff.multiply(new BigDecimal(designFee));
            //应付监理费=监理费*监理费费率
            BigDecimal multiply1 = supervisionFeeDiff.multiply(supervisionRateDiff);
            //应付-实际，监理差额
            BigDecimal supervisionDifference = multiply1.subtract(new BigDecimal(actualSupervisionCost));


            c.setProjectDifference(projectDifference.toString());
            c.setConstructionDifference(constructionDifference.toString());
            c.setCostDifference(costDifference.toString());
            c.setDesignDifference(designDifference.toString());
            c.setSupervisionDifference(supervisionDifference.toString());
            c.setPolicyDifference(policyDifference.toString());
            c.setOtherDifference(otherDifference.toString());
            c.setDesignPayFee(designRateDiff.toString());
            c.setSupervisionPayFee(multiply1.toString());

        }
        return getBootstrapData(page);
    }

    private String getString(String projectBudget) {
        if (null == projectBudget || "".equals(projectBudget)) {
            projectBudget = "0";
        }
        return projectBudget;
    }


    /**
     * 保存表单
     */
    @ResponseBody
    @RequestMapping(value = "saveEdit")
    public AjaxJson saveEdit(CapitalPlan capitalPlan, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        capitalPlanService.saveEdit(capitalPlan);
        j.setSuccess(true);
        j.setMsg("修改费率成功");
        return j;
    }




    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequestMapping(value = "importCapital")
    public AjaxJson importCapital(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 0,0);
            int lastDataRowNum = importExcel.getLastDataRowNum();
            //将写入的文件先进行规则验证
            Map<String, List<ImportErp>> projectGroupList = CapitalImportUtil.getProjectGroup(importExcel, lastDataRowNum);
            Iterator<String> iterator = projectGroupList.keySet().iterator();
            List<CapitalPlan> afterList = new ArrayList<>();
            while (iterator.hasNext()) {
                String key = iterator.next().toString();
                List<ImportErp> importErpList = projectGroupList.get(key);
                CapitalPlan capitalPlan = new CapitalPlan();
                BigDecimal actualCost = new BigDecimal("0");
                BigDecimal actualConstructionCost = new BigDecimal("0");
                BigDecimal actualMaterialCost = new BigDecimal("0");
                BigDecimal actualDesignCost = new BigDecimal("0");
                BigDecimal actualSupervisionCost = new BigDecimal("0");
                BigDecimal actualOtherCost = new BigDecimal("0");
                for (ImportErp i:importErpList) {
                    //根据每个项目定义号获得集合，计算每个项目定义号的项目金额、施工费、物资费、设计费、监理费、政策处理费、其它费用
                    //科目名称
                    String accountName = i.getAccountName();
                    //物料描述
                    String itemDescription = i.getItemDescription();
                    //WBS描述
                    String description = i.getDescription();

                    //项目预算
                    if (accountName.contains("工程成本-")) {
                        actualCost = actualCost.add(new BigDecimal((String) i.getLineAmount()));
                    }

                    //施工费
                    if ("".equals(itemDescription) && accountName.contains("工程成本-安装工程支出")) {
                        actualConstructionCost = actualConstructionCost.add(new BigDecimal((String) i.getLineAmount()));
                    }

                    //物资费（设备费+材料费）
                    if (!"".equals(itemDescription)) {
                        actualMaterialCost = actualMaterialCost.add(new BigDecimal((String) i.getLineAmount()));
                    }
                    //设计费
                    if ("".equals(itemDescription)) {
                        if (accountName.contains("工程成本-待摊支出-其他") || accountName.contains("工程成本-待摊支出-项目法人管理费-其他") || accountName.contains("项目管理经费 - 会议费")) {
                            if (description.contains("工程监理费")) {
                                //监理费
                                actualSupervisionCost = actualSupervisionCost.add(new BigDecimal((String) i.getLineAmount()));
                            } else if (description.contains("工程设计费")) {
                                //设计费
                                actualDesignCost = actualDesignCost.add(new BigDecimal((String) i.getLineAmount()));
                            } else {
                                //其它费用
                                actualOtherCost = actualOtherCost.add(new BigDecimal((String) i.getLineAmount()));
                            }
                        }
                    }
                    //政策处理费
                }
                //********************************************************//
                capitalPlan.setProjectId(key);
                capitalPlan.setActualCost(actualCost.toString());
                capitalPlan.setActualConstructionCost(actualConstructionCost.toString());
                capitalPlan.setActualMaterialCost(actualMaterialCost.toString());
                capitalPlan.setActualDesignCost(actualDesignCost.toString());
                capitalPlan.setActualSupervisionCost(actualSupervisionCost.toString());
                capitalPlan.setActualOtherCost(actualOtherCost.toString());
                afterList.add(capitalPlan);
            }

            //查询出所有的立项信息项目定义号进行插入操作
            List<String> strings = capitalPlanService.allProjectId();
            List<CapitalPlan> canInertList = new ArrayList<>();
            for (CapitalPlan c : afterList) {
                for (String a : strings) {
                    if (c.getProjectId().equals(a)) {
                        canInertList.add(c);
                    }
                }
            }

            //查询出所有的立项信息的projectId
            List<String> planProjectId = capitalPlanService.findPlanProjectId();
            List<CapitalPlan> updateList = new ArrayList<>();
            List<CapitalPlan> insertList = new ArrayList<>();
            for (CapitalPlan c : canInertList) {
                if (checkFlag(c.getProjectId(), planProjectId)) {
                    insertList.add(c);
                } else {
                    updateList.add(c);
                }
            }
            if (updateList.size() > 0) {
                capitalPlanService.updateList(updateList);
            }
            if (insertList.size() > 0) {
                capitalPlanService.insertList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("导入成功！");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;

    }

    /**
     * 判断是否包含规定值
     * string【】写入静态数据比对
     */
    private static Boolean checkFlag(String name, List<String> strings) {
        boolean flag = true;
        for (String str : strings) {
            if (str.equals(name)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

}