package com.jeeplus.modules.sg.settActivi.web;

import com.google.common.collect.Maps;
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.audit.information.entity.Information;
import com.jeeplus.modules.sg.audit.information.utils.FreemarkerUtil;
import com.jeeplus.modules.sg.audit.information.utils.ImportInformation;
import com.jeeplus.modules.sg.audit.information.utils.ResponseUtil;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project1;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.settActivi.entity.SettActivi;
import com.jeeplus.modules.sg.settActivi.entity.SettList;
import com.jeeplus.modules.sg.settActivi.service.SettActiviService;
import com.jeeplus.modules.sys.utils.UserUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.poi.ss.usermodel.Row;
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 java.io.*;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/settActivi")
public class SettActiviController extends BaseController {
    @Autowired
    private SettActiviService settActiviService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private ProjectService projectService;

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

    /**
     * 填写项目表
     */
    @RequestMapping(value = "start")
    public String form(SettActivi settActivi, Model model) {
        model.addAttribute("settActivi", settActivi);
        return "modules/sg/settactivi/activiti/settActiviStart";
    }

    /**
     * 填写现场使用数量页面
     */
    @RequestMapping(value = "usequantity")
    public String useQuantity(SettActivi settActivi, Model model) {
        model.addAttribute("settActivi", settActivi);
        return "modules/sg/settactivi/activiti/useQuantity";
    }

    /**
     * 审计现场复核数量
     */
    @RequestMapping(value = "reviewQuantity")
    public String reviewQuantity(SettActivi settActivi, Model model) {
        model.addAttribute("settActivi", settActivi);
        return "modules/sg/settactivi/activiti/reviewQuantity";
    }

    /**
     * 生成领料退料单
     */
    @RequestMapping(value = "returndoc")
    public String returnDoc(SettActivi settActivi, Model model) {
        model.addAttribute("settActivi", settActivi);
        return "modules/sg/settactivi/activiti/returnDoc";
    }

    /**
     * 修改现场使用数量
     */
    @ResponseBody
    @RequestMapping(value = "updateUsed")
    public AjaxJson updateUsed(SettList settList, String usedQuantity, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        //获取新的数量
        Double aDouble = Double.valueOf(usedQuantity);
        settList.setUsedQuantity(aDouble);
        settActiviService.updateUsed(settList);
        j.setMsg("成功");
        return j;
    }

    /**
     * 审计现场复核数量
     */
    @ResponseBody
    @RequestMapping(value = "updateReviewQuantity")
    public AjaxJson updateReviewQuantity(SettList settList, String reviewQuantity, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        //获取新的数量
        Double aDouble = Double.valueOf(reviewQuantity);
        settList.setReviewQuantity(aDouble);
        settActiviService.updateReviewQuantity(settList);
        j.setMsg("成功");
        return j;
    }

    /**
     * 修改施工单位备注
     */
    @ResponseBody
    @RequestMapping(value = "updateSettMark")
    public AjaxJson updateSettMark(SettList settList, String settMark, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        //获取新的数量
        settList.setSettMark(settMark);
        settActiviService.updateSettMark(settList);
        j.setMsg("成功");
        return j;
    }


