package com.jeeplus.modules.sg.managementcenter.reserveManagement.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
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.entity.Act;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformation;
import com.jeeplus.modules.sg.audit.material.entity.Material;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.UploadImages;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.ReserveProcess;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.service.ReserveProcessService;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 物料规范 Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/reserveProcess")
public class ReserveProcessController extends BaseController {

    @Autowired
    private ReserveProcessService reserveProcessService;

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

    /**
     * 物料规范信息列表页面
     * @param reserveProcess
     * @param model
     * @return
     */
    @RequestMapping(value = "list")
    public String list(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/reserveProcessList";
    }

    /**
     * 设计单位审核
     * */
    @RequestMapping(value = "designUnit")
    public String designUnit(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/designUnit";
    }

    /**
     * 项目经理审图
     * */
    @RequestMapping(value = "drawingReview")
    public String drawingReview(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/drawingReview";
    }

    /**
     * 技经人员审概算
     * */
    @RequestMapping(value = "economicPersonnel")
    public String economicPersonnel(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/economicPersonnel";
    }

    /**
     * 运行单位审图
     * */
    @RequestMapping(value = "operationUnit")
    public String operationUnit(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/operationUnit";
    }

    /**
     * 储备文件管理页面
     * */
    @RequestMapping(value = "allUpload")
    public String allUpload(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/allUploadList";
    }

    /**
     * 甲供材 列表数据
     */
    @ResponseBody
    @RequestMapping(value = "materialData")
    public Map<String, Object> data(MaterialInfo materialInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<MaterialInfo> page = reserveProcessService.findMaterialPage(new Page<MaterialInfo>(request, response), materialInfo);
        return getBootstrapData(page);
    }

    /**
     * 物料规范信息数据列表
     * @param reserveProcess
     * @param request
     * @param response
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "data")
    public Map<String, Object> basicData(ReserveProcess reserveProcess, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ReserveProcess> page = reserveProcessService.findPage(new Page<ReserveProcess>(request, response), reserveProcess);
        return getBootstrapData(page);
    }


    /**
     * 储备流程，文件显示管理
     * */
    @ResponseBody
    @RequestMapping(value = "uploadData")
    public Map<String, Object> uploadData(ReserveProcess reserveProcess, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ReserveProcess> page = reserveProcessService.findUploadPage(new Page<ReserveProcess>(request, response), reserveProcess);
        //当判定系统为linux的时候
        if (Global.SYS_TYPE.equals("2")) {
            List<ReserveProcess> list = page.getList();
            for (ReserveProcess upload:
                    list) {
                String a = "";
                String b = "";
                String c = "";
                String d = "";
                String path = upload.getBudgetStatement();
                String[] split = path.split("\\|");
                for (int i = 0; i < split.length; i++) {
                    a += "http://" + request.getServerName() + split[i] + "|";
                }
                upload.setBudgetStatement(a);

                String projectProposal = upload.getProjectProposal();
                String[] split1 = projectProposal.split("\\|");
                for (int i = 0; i < split1.length; i++) {
                    b += "http://" + request.getServerName() + split1[i] + "|";
                }
                upload.setProjectProposal(b);

                String drawings = upload.getDrawings();
                String[] split2 = drawings.split("\\|");
                for (int i = 0; i < split2.length; i++) {
                    c += "http://" + request.getServerName() + split2[i] + "|";
                }
                upload.setDrawings(c);

                String drawingSpecification = upload.getDrawingSpecification();
                String[] split3 = drawingSpecification.split("\\|");
                for (int i = 0; i < split3.length; i++) {
                    d += "http://" + request.getServerName() + split3[i] + "|";
                }
                upload.setDrawingSpecification(d);

            }
        }
        return getBootstrapData(page);
    }

