/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.financial.settlement.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.sg.audit.information.utils.FreemarkerUtil;
import com.jeeplus.modules.sg.audit.information.utils.ResponseUtil;
import com.jeeplus.modules.sg.financial.settlement.entity.CostCheck;
import com.jeeplus.modules.sg.financial.settlement.entity.DonorMaterial;
import com.jeeplus.modules.sg.financial.settlement.entity.ProjectBudget;
import com.jeeplus.modules.sg.financial.settlement.service.CostCheckService;
import com.jeeplus.modules.sg.financial.settlement.service.ProjectBudgetService;

import com.jeeplus.modules.sg.financial.settlement.util.MyExportUtil;
import com.jeeplus.modules.sys.utils.DictUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 概预算基本信息维护
 */
@Controller
@RequestMapping(value = "${adminPath}/cost/check")
public class CostCheckController extends BaseController {

    @Autowired
    private CostCheckService costCheckService;

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

    /**
     * 列表页面
     */
    @RequiresPermissions("cost:check:list")
    @RequestMapping(value = {"list", ""})
    public String list(CostCheck costCheck, Model model) {
        model.addAttribute("costCheck", costCheck);
        return "modules/sg/financial/settlement/costCheckList";
    }


    /**
     * 列表数据
     */
    @ResponseBody
    @RequiresPermissions("cost:check:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(CostCheck costCheck, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
        String st = "";
        String projectId = costCheck.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                costCheck.setProjectId(sts[0]);
            } else {
                costCheck.setProjectIds(sts);
                costCheck.setProjectId(null);
            }
        }
        Page<CostCheck> page = costCheckService.findPage(new Page<CostCheck>(request, response), costCheck);
        return getBootstrapData(page);
    }


    /**
     * 查看，增加，编辑表单页面
     */
    @RequiresPermissions(value = {"cost:check:view", "cost:check:add", "cost:check:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(CostCheck costCheck, Model model) {
        model.addAttribute("costCheck", costCheck);
        return "modules/sg/financial/settlement/dataMaintenanceForm";
    }

    /**
     * 保存
     */
    @ResponseBody
    @RequiresPermissions(value = {"cost:check:add", "cost:check:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(CostCheck costCheck, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(costCheck);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        costCheckService.save(costCheck);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequiresPermissions("cost:check:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(CostCheck costCheck) {
        AjaxJson j = new AjaxJson();
        costCheckService.delete(costCheck);
        j.setMsg("删除成功");
        return j;
    }


    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("cost:check:export")
    @RequestMapping(value = "export")
    public void exportFile(CostCheck costCheck, HttpServletRequest request, HttpServletResponse response) {
            String st = "";
            String projectId = costCheck.getProjectId();
            if (StringUtils.isNotBlank(projectId)) {
                st = projectId;
            }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
            if (StringUtils.isNotBlank(st)) {
                String[] sts = st.split("\\s+");
                if (sts.length == 1) {
                    costCheck.setProjectId(sts[0]);
                } else {
                    costCheck.setProjectIds(sts);
                    costCheck.setProjectId(null);
                }
            }
            List<CostCheck> list = costCheckService.findList(costCheck);
            for (CostCheck c :
                    list) {
                String conPay = DictUtils.getDictLabel(c.getConstructionUnderPayment(), "finance_underpayment", "");
                String desPay = DictUtils.getDictLabel(c.getDesignUnderPayment(), "finance_underpayment", "");
                String supPay = DictUtils.getDictLabel(c.getSupervisorUnderPayment(), "finance_underpayment", "");
                if ("请选择".equals(conPay)) {
                    c.setConstructionUnderPayment("");
                } else {
                    c.setConstructionUnderPayment(conPay);
                }
                if ("请选择".equals(desPay)) {
                    c.setDesignUnderPayment("");
                } else {
                    c.setDesignUnderPayment(desPay);
                }
                if ("请选择".equals(supPay)) {
                    c.setSupervisorUnderPayment("");
                } else {
                    c.setSupervisorUnderPayment(supPay);
                }
            }
        MyExportUtil util = MyExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("costCheck");
        util.exportExcelOne(response,workbook,list);
    }

    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("cost:check:import")
    @RequestMapping(value = "import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel ei = new ImportExcel(file, 2, "送审单");
            List<CostCheck> list = getData(ei);
            //保存费用检查信息
            String b = costCheckService.insertConstructionList(list);
            j.setMsg("导入成功" + b);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * excel文件数据读取
     */
    private List<CostCheck> getData(ImportExcel importExcel) throws ParseException {
        int lastRow = importExcel.getLastDataRowNum();
        List<CostCheck> list = new ArrayList<>();
        CostCheck costCheck;
        String construction_fee_rates = DictUtils.getDictLabel("1.09", "construction_fee_rates", "");
        BigDecimal rates = new BigDecimal(construction_fee_rates);
        for (int i = 2; i < lastRow; i++) {
            costCheck = new CostCheck();
            Row row = importExcel.getRow(i);
            String projectId = (String) importExcel.getCellValue(row, 1);
            if (StringUtils.isNotBlank(projectId)) {
                costCheck.setProjectId(projectId);
                double aDouble = getDouble(importExcel, row, 34);
                BigDecimal bigDecimal = new BigDecimal(aDouble);
                BigDecimal setScale = bigDecimal.divide(rates, 2, BigDecimal.ROUND_HALF_UP);
                costCheck.setConstructionAmountDue(Double.valueOf(setScale.toString()));
                list.add(costCheck);
            }
        }
        return list;
    }

    /**
     * 获取excel double类型的值
     */
    private double getDouble(ImportExcel importExcel, Row row, int col) {
        double d = 0.00;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("") && !o.equals("-")) {
            d = Double.parseDouble(o.toString());
        }
        return d;
    }

    /**
     * 获取excel double类型的值(折扣比率值，不能小于1.0)
     */
    private double getDisCount(ImportExcel importExcel, Row row, int col) {
        double d = 1.00;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("")) {
            d = Double.parseDouble(o.toString());
        }
        return d;
    }

    /**
     * 获取excel date类型的值
     */
    private Date getDate(ImportExcel importExcel, Row row, int col) throws ParseException {
        Date d = null;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            d = simpleDateFormat.parse(o.toString());
        }
        return d;
    }

    /**
     * 获取excel String类型的值
     */
    private String getString(ImportExcel importExcel, Row row, int col) throws ParseException {
        String str = "";
        Object o = importExcel.getCellValue(row, col);
        if (null != o && !"".equals(o)) {
            str = String.valueOf(o);
        }
        return str;
    }

    /**
     * 修改施工费允许少付
     */
    @ResponseBody
    @RequestMapping(value = "updateDes")
    public AjaxJson updateDes(CostCheck costCheck, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        costCheckService.updateDes(costCheck);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }

    /**
     * 修改设计费允许少付
     */
    @ResponseBody
    @RequestMapping(value = "updateCon")
    public AjaxJson updateCon(CostCheck costCheck, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        costCheckService.updateCon(costCheck);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }

    /**
     * 修改监理费允许少付
     */
    @ResponseBody
    @RequestMapping(value = "updateSup")
    public AjaxJson updateSup(CostCheck costCheck, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        costCheckService.updateSup(costCheck);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }
}