/**
 * 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.entity.Information;
import com.jeeplus.modules.sg.audit.information.entity.OutInformation;
import com.jeeplus.modules.sg.audit.information.utils.FreemarkerUtil;
import com.jeeplus.modules.sg.audit.information.utils.RandomUtil;
import com.jeeplus.modules.sg.audit.information.utils.ResponseUtil;
import com.jeeplus.modules.sg.audit.material.entity.Material;
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.service.CostCheckService;
import com.jeeplus.modules.sg.financial.settlement.service.DonorMaterialService;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
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.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.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 概预算基本信息维护
 *
 * @author user3
 */
@Controller
@RequestMapping(value = "${adminPath}/donor/material")
public class DonorMaterialController extends BaseController {

    @Autowired
    private DonorMaterialService donorMaterialService;

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

    /**
     * 列表页面
     */
    @RequiresPermissions("donor:material:list")
    @RequestMapping(value = {"list", ""})
    public String list(DonorMaterial donorMaterial, Model model) {
        model.addAttribute("donorMaterial", donorMaterial);
        return "modules/sg/financial/settlement/donorMaterialList";
    }


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


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

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

    /**
     * 删除
     */
    @ResponseBody
    @RequiresPermissions("donor:material:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(DonorMaterial donorMaterial) {
        AjaxJson j = new AjaxJson();
        donorMaterialService.delete(donorMaterial);
        j.setMsg("删除成功");
        return j;
    }


    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("donor:material:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(DonorMaterial donorMaterial, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String st = "";
            String projectId = donorMaterial.getProjectId();
            if (StringUtils.isNotBlank(projectId)) {
                st = projectId;
            }
            //对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
            if (StringUtils.isNotBlank(st)) {
                String[] sts = st.split("\\s+");
                if (sts.length == 1) {
                    donorMaterial.setProjectId(sts[0]);
                } else {
                    donorMaterial.setProjectIds(sts);
                    donorMaterial.setProjectId(null);
                }
            }
            String fileName = "导出项目甲供材清单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            List<DonorMaterial> list = donorMaterialService.findList(donorMaterial);
            new ExportExcel("导出项目甲供材清单", DonorMaterial.class).setDataList(list).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出项目甲供材清单！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("donor:material: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<DonorMaterial> list = getData(ei);
            //保存费用检查信息
            String b = donorMaterialService.insertList(list);
            j.setMsg("导入成功" + b);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * excel文件数据读取
     */
    private List<DonorMaterial> getData(ImportExcel importExcel) throws ParseException {
        int lastRow = importExcel.getLastDataRowNum();
        List<DonorMaterial> list = new ArrayList<>();
        DonorMaterial donorMaterial;
        for (int i = 2; i < lastRow; i++) {
            donorMaterial = new DonorMaterial();
            Row row = importExcel.getRow(i);
            String projectId = (String) importExcel.getCellValue(row, 1);
            if (StringUtils.isNotBlank(projectId)) {
                donorMaterial.setProjectId(projectId);
                list.add(donorMaterial);
            }
        }
        return list;
    }

    /**
     * 项目甲供材管理 多文件导入页面
     */
    @RequestMapping(value = "/importMore/Form")
    public String importMoreForm(Model model) {
        return "modules/sg/financial/settlement/donorMore";
    }

    /**
     * 项目甲供材 多文件导入验证
     * 若项目甲供材中已经存在某些项目，则返回消息由操作者选择是否进行覆盖，否则直接导入甲供材明细
     */
    @ResponseBody
    @RequestMapping(value = "importValidations")
    public AjaxJson importValidations(@RequestParam("file") MultipartFile[] file) {
        AjaxJson j = new AjaxJson();
        List<DonorMaterial> list = new ArrayList<>();
        try {
            //获取项目名称列表
            for (int i = 0; i < file.length; i++) {
                ImportExcel module = new ImportExcel(file[i], 1, "预算封面");
                Row row = module.getRow(1);
                Object obj = module.getCellValue(row, 2);
                String projectId = ((String) obj).trim();
                DonorMaterial project = new DonorMaterial();
                project.setProjectId(projectId);
                list.add(project);
            }
            List<DonorMaterial> projects = donorMaterialService.findByList(list);
            //判断是否有已存在项目
            if (projects != null && projects.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (DonorMaterial donorMaterial : projects) {
                    stringBuilder.append(donorMaterial.getProjectId() + ",");
                }
                j.setMsg(stringBuilder.toString());
                j.setSuccess(true);
            } else {
                for (int k = 0; k < file.length; k++) {
                    donorMaterialService.saveData(file[k]);
                }
                j.setSuccess(true);
                j.setErrorCode("0");
                j.setMsg("导入成功");
            }
        } catch (Exception e) {
            j.setSuccess(true);
            j.setErrorCode("0");
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 甲供材文件导入覆盖后方法
     */
    @ResponseBody
    @RequiresPermissions("donor:material:import")
    @RequestMapping(value = "imports")
    public AjaxJson importFile(@RequestParam("file") MultipartFile[] file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            for (int i = 0; i < file.length; i++) {
                donorMaterialService.saveData(file[i]);
            }
            j.setMsg("导入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 项目甲供材修改甲供材信息备注
     */
    @ResponseBody
    @RequestMapping(value = "updateRemarks")
    public AjaxJson updateRemarks(DonorMaterial donorMaterial, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        donorMaterialService.updateRemarks(donorMaterial);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }

    @ResponseBody
    @RequiresPermissions("donor:material:export")
    @RequestMapping(value = "exportInformation")
    public void exportInformation(DonorMaterial donorMaterial, HttpServletRequest request, HttpServletResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        Template template = null;
        File path = new File(this.getClass().getResource("/").getPath() + "/freemarker");
        Configuration cfg = new Configuration();
        try {
            cfg.setDefaultEncoding("UTF-8");
            //配置cfg对象
            cfg.setDirectoryForTemplateLoading(path);
//            根据模板名称获取Template对象
            template = cfg.getTemplate("甲供物资超欠供说明.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        String st = "";
        String projectId = donorMaterial.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
        //对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                donorMaterial.setProjectId(sts[0]);
            } else {
                donorMaterial.setProjectIds(sts);
                donorMaterial.setProjectId(null);
            }
        }
        List<DonorMaterial> list = donorMaterialService.findALLRemarks(donorMaterial);
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(i + 1 + "." + list.get(i).getProjectName()
                    + "(" + list.get(i).getProjectId() + ")"
                    + ";物料编码："
                    + list.get(i).getMaterialCode()
                    + ";物料名称："
                    + list.get(i).getMaterialName()
                    + ";欠供说明："
                    + list.get(i).getRemarks()
            );
            stringBuilder.append("<w:br />");
        }
        data.put("mb", stringBuilder);
        File docFile = new File(path + "\\甲供物资超欠供说明.doc");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("甲供物资超欠供说明.doc", docFile, response);
    }

    /**
     * 删除Model
     * @param ids
     * @return
     */
    @ResponseBody
    @RequiresPermissions("donor:material:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        String idArray[] =ids.split(",");
        List<String> delList = new ArrayList<>();
        for(String id : idArray){
            delList.add(id);
        }
        HashSet set = new HashSet(delList);
        delList.clear();
        delList.addAll(set);
        //删除项目下所有的甲供材信息
        //修改该项目的甲供材状态
        donorMaterialService.delAll(delList);
        donorMaterialService.updateStatus(delList);
//        donorMaterialService.delete(id);
        AjaxJson j = new AjaxJson();
        j.setMsg("删除成功" );
        return j;
    }

}