    /**
     * 储备流程，文件显示管理
     * */
    @ResponseBody
    @RequestMapping(value = "allUploadData")
    public Map<String, Object> allUploadData(ReserveProcess reserveProcess, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ReserveProcess> page = reserveProcessService.findAllUploadPage(new Page<ReserveProcess>(request, response), reserveProcess);
        //当判定系统为linux的时候
        if (Global.SYS_TYPE.equals("2")) {
            List<ReserveProcess> list = page.getList();
            for (ReserveProcess upload:
                    list) {
                String a = "";
                String b = "";
                String c = "";
                String d = "";
                String path = upload.getBudgetStatement();
                if (null != path && !"".equals(path)) {
                    String[] split = path.split("\\|");
                    for (int i = 0; i < split.length; i++) {
                        a += "http://" + request.getServerName() + split[i] + "|";
                    }
                    upload.setBudgetStatement(a);
                }

                String projectProposal = upload.getProjectProposal();
                if (null != projectProposal && !"".equals(projectProposal)) {
                    String[] split1 = projectProposal.split("\\|");
                    for (int i = 0; i < split1.length; i++) {
                        b += "http://" + request.getServerName() + split1[i] + "|";
                    }
                    upload.setProjectProposal(b);
                }

                String drawings = upload.getDrawings();
                if (null != drawings && !"".equals(drawings)) {
                    String[] split2 = drawings.split("\\|");
                    for (int i = 0; i < split2.length; i++) {
                        c += "http://" + request.getServerName() + split2[i] + "|";
                    }
                    upload.setDrawings(c);
                }

                String drawingSpecification = upload.getDrawingSpecification();
                if (null != drawingSpecification && !"".equals(drawingSpecification)) {
                    String[] split3 = drawingSpecification.split("\\|");
                    for (int i = 0; i < split3.length; i++) {
                        d += "http://" + request.getServerName() + split3[i] + "|";
                    }
                    upload.setDrawingSpecification(d);
                }
            }
        }
        return getBootstrapData(page);
    }