    @ResponseBody
    @RequestMapping(value = "useQuantityData")
    public Map<String, Object> useQuantityData(SettList settList, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<SettList> page = settActiviService.useQuantityData(new Page<SettList>(request, response), settList);
        return getBootstrapData(page);
    }


    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequestMapping(value = "exportSett")
    public AjaxJson exportSett(SettList settList, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "竣工甲供材核对表" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<SettList> page = settActiviService.useQuantityData(new Page<SettList>(request, response), settList);
            new ExportExcel("竣工甲供材核对表", SettList.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;
    }


    /**
     * 验收流程批量发起
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(HttpServletResponse response, HttpServletRequest request, SettActivi settActivi, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String projectId = settActivi.getProjectId();
        if (projectId == null || "".equals(projectId)) {
            j.setMsg("请选择项目");
            j.setSuccess(false);
            return j;
        }

        String errMsg = beanValidator(settActivi);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        Map<String, Object> vars = Maps.newHashMap();
        //根据选择的项目查询项目信息
        Project project = new Project();
        project.setId(settActivi.getProjectId());
        Project ass = projectService.getAss(project);
        settActivi.setProjectId(ass.getProjectId());
        settActivi.setProjectName(ass.getProjectName());
        settActivi.setReserveProjectName(ass.getReserveProjectName());
        settActiviService.insertSett(settActivi);
        projectService.updateJsStatus("1", ass.getReserveProjectName());
        vars.put("manager", UserUtils.getByUserName(ass.getAssignment().getOwnerManager()).getLoginName());
        ProcessDefinition p = actProcessService.getProcessDefinition(settActivi.getAct().getProcDefId());
        String title = UserUtils.getUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
        actTaskService.startProcess(p.getKey(), "xm_settlement_process", settActivi.getId(), title, vars);
      /*  vars.put("manager", UserUtils.getByUserName(byIdList.get()).getLoginName());
        ProcessDefinition p = actProcessService.getProcessDefinition(settActivi.getAct().getProcDefId());
        String title = settActivi.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
        actTaskService.startProcess(p.getKey(), "xm_settlement_process", set.getId(), title, vars);*/
       /* //读取文件，获取文件信息
        ImportExcel importExcel = new ImportExcel(file, 1, 0);
        int lastDataRowNum = importExcel.getLastDataRowNum();
        Row row = null;
        List<SettList> settLists = new ArrayList<>();
        for (int i = 1; i < lastDataRowNum; i++) {
            SettList settList = new SettList();
            row = importExcel.getRow(i);
            //项目定义编码
            Object projectNumber = importExcel.getCellValue(row, 10);
            //项目定义编码
            Object requireName = importExcel.getCellValue(row, 11);
            //金额
            Object totalPrice = importExcel.getCellValue(row, 15);
            //数量
            Object outgoingQuantity = importExcel.getCellValue(row, 16);
            //编码
            Object materialEncoding = importExcel.getCellValue(row, 18);
            //描述
            Object materialName = importExcel.getCellValue(row, 19);
            //单位
            Object company = importExcel.getCellValue(row, 20);
            settList.setProjectId(projectNumber.toString());
            settList.setMaterialEncoding(materialEncoding.toString());
            settList.setMaterialName(materialName.toString());
            settList.setCompany(company.toString());
            settList.setRequireName(requireName.toString());
            Double oQ = Double.valueOf(outgoingQuantity.toString());
            Double tP = Double.valueOf(totalPrice.toString());
            settList.setOutgoingQuantity(oQ);
            settList.setTotalPrice(tP);
            double v = tP / oQ;
            settList.setUnitPrice(v);
            settLists.add(settList);
        }
        Map<String, Object> vars = Maps.newHashMap();
        //将选择的项目信息存入结算流程表中
        settActiviService.insertSettActivi(byIdList);
        //根据项目需求名称查询出本次所有
        List<SettActivi> allSett = settActiviService.findAllSett(byIdList);
        //跟新项目的状态
        settActiviService.updateSetStatus(allSett);
        for (SettActivi set : allSett) {
            vars.put("manager", UserUtils.getByUserName(set.getConstructionUnitManage()).getLoginName());
            ProcessDefinition p = actProcessService.getProcessDefinition(settActivi.getAct().getProcDefId());
            String title = settActivi.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcess(p.getKey(), "xm_settlement_process", set.getId(), title, vars);
        }
        List<SettActivi> allSett1 = settActiviService.findAllSett(byIdList);
        for (SettActivi a : allSett1) {
            List<SettList> lists = new ArrayList<>();
            for (SettList list : settLists) {
                if (a.getProjectName().equals(list.getRequireName())) {
                    list.setProcInsId(a.getProcInsId());
                    lists.add(list);
                }
            }
            if (lists.size()>0) {
                settActiviService.insertSettList(lists);
            }
        }*/
        j.setMsg("发起领料流程成功!");
        j.getBody().put("targetUrl", "/act/task/process/");
        return j;
    }


    //导出excel
    @ResponseBody
    @RequestMapping(value = "exportExcel")
    public void exportExcel(SettList settList, HttpServletRequest request, HttpServletResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        Template template = null;
        response.setContentType("text/text;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        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("jiesuan.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        Page<SettList> page = settActiviService.useQuantityData(new Page<SettList>(request, response), settList);
        List<SettList> list = page.getList();
        int i = 1;
        for (SettList s : list) {
            s.setId(String.valueOf(i));
            i++;
        }
        data.put("list", list);
        SettActivi settActivi = settActiviService.exportFind(settList.getProcInsId());
        data.put("projectId", settActivi.getProjectId());
        data.put("projectName", settActivi.getProjectName());
        data.put("manager", settActivi.getConstructionUnitManage());
        File docFile = new File(path + "\\镇江本部配网工程竣工甲供材核对表.xls");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("镇江本部配网工程竣工甲供材核对表.xls", docFile, response);
    }

    //导入明细账信息
    @ResponseBody
    @RequestMapping(value = "importLedger")
    public AjaxJson importLedger(@RequestParam("file") MultipartFile file, SettActivi settActivi, HttpServletRequest request, HttpServletResponse response, Model model) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, 0);
            int lastDataRowNum = importExcel.getLastDataRowNum();
            Row row = null;
            List<SettList> settLists = new ArrayList<>();
            for (int i = 1; i < lastDataRowNum; i++) {
                SettList settList = new SettList();
                row = importExcel.getRow(i);
                //项目定义编码
                Object projectNumber = importExcel.getCellValue(row, 10);
                //项目名称
                Object requireName = importExcel.getCellValue(row, 11);
                //金额
                Object totalPrice = importExcel.getCellValue(row, 15);
                //数量
                Object outgoingQuantity = importExcel.getCellValue(row, 16);
                //编码
                Object materialEncoding = importExcel.getCellValue(row, 18);
                //描述
                Object materialName = importExcel.getCellValue(row, 19);
                //单位
                Object company = importExcel.getCellValue(row, 20);
                settList.setProjectId(projectNumber.toString());
                settList.setMaterialEncoding(materialEncoding.toString());
                settList.setMaterialName(materialName.toString());
                settList.setCompany(company.toString());
                settList.setRequireName(requireName.toString());
                Double oQ = Double.valueOf(outgoingQuantity.toString());
                Double tP = Double.valueOf(totalPrice.toString());
                settList.setOutgoingQuantity(oQ);
                settList.setTotalPrice(tP);
                double v = tP / oQ;
                settList.setUnitPrice(v);
                settLists.add(settList);
            }
            List<SettList> insertList = new ArrayList<>();
            if (null != settLists && settLists.size()>0) {
                for (SettList s :
                        settLists) {
                    if (settActivi.getReserveProjectName().equals(s.getRequireName())) {
                        s.setProcInsId(settActivi.getAct().getProcInsId());
                        insertList.add(s);
                    }
                }
                if (insertList.size() > 0) {
                    settActiviService.insertSettList(insertList);
                }
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入项目原因！失败信息：" + e.getMessage());
        }
        return j;
    }

}


