package com.zcloud.controller.eightwork;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.eightwork.LimitSpaceService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 说明：有限空间台账
 * 作者：luoxiaobao
 * 时间：2021-04-02
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/limitspace")
public class LimitSpaceController extends BaseController {

    @Autowired
    private LimitSpaceService limitspaceService;
    @Autowired
    private DictionariesService dictionariesService;
    @Autowired
    private UsersService usersService;

    @Resource
    private InitPageDataUtil initPageDataUtil;


    @Resource
    private Smb smb;

    /**
     * 新增
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/add")
//	@RequiresPermissions("limitspace:add")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "新增")
    public Object add(@RequestParam(value = "HASINSTRUCTOR_PATH2", required = false) MultipartFile hasinstructorPath, @RequestParam(value = "WARNINGSIGNS_PATH2", required = false) MultipartFile warningsignsPath) throws Exception {

        PageData pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        initPageDataUtil.initSave(pd, "LIMITSPACE_ID");
        if (hasinstructorPath != null && !hasinstructorPath.isEmpty()) {
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + hasinstructorPath.getOriginalFilename().substring(hasinstructorPath.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(hasinstructorPath, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("HASINSTRUCTOR_PATH", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
            pd.put("HASINSTRUCTOR_NAME", fileName);
        }
        if (warningsignsPath != null && !warningsignsPath.isEmpty()) {
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + warningsignsPath.getOriginalFilename().substring(warningsignsPath.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(warningsignsPath, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("WARNINGSIGNS_PATH", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
            pd.put("WARNINGSIGNS_NAME", fileName);
        }
        limitspaceService.save(pd);

        return ReturnMap.ok();
    }

    /**
     * 删除
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
//	@RequiresPermissions("limitspace:del")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "删除")
    public Object delete() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUsername());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        limitspaceService.delete(pd);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 修改
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
//	@RequiresPermissions("limitspace:edit")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "修改")
    public Object edit(@RequestParam(value = "HASINSTRUCTOR_PATH2", required = false) MultipartFile hasinstructorPath, @RequestParam(value = "WARNINGSIGNS_PATH2", required = false) MultipartFile warningsignsPath) throws Exception {
        PageData pd = this.getPageData();
        initPageDataUtil.initEdit(pd);
        if (hasinstructorPath != null && !hasinstructorPath.isEmpty()) {
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + hasinstructorPath.getOriginalFilename().substring(hasinstructorPath.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(hasinstructorPath, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("HASINSTRUCTOR_PATH", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
            pd.put("HASINSTRUCTOR", fileName);
        }
        if (warningsignsPath != null && !warningsignsPath.isEmpty()) {
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + warningsignsPath.getOriginalFilename().substring(warningsignsPath.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(warningsignsPath, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("WARNINGSIGNS_PATH", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
            pd.put("WARNINGSIGNS", fileName);
        }
        limitspaceService.edit(pd);
        return ReturnMap.ok();
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "列表")
    public Object list(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        pd.put("ISMAIN", Jurisdiction.getIS_MAIN());
        pd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
        pd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
        String DEPTIDS = pd.getString("DEPTIDS");
        if (Tools.notEmpty(DEPTIDS)) {
            String DEPT_IDS[] = DEPTIDS.split(",");
            pd.put("DEPT_IDS", DEPT_IDS);
        }
        page.setPd(pd);
        List<PageData> varList = limitspaceService.list(page);    //列出LimitSpace列表
        map.put("varList", varList);
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改页面获取数据
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/goEdit")
    @RequiresPermissions("limitspace:edit")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "去修改页面获取数据")
    public Object goEdit() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd = limitspaceService.findById(pd);    //根据ID读取
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 批量删除
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/deleteAll")
//    @RequiresPermissions("limitspace:del")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "批量删除")
    public Object deleteAll() throws Exception {
        PageData pd = this.getPageData();
        String DATA_IDS = pd.getString("DATA_IDS");
        if (Tools.notEmpty(DATA_IDS)) {
            String ArrayDATA_IDS[] = DATA_IDS.split(",");
            pd.put("ArrayDATA_IDS", ArrayDATA_IDS);
            pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
            pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
            limitspaceService.deleteAll(pd);
        }
        return ReturnMap.ok();
    }


    /**
     * 导出到excel
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
    @RequiresPermissions("toExcel")
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "导出到excel")
    public ModelAndView exportExcel() throws Exception {
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("编号");    //1
        titles.add("有限空间名称");    //2
        titles.add("有限空间类型");    //3
        titles.add("位置及范围");    //4
        titles.add("主要危险及有害因素");    //5
        titles.add("风险等级");    //6
        titles.add("本有限空间最多作业人数");    //7
        titles.add("是否有应急指导书  0无 1有");    //8
        titles.add("备注");    //9
        titles.add("填报人");    //10
        titles.add("主要负责人");    //11
        titles.add("填报时间");    //12
        titles.add("企业ID");    //13
        titles.add("添加人");    //14
        titles.add("添加时间");    //15
        titles.add("修改人");    //16
        titles.add("修改时间");    //17
        titles.add("是否删除 1-是  0-否");    //18
        dataMap.put("titles", titles);
        List<PageData> varOList = limitspaceService.listAll(pd);
        List<PageData> varList = new ArrayList<PageData>();
        for (int i = 0; i < varOList.size(); i++) {
            PageData vpd = new PageData();
            vpd.put("var1", varOList.get(i).getString("NUMBER"));        //1
            vpd.put("var2", varOList.get(i).getString("NAME"));        //2
            vpd.put("var3", varOList.get(i).getString("LIMITSPACETYPE"));        //3
            vpd.put("var4", varOList.get(i).getString("POSITIONSCOPE"));        //4
            vpd.put("var5", varOList.get(i).getString("PRIMARYHAZARD"));        //5
            vpd.put("var6", varOList.get(i).getString("RISKGRADE"));        //6
            vpd.put("var7", varOList.get(i).getString("MAXPERSON"));        //7
            vpd.put("var8", varOList.get(i).getString("HASINSTRUCTOR"));        //8
            vpd.put("var9", varOList.get(i).getString("DESCR"));        //9
            vpd.put("var10", varOList.get(i).getString("INFORMANT"));        //10
            vpd.put("var11", varOList.get(i).getString("PRINCIPAL"));        //11
            vpd.put("var12", varOList.get(i).getString("COMPILETIME"));        //12
            vpd.put("var13", varOList.get(i).getString("CORPINFO_ID"));        //13
            vpd.put("var14", varOList.get(i).getString("CREATOR"));        //14
            vpd.put("var15", varOList.get(i).getString("CREATTIME"));        //15
            vpd.put("var16", varOList.get(i).getString("OPERATOR"));        //16
            vpd.put("var17", varOList.get(i).getString("OPERATTIME"));        //17
            vpd.put("var18", varOList.get(i).getString("ISDELETE"));        //18
            varList.add(vpd);
        }
        dataMap.put("varList", varList);
        ObjectExcelView erv = new ObjectExcelView();
        mv = new ModelAndView(erv, dataMap);
        return mv;
    }

    /**
     * 导出到excel
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/excelModel")
    @RequiresPermissions("toExcel")
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "导出模板")
    public void exportExcelModel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "limitSpace.xls", "有限空间导入模板.xls");
    }

    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel2")
    @SuppressWarnings("unchecked")
    @ResponseBody
    @Transactional
    public Object readExcel(@RequestParam(value = "FFILE", required = false) MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<>();
        String errInfo = "success";
        StringBuffer errorStr = new StringBuffer();

        if (file != null && !file.isEmpty()) {
            File tempFile = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

            List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 1, 0, 0); // 读 EXCEL 操作
            PageData pd = new PageData();
            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
            List<PageData> userList = usersService.listAllUser(pd);

            Map<String, String> phoneToUserIdMap = new HashMap<>();
            for (PageData user : userList) {
                phoneToUserIdMap.put(user.getString("USERNAME"), user.getString("USER_ID"));
            }

            List<PageData> saveList = new ArrayList<>();
            if (!listPd.isEmpty()) {
                int succeeNum = 1;
                for (PageData lpd : listPd) {
                    succeeNum++;
                    boolean hasError = false;
                    for (int i = 0; i < 12; i++) {
                        if (Tools.isEmpty(lpd.getString("var" + i))) {
                            errorStr.append("第").append(succeeNum).append("行的第").append(i + 1).append("列无数据");
                            hasError = true;
                        }
                        if (i == 10) {
                            String s = phoneToUserIdMap.get(lpd.getString("var10"));
                            if (Tools.isEmpty(s)) {
                                errorStr.append("第").append(succeeNum).append("行的第").append(i + 1).append("列未找到相关人员");
                                hasError = true;
                            }
                        }
                        if (i == 11) {
                            String s = phoneToUserIdMap.get(lpd.getString("var11"));
                            if (Tools.isEmpty(s)) {
                                errorStr.append("第").append(succeeNum).append("行的第").append(i + 1).append("列未找到相关人员");
                                hasError = true;
                            }
                        }
                        if (i == 8) {
                            if (Tools.isEmpty(lpd.getString("var" + i))) continue;
                            String temp = lpd.getString("var" + i);
                            if (!("A".equals(temp) || "B".equals(temp) || "C".equals(temp) || "D".equals(temp))) {
                                errorStr.append("第").append(succeeNum).append("行的第").append(i + 1).append("列数据请填写‘A,B,C,D'中一项");
                                hasError = true;
                            } else {
                                lpd.put("var" + i, "riskGrade0004");
                                if ("A".equals(temp)) {
                                    lpd.put("var" + i, "riskGrade0001");
                                }
                                if ("B".equals(temp)) {
                                    lpd.put("var" + i, "riskGrade0002");
                                }
                                if ("C".equals(temp)) {
                                    lpd.put("var" + i, "riskGrade0003");
                                }
                            }
                        }
                    }
                    if (hasError) {
                        errInfo = "error";
                        map.put("result", errInfo);
                        map.put("resultStr", errorStr.toString());
                        FileUtils.deleteQuietly(tempFile);
                        return map;
                    }
                    PageData limitspace = new PageData();
                    // 编号
                    limitspace.put("NUMBER", lpd.get("var0"));
                    // 有限空间名称
                    limitspace.put("NAME", lpd.get("var1"));
                    // 有限空间类型
                    limitspace.put("LIMITSPACETYPE", lpd.get("var2"));
                    // 位置及范围
                    limitspace.put("POSITIONSCOPE", lpd.get("var3"));
                    // 设备名称
                    limitspace.put("DEVICENAME", lpd.get("var4"));
                    // 主要事故类型
                    limitspace.put("ACCIDENTTYPE", lpd.get("var5"));
                    // 作业频次
                    limitspace.put("FREQUENCYNUM", lpd.get("var6"));
                    // 主要危险及有害因素
                    limitspace.put("PRIMARYHAZARD", lpd.get("var7"));
                    // 风险等级
                    limitspace.put("RISKGRADE", lpd.get("var8"));
                    // 本有限空间最多作业人数
                    limitspace.put("MAXPERSON", lpd.get("var9"));
                    // 	填报人
                    limitspace.put("INFORMANT", phoneToUserIdMap.get(lpd.getString("var10")));
                    // 主要负责人
                    limitspace.put("PRINCIPAL", phoneToUserIdMap.get(lpd.getString("var11")));

                    limitspace.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    limitspace.put("LIMITSPACE_ID", get32UUID());
                    limitspace.put("CREATOR", Jurisdiction.getUsername());
                    limitspace.put("CREATTIME", DateUtil.date2Str(new Date()));
                    limitspace.put("OPERATOR", Jurisdiction.getUsername());
                    limitspace.put("OPERATTIME", DateUtil.date2Str(new Date()));
                    limitspace.put("COMPILETIME", DateUtil.date1Str(new Date()));
                    limitspace.put("ISDELETE", "0");
                    saveList.add(limitspace);
                }

                for (PageData pageData : saveList) {
                    limitspaceService.save(pageData);
                }

                FileUtils.deleteQuietly(tempFile);
            } else {
                map.put("result", "error");
                return map;
            }
        }

        map.put("result", errInfo);
        map.put("resultStr", errorStr.toString()); // 返回错误信息
        return map;
    }

}