    /**
     * 专职人员增加，编辑表单页面
     * @param reserveProcess
     * @param model
     * @return
     */
    @RequiresPermissions(value={"sg:reserve:reserveProcess:add","sg:reserve:reserveProcess:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(ReserveProcess reserveProcess, Model model) {
        model.addAttribute("reserveProcess", reserveProcess);
        return "modules/sg/managementcenter/reserveManagement/reserveProcessForm";
    }

    /**
     * 保存表单
     * @param reserveProcess
     * @return
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:reserveProcess:add","sg:reserve:reserveProcess:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(ReserveProcess reserveProcess){
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(reserveProcess);
        if (StringUtils.isNotBlank(errMsg)){
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        //通过储备项目编号
        reserveProcessService.save(reserveProcess);//保存
        j.setSuccess(true);
        j.setMsg("保存物料规范信息成功");
        return j;
    }


    /**
     *
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:reserveProcess:del"},logical=Logical.OR)
    @RequestMapping(value = "deleteAll")
    public AjaxJson delete(String ids){
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        for(String id : idArray){
            reserveProcessService.delete(reserveProcessService.get(id));
        }
        j.setMsg("删除物料规范信息成功");
        return j;
    }

   

    /**
     * 经理导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:reserveProcess:import")
    @RequestMapping(value = "import")
    public AjaxJson jlImportBasic(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            StringBuffer stringBuffer = new StringBuffer();
            List<ReserveProcess> list = ei.getDataList(ReserveProcess.class);
            List<ReserveProcess> insertList = new ArrayList<>();
            j.setSuccess(true);
            j.setMsg("已成功导入" + stringBuffer);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入物料规范信息失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    //导出甲供材清册
    @ResponseBody
    @RequiresPermissions("sg:reserve:reserveProcess:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(String ids,ReserveProcess reserveProcess, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String idArray[] =ids.split(",");
            List<String> exportList = new ArrayList<>();
            String fileName = "甲供材清册"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            //通过id查找到需要导出数据的甲供材清册项目名称
            if (!"".equals(idArray) && idArray.length > 0) {
                exportList = reserveProcessService.findByIds(idArray);
            } else {
                exportList = reserveProcessService.findAllName();
            }
            List<MaterialInfo> list = reserveProcessService.findMaterialExport(exportList);
            new ExportExcel("甲供材清册", MaterialInfo.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;
    }


    @ResponseBody
    @RequestMapping(value = "exportAct")
    public AjaxJson exportAct(String projectName,ReserveProcess reserveProcess, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "甲供材清册"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<MaterialInfo> list = reserveProcessService.findMaterialActiviti(projectName);
            new ExportExcel("甲供材清册", MaterialInfo.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;
    }


    /**
     * 下载导入模板
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:reserveProcess:import")
    @RequestMapping(value = "template")
    public AjaxJson importTemplate(HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "物料规范信息详细导入模板.xlsx";
            List<BasicInformation> list = Lists.newArrayList();
            new ExportExcel("物料规范详细信息表", ReserveProcess.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
        }
        return j;
    }

    /***
     * 设计单位审核
     * */
    @ResponseBody
    @RequestMapping(value = "actDesignUnit")
    public AjaxJson actDesignUnit(Act act, ReserveProcess reserveProcess) {
        AjaxJson j = new AjaxJson();
        String flag = act.getFlag();
        try {
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            if ("yes".equals(flag)) {
                //通过流程流程定义号查询项目编码，查询是否存在甲供材信息
                Integer materialData = reserveProcessService.findMaterialData(act.getProcInsId());
                if (materialData <= 0) {
                    j.setMsg("该项目没有甲供材清册");
                    j.setSuccess(false);
                    return j;
                } else {
                    //修改项目设计单位上传文件部分
                    reserveProcessService.updateDesign(reserveProcess);
                    reserveProcessService.actDesignUnit(act,reserveProcess);
               }
            } else {
                reserveProcessService.actDesignUnit(act,reserveProcess);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }


    /***
     * 设计单位审核
     * */
    @ResponseBody
    @RequestMapping(value = "actDrawingReview")
    public AjaxJson actDrawingReview(Act act) {
        AjaxJson j = new AjaxJson();
        try {
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            reserveProcessService.actDrawingReview(act);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }

    /***
     * 技经人员审概算
     * */
    @ResponseBody
    @RequestMapping(value = "actEconomicPersonnel")
    public AjaxJson actEconomicPersonnel(Act act,ReserveProcess reserveProcess) {
        AjaxJson j = new AjaxJson();
        try {
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            String flag = act.getFlag();
            //修改流程对应金额数据
            if ("yes".equals(flag)) {
                reserveProcessService.updateAmount(reserveProcess);
            }
            reserveProcessService.actEconomicPersonnel(act);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }

    /***
     * 运行单位审图（联合审图）
     * */
    @ResponseBody
    @RequestMapping(value = "actOperationUnit")
    public AjaxJson actOperationUnit(Act act) {
        AjaxJson j = new AjaxJson();
        try {
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            reserveProcessService.actOperationUnit(act);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }


    /**
     * 年度物资上报明细 多文件导入验证
     */
    @ResponseBody
    @RequestMapping(value = "importValidations")
    public AjaxJson importValidations(@RequestParam("file")MultipartFile[] file) {
        AjaxJson j = new AjaxJson();
        List<MaterialProject> list = new ArrayList<>();
        try {
            for(int k=0;k<file.length;k++) {
                reserveProcessService.saveData(file[k]);
            }
            j.setSuccess(true);
            j.setErrorCode("0");
            j.setMsg("导入成功");
        } catch (Exception e) {
            j.setSuccess(true);
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }

    /**
     * 储备项目附件打包下载
     */
    @RequestMapping(value = "exportFiles")
    public String exportFiles(String ids,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        List<String> idList = new ArrayList<>();
        String idArray[] =ids.split(",");
        if (!"".equals(ids) && idArray.length > 0) {
            idList = reserveProcessService.findIds(idArray);
        } else {
            idList = reserveProcessService.findAllId();
        }
        try {
            String filePath = reserveProcessService.exportFiles(idList);
            downloadZipFile(filePath,response);
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "批量下载项目文件失败！");
        }
        return "redirect:"+Global.getAdminPath()+"/sg/reserveProcess/allUpload";
    }


    /**
     * 下载压缩文件
     *
     * @param filePath
     * @param response
     */
    public void downloadZipFile(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        //取得文件名。
        String fileName = file.getName();
        InputStream in = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            in = new FileInputStream(file);
            response.reset();//重置 响应头
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);

            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            in.close();
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //路径是个文件且不为空时删除文件
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }
    }



}
