package com.zcloud.service.depository.impl;

import com.alibaba.excel.EasyExcel;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.dsno1.depository.HiddenLibraryMapper;
import com.zcloud.service.depository.HiddenLibraryService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Warden;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 说明：隐患库主表
 * 作者：luoxiaobao
 * 时间：2023-08-03
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class HiddenLibraryServiceImpl implements HiddenLibraryService {

    @Resource
    private HiddenLibraryMapper hiddenLibraryMapper;

    @Resource
    private DictionariesService dictionariesService;

    /**
     * 新增
     *
     * @param pd
     * @throws Exception
     */
    public void save(PageData pd) throws Exception {
        Warden.initDate(pd);
        hiddenLibraryMapper.save(pd);
    }

    /**
     * 删除
     *
     * @param pd
     * @throws Exception
     */
    public void delete(PageData pd) throws Exception {
        hiddenLibraryMapper.delete(pd);
    }

    /**
     * 修改
     *
     * @param pd
     * @throws Exception
     */
    public void edit(PageData pd) throws Exception {
        Warden.updateDate(pd);
        hiddenLibraryMapper.edit(pd);
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    public List<PageData> list(Page page) throws Exception {
        return hiddenLibraryMapper.datalistPage(page);
    }

    /**
     * 列表(全部)
     *
     * @param pd
     * @throws Exception
     */
    public List<PageData> listAll(PageData pd) throws Exception {
        return hiddenLibraryMapper.listAll(pd);
    }

    /**
     * 通过id获取数据
     *
     * @param pd
     * @throws Exception
     */
    public PageData findById(PageData pd) throws Exception {
        return hiddenLibraryMapper.findById(pd);
    }

    /**
     * 批量删除
     *
     * @param ArrayDATA_IDS
     * @throws Exception
     */
    public void deleteAll(String[] ArrayDATA_IDS) throws Exception {
        hiddenLibraryMapper.deleteAll(ArrayDATA_IDS);
    }

    @Override
    public void addToLibrary(PageData pd) {
        List<PageData> _ids = Warden.getList(pd.getString("ids"));
        List<String> ids = _ids.stream().map(n -> n.getString("HIDDEN_LIBRARY_ID")).collect(Collectors.toList());
        pd.put("HIDDEN_LIBRARY_IDS", ids);
        hiddenLibraryMapper.addToLibrary(pd);
    }

    @Override
    public PageData readWord(MultipartFile[] excel) throws Exception {
        if (excel.length == 0) {
            throw new RuntimeException("系统异常：未读取到目标文件");
        }
        List<Map<Integer, String>> excelInfo = EasyExcel.read(excel[0].getInputStream()).sheet().doReadSync();

        if (excelInfo.size() > 100) throw new RuntimeException("数据超过100条");

        PageData condition = new PageData();
        // 门类
        List<String> zero = excelInfo.stream().map(n -> n.get(0)).distinct().collect(Collectors.toList());
        for (String _zero : zero) {
            condition.put("NAME", _zero);
            List<PageData> info = dictionariesService.findByCondition(condition);
            if (info == null || info.size() == 0) throw new RuntimeException("导入失败：未查找到关键词：" + _zero + "]");
        }
        // 大类
        List<String> one = excelInfo.stream().map(n -> n.get(1)).distinct().collect(Collectors.toList());
        for (String _one : one) {
            condition.put("NAME", _one);
            List<PageData> info = dictionariesService.findByCondition(condition);
            if (info == null || info.size() == 0) throw new RuntimeException("导入失败：未查找到关键词：" + _one + "]");
        }
        // 中类
        List<String> two = excelInfo.stream().map(n -> n.get(2)).distinct().collect(Collectors.toList());
        for (String _two : two) {
            condition.put("NAME", _two);
            List<PageData> info = dictionariesService.findByCondition(condition);
            if (info == null || info.size() == 0) throw new RuntimeException("导入失败：未查找到关键词：" + _two + "]");
        }
        // 小类
        List<String> three = excelInfo.stream().map(n -> n.get(3)).distinct().collect(Collectors.toList());
        for (String _three : three) {
            condition.put("NAME", _three);
            List<PageData> info = dictionariesService.findByCondition(condition);
            if (info == null || info.size() == 0) throw new RuntimeException("导入失败：未查找到关键词：" + _three + "]");
        }

        List<String> four = excelInfo.stream().map(n -> n.get(4)).filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (four.size() > 0) throw new RuntimeException("隐患区域有空值");

        List<String> five = excelInfo.stream().map(n -> n.get(5)).filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (five.size() > 0) throw new RuntimeException("隐患部位有空值");

        List<String> six = excelInfo.stream().map(n -> n.get(6)).filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (six.size() > 0) throw new RuntimeException("隐患描述有空值");

        List<String> ten = excelInfo.stream().map(n -> n.get(10)).filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (ten.size() > 0) throw new RuntimeException("一级隐患类型有空值");

        List<String> thirteen = excelInfo.stream().map(n -> n.get(13)).filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (thirteen.size() > 0) throw new RuntimeException("整改建议有空值");

        List<PageData> list = excelInfo.stream().map(HiddenLibraryWarden::getExcel).collect(Collectors.toList());
        int index = 2;
        for (PageData entity : list) {
            condition.put("NAME", entity.getString("INDUSTRY_TYPE_ONE"));
            List<PageData> _dic_one = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_one = _dic_one.stream()
                    .filter(n -> "f2598ba72e864eadabf0ca4b664d26b9".equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_one.isPresent()) throw new RuntimeException("行业类型关联性错误");
            entity.put("INDUSTRY_TYPE_ONE", dic_one.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("INDUSTRY_TYPE_TWO"));
            List<PageData> _dic_two = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_two = _dic_two.stream()
                    .filter(n -> dic_one.get().getString("DICTIONARIES_ID").equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_two.isPresent()) throw new RuntimeException("第[" + index + "]行数据，行业类型关联性错误");
            entity.put("INDUSTRY_TYPE_TWO", dic_two.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("INDUSTRY_TYPE_THREE"));
            List<PageData> _dic_three = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_three = _dic_three.stream()
                    .filter(n -> dic_two.get().getString("DICTIONARIES_ID").equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_three.isPresent()) throw new RuntimeException("第[" + index + "]行数据，行业类型关联性错误");
            entity.put("INDUSTRY_TYPE_THREE", dic_three.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("INDUSTRY_TYPE_FOUR"));
            List<PageData> _dic_four = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_four = _dic_four.stream()
                    .filter(n -> dic_three.get().getString("DICTIONARIES_ID").equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_four.isPresent()) throw new RuntimeException("第[" + index + "]行数据，行业类型关联性错误");
            entity.put("INDUSTRY_TYPE_FOUR", dic_four.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("HIDDEN_TYPE_ONE"));
            List<PageData> _dic_h_one = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_h_one = _dic_h_one.stream()
                    .filter(n -> "b4a7325f96af40808ec64c85c162933d".equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_h_one.isPresent()) throw new RuntimeException("第[" + index + "]行数据，隐患区域关联性错误");
            entity.put("HIDDEN_TYPE_ONE", dic_h_one.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("HIDDEN_TYPE_TWO"));
            List<PageData> _dic_h_two = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_h_two = _dic_h_two.stream()
                    .filter(n -> dic_h_one.get().getString("DICTIONARIES_ID").equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_h_two.isPresent()) throw new RuntimeException("第[" + index + "]行数据，隐患区域关联性错误");
            entity.put("HIDDEN_TYPE_TWO", dic_h_two.get().getString("DICTIONARIES_ID"));

            condition.put("NAME", entity.getString("HIDDEN_TYPE_THREE"));
            List<PageData> _dic_h_three = dictionariesService.findByCondition(condition);
            Optional<PageData> dic_h_three = _dic_h_three.stream()
                    .filter(n -> dic_h_two.get().getString("DICTIONARIES_ID").equals(n.getString("PARENT_ID")))
                    .findFirst();
            if (!dic_h_three.isPresent()) throw new RuntimeException("第[" + index + "]行数据，隐患区域关联性错误");
            entity.put("HIDDEN_TYPE_THREE", dic_h_three.get().getString("DICTIONARIES_ID"));

            index++;
        }

        for (PageData entity : list) {
            entity.put("ISDELETE", "0");
            entity.put("SOURCE", "0");
            entity.put("STATUS", "0");
            hiddenLibraryMapper.save(entity);
        }
        return new PageData();
    }

}

