package com.zcloud.modules.RyCheck.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcloud.common.utils.Const;
import com.zcloud.common.utils.DateUtil;
import com.zcloud.common.utils.Tools;
import com.zcloud.modules.RyCheck.entity.*;
import com.zcloud.modules.RyCheck.entity.rycheck.*;
import com.zcloud.modules.RyCheck.mapper.ImgfilesMapper;
import com.zcloud.modules.RyCheck.mapper.UserMapper;
import com.zcloud.modules.RyCheck.service.*;
import com.zcloud.modules.sys.entity.PageData;
import com.zcloud.util.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class RyCheckServiceImpl implements RyCheckService {

    private static final Logger logger = LoggerFactory.getLogger(RyCheckServiceImpl.class);
    @Resource
    private RyCheckJlService ryCheckJlService;
    @Resource
    private RyCheckJhService ryCheckJhService;
    @Resource
    private RyCheckMbService ryCheckMbService;
    @Resource
    private HiddenService hiddenService;
    @Resource
    private HiddenUserService hiddenUserService;
    @Resource
    private HiddenCheckUserService hiddenCheckUserService;
    @Resource
    private UserMapper userMapper;

    @Resource
    private ImgfilesMapper imgfilesMapper;

    private HashMap<String, PageData> userMap;
    private HashMap<String, String> deptMap;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getRyCheckJlList() {
        ReturnMap httpResponseStr = HttpRequestUtilCheck.doPost("http://192.168.210.123:7016/jt_equipment/jt/getDjResultData");
        httpResponseStr.get("list");
        JSONArray dataList = (JSONArray) httpResponseStr.get("list");
        List<RyCheckJlEntity> ryCheckJlEntities = JSON.parseArray(dataList.toJSONString(), RyCheckJlEntity.class);
        // 处理记录入库
        ryCheckJlService.saveBatch(ryCheckJlEntities);
        // 转成隐患 turnIntoHidden danger
        LinkedList<HiddenEntity> hiddenList = turnIntoHidden(ryCheckJlEntities);

        // 增量数据
        List<String> hiddenids = new ArrayList();
        for (HiddenEntity hidden : hiddenList) {
            hiddenids.add(hidden.getHIDDEN_ID());
        }
        if (!hiddenids.isEmpty()) {
            PageData pageData = new PageData();
            pageData.put("HIDDEN_IDS", hiddenids.toArray(new String[hiddenids.size()]));
            getAllHidden(pageData);
        }
    }

    private LinkedList<HiddenEntity> turnIntoHidden(List<RyCheckJlEntity> ryCheckJlEntities) {
        List<PageData> allUserList = userMapper.getAllUserList(new PageData());
        userMap = new HashMap<>();
        allUserList.forEach(item -> {
            userMap.put(item.getString("USERNAME"), item);
        });
        List<PageData> allDeptList = userMapper.getAllDeptList(new PageData());
        deptMap = new HashMap<>();
        allDeptList.forEach(item -> {
            deptMap.put(item.getString("deptname"), item.getString("DEPARTMENT_ID"));
        });
        //  处理工单转隐患存入系统
        LinkedList<HiddenEntity> hiddenList = new LinkedList<>();
        // 发现人
        LinkedList<HiddenUserEntity> hiddenUserList = new LinkedList<>();
        // 验收人
        LinkedList<HiddenCheckUserEntity> hiddenCheckUserList = new LinkedList<>();
        for (RyCheckJlEntity ryCheckJlEntity : ryCheckJlEntities) {
            if (Tools.notEmpty(ryCheckJlEntity.getFgdno())) {
                // 没有工单 不存隐患
                HiddenEntity hiddenEntity = new HiddenEntity();
                hiddenEntity.setHIDDEN_ID(UuidUtil.get32UUID());
                // 已验收
                hiddenEntity.setSTATE("4");
                hiddenEntity.setISDELETE("0");
                hiddenEntity.setCORPINFO_ID("8854edee3aa94be496cee676b6d4845a");
                // 期限整改
                //  `RECTIFICATIONTYPE 1 立即整改    2   限期整改,
                hiddenEntity.setRECTIFICATIONTYPE("2");
                hiddenEntity.setLONGITUDE(ryCheckJlEntity.getLongitude());
                hiddenEntity.setLATITUDE(ryCheckJlEntity.getLatitude());
                // 实际开始实际 是维修时间，
                ryCheckJlEntity.getFstrdateSj();
                // 实际结束时间是 维修完成时间
                ryCheckJlEntity.getFenddateSj();
                // 整改期限-整改时间
                hiddenEntity.setRECTIFICATIONDEADLINE(ryCheckJlEntity.getFenddateSj());
                hiddenEntity.setRECTIFICATIONTIME(ryCheckJlEntity.getFenddateSj());
                // 隐患级别  默认为一般隐患
                hiddenEntity.setHIDDENLEVEL("hiddenLevel1002");
                // 隐患来源 souce -》 8 点检隐患
                hiddenEntity.setSOURCE("8");

                // 派单模式(0 指派;1 抢单;2 技术员自修),  2 是本公司的人  0，1都是相关方的人。
                if (ryCheckJlEntity.getFpattern() == 2) {
                    hiddenEntity.setISRELEVANT("2");
                    System.out.println("整改人是本公司的");
                } else {
                    System.out.println("整改人是相关方的");
                    hiddenEntity.setISRELEVANT("1");
                    if (!deptMap.containsKey(ryCheckJlEntity.getFwwdwStr())) {
                        // 新部门 一定是相关方的 相关方 为144
                        PageData deptPageData = saveDept("14465464734a4845b6313118408e328e", ryCheckJlEntity.getFwwdwStr());
                        deptMap.put(ryCheckJlEntity.getFwwdwStr(), deptPageData.getString("DEPARTMENT_ID"));
                    }
                }
                // 维修单位，维修人 对应隐患维修人
                ryCheckJlEntity.getFwwdwStr();
                ryCheckJlEntity.getFwxfzr();
                ryCheckJlEntity.getFwxfzrTel();

                PageData RECTIFI_USER = getUserPdByTel(userMap, ryCheckJlEntity, 1);
                System.out.println("整改人-》整改人有可能是本公司的" + "姓名" + ryCheckJlEntity.getFwxfzr() + ",电话:" + ryCheckJlEntity.getFwxfzrTel() + ",部门:" + ryCheckJlEntity.getFwwdwStr() + ",维修工艺:" + ryCheckJlEntity.getFwxgyName());
                hiddenEntity.setRECTIFICATIONOR(RECTIFI_USER.getString("USER_ID"));


                // 签发人
                ryCheckJlEntity.getFqfuserStr();
                ryCheckJlEntity.getFqfuserPhone();
                ryCheckJlEntity.getFqfuserDeptStr();
                if (!deptMap.containsKey(ryCheckJlEntity.getFqfuserDeptStr())) {
                    // 新部门 一定是本单位的
                    PageData deptPageData = saveDept("8854edee3aa94be496cee676b6d4845a", ryCheckJlEntity.getFqfuserDeptStr());
                    deptMap.put(ryCheckJlEntity.getFqfuserDeptStr(), deptPageData.getString("DEPARTMENT_ID"));
                }
                // todo
                System.out.println("发现人-》发现人是本公司的" + "姓名" + ryCheckJlEntity.getFqfuserStr() + ",电话:" + ryCheckJlEntity.getFqfuserPhone() + ",部门:" + ryCheckJlEntity.getFqfuserDeptStr());
                PageData CREATOR_USER = getUserPdByTel(userMap, ryCheckJlEntity, 2);
                hiddenEntity.setCREATOR(CREATOR_USER.getString("USER_ID"));
//                hiddenEntity.setCREATOR("5c61afed41bc4c25acf77aed1391e666");
                // 签发时间-》 对应隐患发现时间
                hiddenEntity.setCREATTIME(ryCheckJlEntity.getFqfdate());
                // 隐患确认人
                hiddenEntity.setCONFIRM_USER(CREATOR_USER.getString("USER_ID"));
                hiddenEntity.setCONFIRM_TIME(ryCheckJlEntity.getFqfdate());
                hiddenEntity.setDISCOVERYTIME(ryCheckJlEntity.getFqfdate());

                // 隐患类型 1 保养类;2 故障停机类;3 环保设施类)
                if (ryCheckJlEntity.getFworkordertype() != null && ryCheckJlEntity.getFworkordertype() == 3) {
                    hiddenEntity.setHIDDENTYPE2("卫生环保");
                    hiddenEntity.setHIDDENTYPE("wshb-qt");
                } else {
                    hiddenEntity.setHIDDENTYPE2("安全隐患");
                    hiddenEntity.setHIDDENTYPE("aqyh-qt");
                }


                // 问题描述对应 -》隐患描述
                ryCheckJlEntity.getZxNote();
                hiddenEntity.setHIDDENDESCR(ryCheckJlEntity.getZxNote());
                // 维修工艺附件（整改方案） 和 点检评价（隐患图片） 附件
                // 整改描述
                ryCheckJlEntity.getFwxgyName();
                hiddenEntity.setRECTIFYDESCR(ryCheckJlEntity.getFwxgyName());
                // 维修工艺附件
                ryCheckJlEntity.getFwxgyFilepath();

                // 验收人 对应验收人
                ryCheckJlEntity.getYs_user();
                // 默认合格
                hiddenEntity.setISQUALIFIED("1");
                // 验收描述
                hiddenEntity.setCHECKDESCR(ryCheckJlEntity.getFys_note());
                // 验收人
//                hiddenEntity.setCHECKOR(ryCheckJlEntity.getYs_user());
                if (!deptMap.containsKey(ryCheckJlEntity.getFysDept())) {
                    // 新部门 一定是本单位的
                    PageData deptPageData = saveDept("8854edee3aa94be496cee676b6d4845a", ryCheckJlEntity.getFysDept());
                    deptMap.put(ryCheckJlEntity.getFqfuserDeptStr(), deptPageData.getString("DEPARTMENT_ID"));
                }

                PageData CHECKOR_USER = getUserPdByTel(userMap, ryCheckJlEntity, 3);
                hiddenEntity.setCHECKOR(CHECKOR_USER.getString("USER_ID"));
                System.out.println("验收人-》验收人是本公司的" + "姓名" + ryCheckJlEntity.getYs_user() + ",电话:" + ryCheckJlEntity.getFysPhone() + ",部门:" + ryCheckJlEntity.getFysDept());
                // 验收时间
                hiddenEntity.setCHECKTIME(ryCheckJlEntity.getFys_date());
                hiddenList.add(hiddenEntity);
                // 如果有隐患照片的话 保存起来
                if (ryCheckJlEntity.getFileList() != null) {
                    for (HashMap map : ryCheckJlEntity.getFileList()) {
                        // 获取文件路径
                        String ffilepath = (String) map.get("ffilepath");
                        // filename -> temp.jpg
                        InputStream netUrlHttps = HttpsFileDownload.getNetUrlHttpsStream(ffilepath, "");
                        String ffile = DateUtil.getDays();
                        String fileName = UuidUtil.get32UUID() + (String) map.get("filename");
                        String filePath = Const.FILEPATHYHTP + "8854edee3aa94be496cee676b6d4845a" + "/" + ffile + "/";
                        // 获取流文件 上传到 附件服务器
//                        InputStream fileI = Smb.sshSftpForInput(new FileInputStream(ffilepath), ffilepath, "");
                        // bus_imgfiles -> FOREIGN_KEY  -> hiddenId ||| TYPE ->3
                        try {
                            Smb.sshSftpForInput(netUrlHttps, fileName, filePath);
                            ImgFilesEntity imgFilesEntity = new ImgFilesEntity();
                            imgFilesEntity.setIMGFILES_ID(UuidUtil.get32UUID());
                            imgFilesEntity.setFILEPATH(filePath + fileName);
                            imgFilesEntity.setFOREIGN_KEY(hiddenEntity.getHIDDEN_ID());
                            imgFilesEntity.setTYPE("3");
                            imgfilesMapper.insert(imgFilesEntity);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                hiddenUserList.add(new HiddenUserEntity(UuidUtil.get32UUID(), hiddenEntity.getHIDDEN_ID(), hiddenEntity.getCREATOR(), "1", "0"));
                hiddenCheckUserList.add(new HiddenCheckUserEntity(UuidUtil.get32UUID(), hiddenEntity.getHIDDEN_ID(), deptMap.get(ryCheckJlEntity.getFysDept()), userMap.get(ryCheckJlEntity.getFysPhone()).getString("USER_ID"), "0", ryCheckJlEntity.getFys_date(), ryCheckJlEntity.getFys_note()));
            }
        }
        if (!hiddenList.isEmpty()) {
            hiddenService.saveBatch(hiddenList);
            hiddenUserService.saveBatch(hiddenUserList);
            hiddenCheckUserService.saveBatch(hiddenCheckUserList);
            // bus_hidden_user  隐患发现人存入这里
            //BUS_HIDDENCHECK 隐患验收人存入这里
        }
        return hiddenList;
    }

    private PageData saveDept(String PARENT_ID, String fwwdwStr) {
        PageData deptPageData = new PageData();
        deptPageData.put("DEPARTMENT_ID", UuidUtil.get32UUID());
        deptPageData.put("NAME", fwwdwStr);
        deptPageData.put("PARENT_ID", PARENT_ID);
        deptPageData.put("CORPINFO_ID", "8854edee3aa94be496cee676b6d4845a");
        deptPageData.put("LEVEL", "departmentLevel0003");
        deptPageData.put("DEP_ORDER", "1");
        deptPageData.put("ISSUPERVISE", "0");
        userMapper.addDept(deptPageData);
        return deptPageData;
    }

    private PageData getUserPdByTel(HashMap<String, PageData> userMap, RyCheckJlEntity ryCheckJlEntity, int type) {
        PageData pageData = null;
        // 整改人
        if (type == 1) {
            pageData = userMap.get(ryCheckJlEntity.getFwxfzrTel());
        }
        // 发现人
        if (type == 2) {
            pageData = userMap.get(ryCheckJlEntity.getFqfuserPhone());
        }
        // 验收人
        if (type == 3) {
            pageData = userMap.get(ryCheckJlEntity.getFysPhone());
        }
        if (pageData == null) {
            // 本系统不存在这个人。 新增 这个人、部门。然后同步给秦港。
            PageData userPd = saveUser(ryCheckJlEntity, type);
            if (type == 1) {
                userMap.put(ryCheckJlEntity.getFwxfzrTel(), userPd);
            }
            if (type == 2) {
                userMap.put(ryCheckJlEntity.getFqfuserPhone(), userPd);
            }
            if (type == 3) {
                userMap.put(ryCheckJlEntity.getFysPhone(), userPd);
            }
            return userPd;
        }
        return pageData;
    }

    private PageData saveUser(RyCheckJlEntity ryCheckJlEntity, int type) {
        // 整改人 （大概率相关方）
        PageData pageData = new PageData();
        String password = "";
        pageData.put("USER_ID", UuidUtil.get32UUID());
        pageData.put("IS_HAZARDCONFIRMER", "1");

        // 整改
        if (type == 1) {
            pageData.put("USERNAME", ryCheckJlEntity.getFwxfzrTel());
            pageData.put("NAME", ryCheckJlEntity.getFwxfzr());
            pageData.put("IS_HAZARDCONFIRMER", "0");
            pageData.put("DEPARTMENT_ID", deptMap.get(ryCheckJlEntity.getFwwdwStr()));
            password = new SimpleHash("SHA-1", ryCheckJlEntity.getFwxfzrTel(), "Aa@602209238").toString();
        }
        // 发现人
        if (type == 2) {
            pageData.put("USERNAME", ryCheckJlEntity.getFqfuserPhone());
            pageData.put("NAME", ryCheckJlEntity.getFqfuserStr());
            pageData.put("DEPARTMENT_ID", deptMap.get(ryCheckJlEntity.getFqfuserDeptStr()));
            password = new SimpleHash("SHA-1", ryCheckJlEntity.getFqfuserPhone(), "Aa@602209238").toString();

        }
        // 验收
        if (type == 3) {
            pageData.put("USERNAME", ryCheckJlEntity.getFysPhone());
            pageData.put("NAME", ryCheckJlEntity.getYs_user());
            pageData.put("DEPARTMENT_ID", deptMap.get(ryCheckJlEntity.getFysDept()));
            password = new SimpleHash("SHA-1", ryCheckJlEntity.getFysPhone(), "Aa@602209238").toString();
        }
        pageData.put("ROLE_ID", "96036bcce5cf418baf8bc2f91271c8c6");
        pageData.put("PASSWORD", password);
        pageData.put("STATUS", "0");
        pageData.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");
        pageData.put("CORPINFO_ID", "8854edee3aa94be496cee676b6d4845a");
        pageData.put("ISMAIN", "0");
        pageData.put("ISDELETE", "0");
        pageData.put("PERSON_TYPE", "其他");
        userMapper.saveUser(pageData);
        System.out.println("新增用户" + pageData.toString());
        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getRyCheckJhList() {
        ReturnMap httpResponseStr = HttpRequestUtilCheck.doPost("http://192.168.210.123:7016/jt_equipment/jt/getDjjhData");
        httpResponseStr.get("list");
        JSONArray dataList = (JSONArray) httpResponseStr.get("list");
        List<RyCheckJhEntity> ryCheckJlEntities = JSON.parseArray(dataList.toJSONString(), RyCheckJhEntity.class);
        ryCheckJhService.saveBatch(ryCheckJlEntities);
    }

    @Override
    public void getRyCheckRyMbList() {
        ryCheckMbService.remove(new QueryWrapper<>());
        ReturnMap httpResponseStr = HttpRequestUtilCheck.doPost("http://192.168.210.123:7016/jt_equipment/jt/getModelPlanData");
        httpResponseStr.get("list");
        JSONArray dataList = (JSONArray) httpResponseStr.get("list");
        List<RyCheckMbEntity> ryCheckJlEntities = JSON.parseArray(dataList.toJSONString(), RyCheckMbEntity.class);
        ryCheckMbService.saveBatch(ryCheckJlEntities);
    }

    @Override
    public void pushedHiddenList() {
        QueryWrapper<HiddenEntity> hiddenEntityQueryWrapper = new QueryWrapper<>();
        hiddenEntityQueryWrapper.eq("SOURCE", "8");
        hiddenEntityQueryWrapper.eq("ISDELETE", "0");
        hiddenEntityQueryWrapper.notIn("HIDDEN_ID", new ArrayList<>());
//        hiddenService.listAnd
        List<HiddenEntity> list = hiddenService.list(hiddenEntityQueryWrapper);
        // 推送数据到港股。
        // hiddenInfoList
        // userInfoList


    }

    @Override
    public void getAllUser() {
        List<PageData> allUserList = userMapper.getAllUsers(new PageData());

    }

    @Override
    public void getAllDept() {
        List<PageData> allDeptList = userMapper.getAllDepts(new PageData());

    }

    @Override
    public void getAllHidden(PageData pd) {
        List<PageData> hiddenList = hiddenService.getAllUserList(pd);
        String fileUrl = Const.FILE_URL;
        for (PageData pageData : hiddenList) {
            PageData imgPd = new PageData();
            imgPd.put("FOREIGN_KEY",pageData.getString("HIDDEN_ID"));
            imgPd.put("fileUrl",fileUrl);
            List<PageData> imgList= imgfilesMapper.getAllImgList(imgPd);
            pageData.put("FileList",imgList);
        }
    }



    public static void main(String[] args) throws Exception {
//        InputStream 转
        // ffilepath -> http://192.168.210.76/uploads//1729600183218.jpg
        InputStream netUrlHttps = HttpsFileDownload.getNetUrlHttpsStream("http://192.168.210.76/uploads//1729600183218.jpg", "");
        //
        System.out.println(netUrlHttps);

        Smb.sshSftpForInput(netUrlHttps, "", "");
    }
}
