package com.zcloud.service.hiddenDangerCheckStandard.impl;

import com.alibaba.excel.EasyExcel;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.dsno2.hiddenDangerCheckStandard.CommonMapper;
import com.zcloud.service.hiddenDangerCheckStandard.CommonItemService;
import com.zcloud.service.hiddenDangerCheckStandard.CommonService;
import com.zcloud.service.hiddenDangerCheckStandard.DictionaryService;
import com.zcloud.util.Tools;
import com.zcloud.util.UuidUtil;
import com.zcloud.util.Warden;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * 说明：隐患排查标准表（通用）
 * 作者：wangpeng
 * 时间：2024-01-25
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class CommonServiceImpl implements CommonService {

    @Resource
    private CommonMapper commonMapper;

    @Autowired
    private CommonItemService commonItemService;
    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 新增
     *
     * @param pd
     * @throws Exception
     */
    @Override
    public void save(PageData pd) throws Exception {
        commonMapper.save(pd);
    }

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

    /**
     * 修改
     *
     * @param pd
     * @throws Exception
     */
    @Override
    public void edit(PageData pd) throws Exception {
        commonMapper.edit(pd);
    }

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

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

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

    /**通过id获取数据
     * @param pd
     * @throws Exception
     */
    @Override
    public PageData getInfo(PageData pd)throws Exception {
        pd = this.findById(pd);
        PageData itemPd = new PageData();
        itemPd.put("COMMON_ID", pd.getString("COMMON_ID"));
        List<PageData> itemList = commonItemService.listAll(itemPd);
        pd.put("itemList", itemList);
        return pd;
    }

    /**
     * 批量删除
     *
     * @param pd
     * @throws Exception
     */
    @Override
    public void deleteAll(PageData pd) throws Exception {
        commonMapper.deleteAll(pd);
    }


    @Override
    public Map<String, String> importExcel(PageData pd, MultipartFile[] excel) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        String errInfo = "success";
        List<Map<Integer, String>> excelInfo = EasyExcel.read(excel[0].getInputStream()).sheet().doReadSync();

        System.out.println(excelInfo);
        Map<String, PageData> dictAll = new HashMap<>();
        List<PageData> dictList = dictionaryService.listAll(new PageData());
        dictList.forEach(dict -> {
            dictAll.put(dict.getString("DICTIONARY_NAME")+"_"+dict.getString("DICTIONARY_LEVEL"), dict);
        });

        List<String> header = new ArrayList<>();
        header.add("检查类别"); //0
        header.add("检查项目"); //1
        header.add("检查内容"); //2
        header.add("检查标准"); //3
        header.add("参考依据"); //4
        header.add("检查合格项"); //5
        header.add("检查不合格项"); //6
        header.add("操作类型"); //7

        List<PageData> dictSaveList = new ArrayList<>();
        List<PageData> dataList = new ArrayList<>();
        int succeeNum = 1;
        int itemSort = 0;
        if ("appendImport".equals(pd.getString("importType"))) {    //重新导入
            PageData itemPd = new PageData();
            itemPd.put("COMMON_ID", pd.getString("COMMON_ID"));
            itemSort = commonItemService.getCount(itemPd);
        }
        StringBuffer errorStr = new StringBuffer();
        for (int i = 0; i < excelInfo.size(); i++) {
            succeeNum++;
            itemSort++;
            PageData data = new PageData();
            data.put("COMMON_ITEM_ID",UuidUtil.get32UUID());
            data.put("COMMON_ITEM_SORT",itemSort);
            Map<Integer, String> mapExcel = excelInfo.get(i);
            PageData dict1 = new PageData();
            PageData dict2 = new PageData();
            for (int j = 0; j < header.size(); j++) {
                if (Tools.isEmpty(mapExcel.get(j)) && j < 7) {
                    errorStr.append("<p>第" + succeeNum + "行的\"" + header.get(j) + "\"无数据</p>");
                    continue;
                }
                if (j == 7) {
                    if (Tools.isEmpty(mapExcel.get(j))) {
                        errorStr.append("<p>第" + succeeNum + "行的\"" + header.get(j) + "\"无数据</p>");
                        continue;
                    } else if (!"选择".equals(mapExcel.get(j).trim()) && !"填写".equals(mapExcel.get(j).trim())) {
                        errorStr.append("<p>第" + succeeNum + "行的\"" + header.get(j) + "\"数据内容不正确，请选择正确选项</p>");
                        continue;
                    }
                }

                if (j<2) {
                    setItemDict(dictAll, mapExcel, j, data, dictSaveList, dict1, dict2);
                } else {
                    switch (j) {
                        case 2:
                            data.put("CHECK_CONTENT", mapExcel.get(j).trim());
                            break;
                        case 3:
                            data.put("CHECK_STANDARD", mapExcel.get(j).trim());
                            break;
                        case 4:
                            data.put("REFERENCE_BASIS", mapExcel.get(j).trim());
                            break;
                        case 5:
                            data.put("CHECK_QUALIFIED", mapExcel.get(j).trim());
                            break;
                        case 6:
                            data.put("CHECK_UNQUALIFIED", mapExcel.get(j).trim());
                            break;
                        case 7:
                            data.put("OPERATION_TYPE", "填写".equals(mapExcel.get(j).trim()) ? 2 : 1);
                            break;
                    }
                }
            }
            dataList.add(data);
        }
        if (Tools.isEmpty(errorStr.toString())) {
            if ("import".equals(pd.getString("importType"))) {
                pd.put("COMMON_ID",UuidUtil.get32UUID());
                pd.put("COMMON_STATUS",1); // 有效
                Warden.initDate(pd);
                this.save(pd);
            }
            for (PageData dict : dictSaveList) {
                Warden.initDate(dict);
                if (Tools.isEmpty(dict.getString("DICTIONARY_SORT"))) {
                    Integer count = dictionaryService.getCount(dict);
                    dict.put("DICTIONARY_SORT", count+1);
                }
                dict.put("DICTIONARY_SOURCE", 1);
                dictionaryService.save(dict);
            }
            if ("reimport".equals(pd.getString("importType"))) {    //重新导入
                Warden.deleteDate(pd);
                commonItemService.deleteByCommon(pd);
            }
            for (PageData entity : dataList) {
                entity.put("COMMON_ID",pd.getString("COMMON_ID"));
                entity.put("COMMON_ITEM_STATUS",1);
                Warden.initDate(entity);
                commonItemService.save(entity);
            }
            errorStr.append("成功导入" + dataList.size() + "条数据!");
        } else {
            errInfo = "error";
        }
        result.put("result", "success");				//返回结果
        result.put("resultType", errInfo);				//返回message类型
        result.put("isExcel","1");				//返回类型
        result.put("resultStr", errorStr.toString());
        return result;
    }

    private void setItemDict(Map<String, PageData> dictAll, Map<Integer, String> map, int j, PageData data, List<PageData> dictSaveList,
                             PageData dict1, PageData dict2) {
        if (dictAll.containsKey(map.get(j).trim()+"_"+(j+1))) {
            switch(j) {
                case 0:
                    dict1 = dictAll.get(map.get(j).trim()+"_"+(j+1));
                    data.put("CHECK_CATEGORY",dict1.getString("DICTIONARY_ID"));
                    break;
                case 1:
                    dict2 = dictAll.get(map.get(j).trim()+"_"+(j+1));
                    data.put("CHECK_ITEM",dict2.getString("DICTIONARY_ID"));
                    break;
            }
        } else {
            if (j == 0) {
                dict1.put("DICTIONARY_ID", UuidUtil.get32UUID());
                dict1.put("DICTIONARY_NAME", map.get(j));
                dict1.put("PARENT_ID", "0");
                dict1.put("PARENT_IDS", dict1.getString("DICTIONARY_ID"));
                dict1.put("DICTIONARY_NAMES", dict1.getString("DICTIONARY_NAME"));
                dict1.put("DICTIONARY_LEVEL", 1);
                dictSaveList.add(dict1);
                dictAll.put(dict1.getString("DICTIONARY_NAME")+"_"+dict1.getString("DICTIONARY_LEVEL"), dict1);
                data.put("CHECK_CATEGORY",dictAll.get(map.get(j)+"_"+(j+1)).getString("DICTIONARY_ID"));
            } else if (j == 1) {
                dict2.put("DICTIONARY_ID", UuidUtil.get32UUID());
                dict2.put("DICTIONARY_NAME", map.get(j));
                dict2.put("PARENT_ID", dict1.getString("DICTIONARY_ID"));
                dict2.put("PARENT_IDS", dict1.getString("DICTIONARY_ID")+","+dict2.getString("DICTIONARY_ID"));
                dict2.put("DICTIONARY_NAMES", dict1.getString("DICTIONARY_NAME")+","+dict2.getString("DICTIONARY_NAME"));
                dict2.put("DICTIONARY_LEVEL", 2);
                dictSaveList.add(dict2);
                dictAll.put(dict2.getString("DICTIONARY_NAME")+"_"+dict2.getString("DICTIONARY_LEVEL"), dict2);
                data.put("CHECK_ITEM",dictAll.get(map.get(j)+"_"+(j+1)).getString("DICTIONARY_ID"));
            }
        }
    }
}

