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

import com.google.common.collect.Lists;
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.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sg.annualmaterialreport.entity.ExportDetails;
import com.jeeplus.modules.sg.annualmaterialreport.entity.NewMaterialReport;
import com.jeeplus.modules.sg.annualmaterialreport.entity.ReportDetails;
import com.jeeplus.modules.sg.annualmaterialreport.service.NewMaterialReportService;
import com.jeeplus.modules.sg.annualmaterialreport.service.ReportDetailsService;
import com.jeeplus.modules.sg.audit.information.entity.Information;
import com.jeeplus.modules.sg.audit.information.entity.append;
import com.jeeplus.modules.sg.audit.information.utils.ImportInformation;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.service.MaterialInfoService;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;

import com.jeeplus.modules.sg.managementcenter.materialproject.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.materialproject.util.MaterialProUtil;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.project.util.ProjectImportUtil;
import com.jeeplus.modules.sg.materialmodule.activiti.entity.NonPower;
import com.jeeplus.modules.sg.materialmodule.activiti.service.NonPowerService;
import com.jeeplus.modules.sg.picking.activiti.entity.ShowList;
import com.jeeplus.modules.sg.picking.activiti.service.ShowListService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.activiti.engine.repository.ProcessDefinition;
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.math.BigDecimal;
import java.util.*;


@Controller
@RequestMapping(value = "${adminPath}/new/materialProject")
public class NewMaterialProjectController extends BaseController {


    @Autowired
    private NewMaterialReportService newMaterialReportService;

    @Autowired
    private ReportDetailsService reportDetailsService;

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

    /**
     * 项目列表页面
     */
    @RequiresPermissions("new:materialProject:list")
    @RequestMapping(value = "list")
    public String list(NewMaterialReport newMaterialReport, Model model) {
        model.addAttribute("newMaterialReport", newMaterialReport);
        return "modules/sg/annualMaterialReport/newMaterialProjectList";
    }

    /**
     * 列表数据
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(NewMaterialReport newMaterialReport, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<NewMaterialReport> page = newMaterialReportService.findPage(new Page<NewMaterialReport>(request, response), newMaterialReport);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑表单页面
     */
    @RequiresPermissions(value = {"new:materialProject:view", "new:materialProject:add", "new:materialProject:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(NewMaterialReport newMaterialReport, Model model) {
        model.addAttribute("newMaterialReport", newMaterialReport);
        return "modules/sg/annualMaterialReport/newMaterialProjectForm";
    }

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

    /**
     * 删除项目
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(NewMaterialReport newMaterialReport) {
        AjaxJson j = new AjaxJson();
        newMaterialReportService.delete(newMaterialReport);
        j.setMsg("删除项目成功");
        return j;
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        AjaxJson j = new AjaxJson();
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            //通过id查询项目信息获取到储备项目名称，删除对应的年度物资上报信息及其明细信息
            NewMaterialReport newMaterialReport = newMaterialReportService.get(id);
            newMaterialReportService.delete(newMaterialReport);
            reportDetailsService.delByName(newMaterialReport);
        }
        j.setMsg("删除项目成功");
        return j;
    }


    /**
     * 年度物资上报模板下载
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:export")
    @RequestMapping(value = "templates")
    public AjaxJson importFileTemplateS(HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "年度物资上报统计模板.xlsx";
            List<append> list = Lists.newArrayList();
            new ExportExcel("", NewMaterialReport.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入送审下载失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 项目列表导出
     * @param newMaterialReport
     * @param request
     * @param response
     * @return 返回符合条件的项目列表excel
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:export")
    @RequestMapping(value = "export")
    public AjaxJson export(NewMaterialReport newMaterialReport, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "年度物资上报统计物料详细" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            List<ReportDetails> returnList = new ArrayList<>();
            List<NewMaterialReport> list = newMaterialReportService.findList(newMaterialReport);
            List<ReportDetails> reportDetailsList = reportDetailsService.exportList(list);
            HashMap<String, ReportDetails> map = new HashMap<String, ReportDetails>();
            for (ReportDetails a :
                    reportDetailsList) {
                String materialCode = a.getMaterialCode();
                String materialDescription = a.getMaterialDescription();
                String extendedDescription = a.getExtendedDescription();
                String s = materialCode + materialDescription + extendedDescription;
                if (map.containsKey(s)) {
                    ReportDetails reportDetails = map.get(s);
                    BigDecimal bigDecimal = new BigDecimal(reportDetails.getQuantity());
                    BigDecimal bigDecimal1 = new BigDecimal(a.getQuantity());
                    BigDecimal add = bigDecimal.add(bigDecimal1);
                    reportDetails.setQuantity(add.toString());
                    map.put(s, reportDetails);
                } else {
                    map.put(s, a);
                }
            }
            for (String r :
                    map.keySet()) {
                ReportDetails reportDetails = map.get(r);
                returnList.add(reportDetails);
            }
            new ExportExcel(null, ExportDetails.class).setDataList(returnList).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    /**
     * 项目列表导出
     * @param newMaterialReport
     * @param request
     * @param response
     * @return 返回符合条件的项目列表excel
     */
    @ResponseBody
    @RequiresPermissions("new:materialProject:export")
    @RequestMapping(value = "exportPro")
    public AjaxJson exportPro(NewMaterialReport newMaterialReport, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "年度物资上报统计" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<NewMaterialReport> page = newMaterialReportService.findPage(new Page<NewMaterialReport>(request, response, -1), newMaterialReport);
            new ExportExcel(null, NewMaterialReport.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出失败！失败信息：" + e.getMessage());
        }
        return j;
    }



    /**
     * 导入年度物资上报后续信息
     */
    @RequiresPermissions("new:materialProject:import")
    @ResponseBody
    @RequestMapping(value = "import")
    public AjaxJson importFileCom(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        List<NewMaterialReport> list = new ArrayList<>();
        int successNum = 0;
        try {
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            int lastDataRowNum = ei.getLastDataRowNum();
            for (int i = 1; i < lastDataRowNum; i++) {
                NewMaterialReport newMaterialReport = new NewMaterialReport();
                Row row = ei.getRow(i);
                String cellValue = (String) ei.getCellValue(row, 0);
                if (null == cellValue || "".equals(cellValue)) {
                    continue;
                }
                newMaterialReport.setReserveProjectName(cellValue);
                newMaterialReport.setReserveCode((String)ei.getCellValue(row, 1));
                newMaterialReport.setProjectType((String)ei.getCellValue(row, 2));
                newMaterialReport.setBatchPlan((String)ei.getCellValue(row, 3));
                newMaterialReport.setIssuePlan((String)ei.getCellValue(row, 4));
                newMaterialReport.setMonthPlan((String)ei.getCellValue(row, 5));
                newMaterialReport.setHasPlan((String)ei.getCellValue(row, 6));
                newMaterialReport.setHalfPlan((String)ei.getCellValue(row, 7));
                newMaterialReport.setProjectId((String)ei.getCellValue(row, 8));
                newMaterialReport.setProjectName((String)ei.getCellValue(row, 9));
                list.add(newMaterialReport);
                successNum++;
            }
            //批量更新年度物资上报信息
            newMaterialReportService.updateList(list);
            j.setMsg("已成功导入 " + successNum + " 项目管理记录" + failureMsg);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入项审定日期失败！失败信息：" + e.getMessage());
        }
        return j;
    }
}