package com.rongwei.sfcommon.sys.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwe.scentity.domian.AspEvaluationRecordDo;
import com.rongwe.scentity.domian.AspEvaluationRecordHistoryDo;
import com.rongwe.scentity.domian.AspRiskSourceDo;
import com.rongwe.scentity.domian.AspRiskSourceHistoryDo;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwadmincommon.system.service.SysOrganizationService;
import com.rongwei.rwadmincommon.system.service.SysUserService;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.sfcommon.sys.dao.AspRiskSourceDao;
import com.rongwei.sfcommon.sys.service.AspEvaluationRecordService;
import com.rongwei.sfcommon.sys.service.AspRiskSourceService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AspRiskSourceServiceImpl extends ServiceImpl<AspRiskSourceDao, AspRiskSourceDo> implements AspRiskSourceService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private AspEvaluationRecordService aspEvaluationRecordService;

    @Autowired
    private AspRiskSourceHistoryServiceImpl aspRiskSourceHistoryService;
    @Autowired
    private AspEvaluationRecordHistoryServiceImpl aspEvaluationRecordHistoryService;

    @Override
    public void test(Boolean haveJob, String filePath, String category) {
//        //获取文件目录
//        String filePath = "C:\\Users\\shangmi\\Downloads\\设备活动分级管控清单.xls";
        HashMap<String, String> map = new HashMap<>();
        map.put("山东创新精铝金属制造有限公司", "0001651000000017DRZ1");
        map.put("山东创新板材有限公司", "0001S31000000000J0TR");
        map.put("山东创新箔材科技有限公司", "0001651000000015EFDD");

        HashMap<String, String> map2 = new HashMap<>();
        map2.put("一", "I");
        map2.put("二", "II");
        map2.put("三", "III");
        map2.put("四", "IV");


        //初始化责任单位
        HashMap<String, String> map3 = new HashMap<>();
        List<SysOrganizationDo> organizationDoList = sysOrganizationService.list(new QueryWrapper<SysOrganizationDo>().lambda().isNotNull(SysOrganizationDo::getFullpid).eq(SysOrganizationDo::getDeleted, "0"));
        for (SysOrganizationDo sysOrganizationDo : organizationDoList) {
            map3.put(sysOrganizationDo.getFullpid().split(",")[1] + "-" + sysOrganizationDo.getFullname(), sysOrganizationDo.getId());
        }

        //初始化责任人
        HashMap<String, String> map4 = new HashMap<>();
        List<SysUserDo> userDoList = sysUserService.list(new QueryWrapper<SysUserDo>().lambda().eq(SysUserDo::getDeleted, "0"));
        for (SysUserDo sysUserDo : userDoList) {
            map4.put(sysUserDo.getName(), sysUserDo.getId());
        }

        //初始化序号短码
        HashMap<String, String> map5 = new HashMap<>();
        map5.put("0001S31000000000J0TR", "CXBC");
        map5.put("0001651000000017DRZ1", "CXJL");
        map5.put("0001651000000015EFDD", "CXLB");

        //时间 年月
        String time = DateUtil.format(new Date(), "yyyyMM");

        List<AspRiskSourceDo> resList = new LinkedList<>();

        //读取文件
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             Workbook workbook = new HSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            int i = 1;
            for (Row row : sheet) {
                String cell0 = row.getCell(0).getStringCellValue().trim();
                if (ObjectUtil.isEmpty(cell0)) {
                    continue;
                }
                if (!map.containsKey(cell0)) {
                    continue;
                }
                AspRiskSourceDo aspRiskSourceDo = new AspRiskSourceDo();
                //生成ID
                aspRiskSourceDo.setId(SecurityUtil.getUUID());
                //类别
                aspRiskSourceDo.setCategory(category);

                //所属工厂
                aspRiskSourceDo.setTenantid(map.get(cell0));
                //序号
                aspRiskSourceDo.setSerialnumber(map5.get(aspRiskSourceDo.getTenantid()) + "-" + time + "-AQ-" + String.format("%03d", i));
                //名称
                aspRiskSourceDo.setName(row.getCell(1).getStringCellValue().trim());
                if (haveJob) {
                    //作业活动
                    aspRiskSourceDo.setJobactivity(row.getCell(2).getStringCellValue().trim());
                }
                //作业步骤/内容（检查项目/作业步骤）
                aspRiskSourceDo.setInspectionitem(row.getCell(3).getStringCellValue().trim());
                //检查标准
                aspRiskSourceDo.setInspectionstandard(row.getCell(4).getStringCellValue().trim());
                //可能发生的事故类型及后果
                aspRiskSourceDo.setEventuality(row.getCell(5).getStringCellValue().trim());
                //工程技术措施
                aspRiskSourceDo.setEngineeringmeasure(row.getCell(6).getStringCellValue().trim());
                //管理措施
                aspRiskSourceDo.setControlmeasure(row.getCell(7).getStringCellValue().trim());
                //培训教育
                aspRiskSourceDo.setEducationaltraining(row.getCell(8).getStringCellValue().trim());
                //个体防护措施
                aspRiskSourceDo.setSafeguardprocedures(row.getCell(9).getStringCellValue().trim());
                //应急处置措施
                aspRiskSourceDo.setImprintingmeasures(row.getCell(10).getStringCellValue().trim());
                //评定级别
                String cell15 = row.getCell(11).getStringCellValue().trim();
                if (ObjectUtil.isEmpty(cell15)) {
                    continue;
                }
                if (!map2.containsKey(cell15)) {
                    continue;
                }
                aspRiskSourceDo.setRating(map2.get(cell15));
                //风险分级
                aspRiskSourceDo.setRiskranking(row.getCell(12).getStringCellValue().trim());
                //管控层级
                aspRiskSourceDo.setManagementlevel(row.getCell(13).getStringCellValue().trim());
                //责任单位
                String key = row.getCell(14).getStringCellValue().trim();
                if (ObjectUtil.isNotEmpty(key)) {
                    String[] split = key.split("、");
                    List<String> orgNameList = new LinkedList<>();
                    List<String> orgIdList = new LinkedList<>();
                    for (String s : split) {
                        orgNameList.add(s);
                        orgIdList.add(map3.get(map.get(cell0) + "-" + s));
                    }
                    aspRiskSourceDo.setAccountabilityunnitname(String.join("/", orgNameList));
                    aspRiskSourceDo.setAccountabilityunnitid(String.join(",", orgIdList));
                }
                //责任人
                String key2 = row.getCell(15).getStringCellValue().trim();
                if (ObjectUtil.isNotEmpty(key2)) {
                    String[] split2 = key2.split("、");
                    List<String> userNameList = new LinkedList<>();
                    List<String> userIdList = new LinkedList<>();
                    for (String s : split2) {
                        if (map4.containsKey(s)) {
                            userNameList.add(s);
                            userIdList.add(map4.get(s));
                        }
                    }
                    aspRiskSourceDo.setDutyofficername(String.join(",", userNameList));
                    aspRiskSourceDo.setDutyofficerid(String.join(",", userIdList));
                }

                //合并
                resList.add(aspRiskSourceDo);
                i += 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //插入数据
        this.saveBatch(resList);
    }

    /**
     * 将以评估的非历史记录 变为历史记录并生成新的数据
     */
    @Override
    @Transactional
    public void resetInfo() {
        // 获取所有以评估的数据
        List<AspRiskSourceDo> list = this.list(new LambdaQueryWrapper<AspRiskSourceDo>()
                .eq(BaseDo::getDeleted, "0")
                .eq(AspRiskSourceDo::getAssessstatus, "ypg"));
        if (list.isEmpty()) {
            log.debug("暂无需要重置信息的风险源信息");
            return;
        }
        // 将原来的数据变为 历史记录
        List<String> oldIds = list.stream().map(AspRiskSourceDo::getId).collect(Collectors.toList());
        // 更新历史记录信息
        oldIds.forEach(id -> {
            updateHistory(id);
        });

        // 删除子表数据
        aspEvaluationRecordService.remove(new LambdaQueryWrapper<AspEvaluationRecordDo>().in(AspEvaluationRecordDo::getMasterid, oldIds));
        // 删除主表信息
        this.removeByIds(oldIds);

        // 重新生成新的数据
        list.forEach(info -> {
            info.setAssessstatus("dpg");
            info.setAvgsalary(null);
            info.setRating(null);
            info.setRiskranking(null);
            info.setSerialnumber(null);
            info.setId(SecurityUtil.getUUID());
        });
        this.saveBatch(list);
    }

    /**
     * 更新风险源的历史评估记录
     *
     * @param id
     */
    @Override
    public R updateHistory(String id) {
        log.info("开始更新风险源的历史评估记录");
        AspRiskSourceDo aspRiskSourceDo = this.getById(id);
        if (aspRiskSourceDo == null) {
            log.error("无法通过ID:{}获取到风险源评估信息", id);
            return R.error("无法获取到风险评估信息");
        }
        // 主表
        AspRiskSourceHistoryDo saveData = new AspRiskSourceHistoryDo();
        BeanUtils.copyProperties(aspRiskSourceDo, saveData);

        // 子表
        List<AspEvaluationRecordDo> recordHistoryDos = aspEvaluationRecordService.list(new LambdaQueryWrapper<AspEvaluationRecordDo>()
                .eq(AspEvaluationRecordDo::getMasterid, id)
                .eq(BaseDo::getDeleted, "0"));
        List<AspEvaluationRecordHistoryDo> historySaveList = new ArrayList<>();
        recordHistoryDos.forEach(data -> {
            AspEvaluationRecordHistoryDo aspEvaluationRecordHistoryDo = new AspEvaluationRecordHistoryDo();
            BeanUtils.copyProperties(data, aspEvaluationRecordHistoryDo);
            historySaveList.add(aspEvaluationRecordHistoryDo);
        });
        // 删除历史表的记录
        aspRiskSourceHistoryService.getBaseMapper().removeById(id);
        aspEvaluationRecordHistoryService.getBaseMapper().removeByMasterId(id);
        // 保存;
        aspRiskSourceHistoryService.save(saveData);
        if (!historySaveList.isEmpty()) {
            aspEvaluationRecordHistoryService.saveBatch(historySaveList);
        }
        return R.ok();
    }
}
