package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.ItfTblAssignGzdmDowloadService;
import com.zfire.jiasm.syncdata.plus.service.RepairBugService;
import com.zfire.jiasm.syncdata.plus.service.SysDictService;
import com.zfire.jiasm.syncdata.service.GLPPGuZhandDaiMaService;
import com.zfire.jiasm.syncdata.service.PublicService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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


@Slf4j
@Service
public class GLPPGuZhandDaiMaServiceImpl implements GLPPGuZhandDaiMaService {
    @Resource
    ItfTblAssignGzdmDowloadService itfTblAssignGzdmDowloadService;
    @Resource
    SysDictService sysDictService;
    @Resource
    RepairBugService repairBugService;
    @Resource
    private PublicService publicService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedGZDMPC(Brand brandRec,JSONArray jsonArray, ItfGreeToFaDownloadPcgzdmTask itfpct) {
        List<ItfTblAssignGzdmDowload> addRec = new ArrayList<>();
        List<ItfTblAssignGzdmDowload> updateRec = new ArrayList<>();

        // 数据同步落到同步信息表
        extractedGZDMAddOrUpdate(jsonArray, addRec, updateRec);

        // 数据同步到本地故障现象表
        extractedGZDMLocalAddOrUpdate(brandRec, addRec, updateRec);

        // 新增的插入到表
        if (addRec.size()>0){
            // 先清除再新增
            QueryWrapper del = new QueryWrapper<ItfTblAssignGzdmDowload>()
                    .gt("gzid", 0);
            itfTblAssignGzdmDowloadService.remove(del);

            itfTblAssignGzdmDowloadService.saveBatch(addRec);
            log.info("格力品牌固障代码信息同步新增插入了{}条数据", addRec.size());
            addRec.clear();
        }

        itfpct.setNeedDownload(0);
        itfpct.updateById();
    }

    private void addRepairBugCheck(Brand brandRec, List<RepairBug> addRepairBug, Map<String, List<SysDict>> xlMap,
                                   Map<String, List<SysDict>> dlMap, ItfTblAssignGzdmDowload item) {
        RepairBug v = new RepairBug();
        v.setBugId(publicService.getUUID());
        v.setGzid(String.valueOf(item.getGzid()));
        v.setBrandId(brandRec.getBrandId());
        v.setBrandName(brandRec.getBrand());
        // 类别不为空时 key名称
        if (xlMap.get(item.getLeib()).get(0)!=null){
            // 小类编号
            v.setSmallId(xlMap.get(item.getLeib()).get(0).getDictCode());
            // 小类名称
            v.setSmallName(xlMap.get(item.getLeib()).get(0).getDictValue());
            // 小类有对应的父类时 提取父类信息
            if (!StringUtils.isEmpty(xlMap.get(item.getLeib()).get(0).getParentDictCode())){
                v.setMainId(xlMap.get(item.getLeib()).get(0).getParentDictCode());
                v.setMainName(dlMap.get(v.getMainId()).get(0).getDictValue());
                v.setMainFlag(dlMap.get(v.getMainId()).get(0).getFlag());
            }
        }
        v.setBugObj(item.getGzmc());
        v.setBugObjCode(item.getGzno());
        v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
        if (item.getFlag().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
            v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        }
        v.setCreateBy("system");
        v.setCreateTime(new Date());
        if (item.getCjren() !=null){
            v.setCreateBy(item.getCjren());
        }
        if (item.getCjdt() != null){
            v.setCreateTime(item.getCjdt());
        }
        addRepairBug.add(v);
    }


    private void addRepairBugFun(Brand brandRec, List<RepairBug> addRepairBug, ItfTblAssignGzdmDowload item) {
        RepairBug v = new RepairBug();
        v.setBugId(publicService.getUUID());
        v.setGzid(String.valueOf(item.getGzid()));
        v.setBrandId(brandRec.getBrandId());
        v.setBrandName(brandRec.getBrand());
        v.setMainId("");
        v.setBugObj(item.getGzmc());
        v.setBugObjCode(item.getGzno());
        v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
        if (item.getFlag().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
            v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        }
        v.setCreateBy("system");
        v.setCreateTime(new Date());
        if (item.getCjren() !=null){
            v.setCreateBy(item.getCjren());
        }
        if (item.getCjdt() != null){
            v.setCreateTime(item.getCjdt());
        }
        addRepairBug.add(v);
    }

    private Boolean addRepairBugCheckt(@NotNull Brand brandRec, List<RepairBug> addRepairBug, Map<String, List<SysDict>> xlMap,
                                       Map<String, List<SysDict>> dlMap, ItfTblAssignGzdmDowload item) {
        RepairBug v = new RepairBug();
        v.setBugId(publicService.getUUID());
        v.setGzid(String.valueOf(item.getGzid()));
        v.setBrandId(brandRec.getBrandId());
        v.setBrandName(brandRec.getBrand());
        // 类别不为空时 key名称
        String leibname = "";
        if (item.getLeib().equals("煤气灶")){
            leibname="燃气灶";
        } else if (item.getLeib().equals("家用热水器") || item.getLeib().equals("商用热水器")){
            leibname="家用空气能热水器";
        } else if (item.getLeib().equals("电风扇/冷风扇/塔扇")){
            leibname="电风扇/冷风扇/大厦扇";
        } else if (item.getLeib().equals("电风扇/冷风扇/塔扇")){
            leibname="电风扇/冷风扇/大厦扇";
        } else if (item.getLeib().equals("抽油烟机")){
            leibname="吸油烟机";
        }
        if (StringUtils.isEmpty(leibname)) {
            return Boolean.TRUE;
        }
        if (!xlMap.containsKey(leibname)){
            return Boolean.TRUE;
        }

        // 小类编号
        v.setSmallId(xlMap.get(leibname).get(0).getDictCode());
        // 小类名称
        v.setSmallName(xlMap.get(leibname).get(0).getDictValue());
        // 小类有对应的父类时 提取父类信息
        if (!StringUtils.isEmpty(xlMap.get(leibname).get(0).getParentDictCode())){
            v.setMainId(xlMap.get(leibname).get(0).getParentDictCode());
            v.setMainName(dlMap.get(v.getMainId()).get(0).getDictValue());
            v.setMainFlag(dlMap.get(v.getMainId()).get(0).getFlag());
        }

        v.setBugObj(item.getGzmc());
        v.setBugObjCode(item.getGzno());
        v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
        if (item.getFlag().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
            v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        }
        v.setCreateBy("system");
        v.setCreateTime(new Date());
        if (item.getCjren() !=null){
            v.setCreateBy(item.getCjren());
        }
        if (item.getCjdt() != null){
            v.setCreateTime(item.getCjdt());
        }
        addRepairBug.add(v);
        return Boolean.FALSE;
    }

    private Boolean addRepairBugCheckd(Brand brandRec, List<RepairBug> addRepairBug, ItfTblAssignGzdmDowload item,
                                       Map<String, List<SysDict>> dlNameMap) {
        RepairBug v = new RepairBug();
        v.setBugId(publicService.getUUID());
        v.setGzid(String.valueOf(item.getGzid()));
        v.setBrandId(brandRec.getBrandId());
        v.setBrandName(brandRec.getBrand());
        // 类别不为空时 key名称
        String leibname = "";
        if (item.getLeib().equals("空调")){
            leibname="家用空调";
        } else if (item.getLeib().equals("家用热水器") || item.getLeib().equals("商用热水器")){
            leibname="家用空气能热水器";
        } else if (item.getLeib().equals("晶弘冰箱")){
            leibname="晶弘冰箱";
        } else if (item.getLeib().equals("洗衣机")){
            leibname="洗衣机";
        } else if (item.getLeib().equals("商用空调")){
            leibname="商用空调";
        } else if (item.getLeib().equals("手机")){
            leibname="手机";
        } else if (item.getLeib().equals("移动电源")){
            leibname="移动电源";
        } else if (item.getLeib().equals("智能门锁")){
            leibname="智能门锁";
        }
        if (StringUtils.isEmpty(leibname)) {
            return Boolean.TRUE;
        }
        if (!dlNameMap.containsKey(leibname)){
            return Boolean.TRUE;
        }
        v.setMainId(dlNameMap.get(leibname).get(0).getDictCode());
        v.setMainName(dlNameMap.get(leibname).get(0).getDictValue());
        v.setMainFlag(dlNameMap.get(leibname).get(0).getFlag());
        v.setBugObj(item.getGzmc());
        v.setBugObjCode(item.getGzno());
        v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
        if (item.getFlag().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
            v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        }
        v.setCreateBy("system");
        v.setCreateTime(new Date());
        if (item.getCjren() !=null){
            v.setCreateBy(item.getCjren());
        }
        if (item.getCjdt() != null){
            v.setCreateTime(item.getCjdt());
        }
        addRepairBug.add(v);
        return Boolean.FALSE;
    }

    private void addXL(Brand brandRec, List<RepairBug> addRepairBug, List<String> xlname, Map<String, List<SysDict>> xlMap,
                       Map<String, List<SysDict>> dlMap, ItfTblAssignGzdmDowload item, List<String> dlname,Map<String, List<SysDict>> dlNameMap) {
        Boolean flag = Boolean.FALSE;
        // leib为小类的名称
        if (xlname.contains(item.getLeib())){
            addRepairBugCheck(brandRec, addRepairBug, xlMap, dlMap, item);
        } else {
            // 部分小类特殊处理
            if (!StringUtils.isEmpty(item.getLeib())){
                // 小类的处理
                flag = addRepairBugCheckt(brandRec, addRepairBug, xlMap, dlMap, item);
                if (flag){
                    // 小类做为大类处理
                    flag = addRepairBugCheckd(brandRec, addRepairBug, item,dlNameMap);
                    if (flag){
                        // 无法对应到类别信息直接添加
                        addRepairBugFun(brandRec, addRepairBug, item);
                    }
                }
            } else {
                // 无小类信息直接添加
                addRepairBugFun(brandRec, addRepairBug, item);
            }
        }
    }

    private void extractedGZDMLocalAddOrUpdate(Brand brandRec, List<ItfTblAssignGzdmDowload> addRec, List<ItfTblAssignGzdmDowload> updateRec) {
        List<RepairBug> addRepairBug = new ArrayList<>();
        // 提取小类字典数据
        List<SysDict> oldSysDictRec =  sysDictService.lambdaQuery()
                .eq(SysDict::getDictType, DictTypeEnum.DICT_TYPE_SMALL_TYPE.getCode())
                .eq(SysDict::getStatus, DictTypeEnum.DICT_TYPE_ON.getCode())
                .list();
        // 小类名称
        List<String> xlname = oldSysDictRec.stream().map(SysDict::getDictValue).collect(Collectors.toList());
        // 小类编号
        Map<String, List<SysDict>> xlMap = oldSysDictRec.stream().collect(Collectors.groupingBy(SysDict::getDictValue));

        // 提取大类字典数据
        List<SysDict> oldDSysDictRec =  sysDictService.lambdaQuery()
                .eq(SysDict::getDictType, DictTypeEnum.DICT_TYPE_MAIN_TYPE.getCode())
                .eq(SysDict::getStatus, DictTypeEnum.DICT_TYPE_ON.getCode()).list();
        // 大类名称
        List<String> dlname = oldDSysDictRec.stream().map(SysDict::getDictValue).collect(Collectors.toList());
        // 大类编号
        Map<String, List<SysDict>> dlMap = oldDSysDictRec.stream().collect(Collectors.groupingBy(SysDict::getDictCode));
        Map<String, List<SysDict>> dlNameMap = oldDSysDictRec.stream().collect(Collectors.groupingBy(SysDict::getDictValue));

        // 获取新增的
        if (addRec.size()>0){
            // 先清除再新增
            QueryWrapper del = new QueryWrapper<RepairBug>()
                    .eq("brand_id", brandRec.getBrandId());
            repairBugService.remove(del);

            for (ItfTblAssignGzdmDowload item : addRec){
                // 类别不存在不新增 这里的类别为类别名称，可能是大类也可能是小类
                // 大类的处理
                // addDL(brandRec, addRepairBug, oldSysDictReclistDL, oldDSysDictRecMapN, oldDSysDictRecMap, item);
                // 小类的处理
                addXL(brandRec, addRepairBug, xlname, xlMap, dlMap, item, dlname, dlNameMap);
            }
        }

        // 新增的插入到表
        if (addRepairBug.size()>0){
            repairBugService.saveBatch(addRepairBug);
            log.info("格力品牌固障代码本地信息表新增插入了{}条数据",addRepairBug.size());
            addRepairBug.clear();
        }
    }

    private void extractedGZDMAddOrUpdate(JSONArray jsonArray, List<ItfTblAssignGzdmDowload> addRec, List<ItfTblAssignGzdmDowload> updateRec) {
        String synTaskNo = publicService.getUUID();

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblAssignGzdmDowload item = JSON.toJavaObject(aData,ItfTblAssignGzdmDowload.class);
            if (StringUtils.isEmpty(item.getGzno())){
                item.setGzno("");
            }
            // 新增或修改数据
            if (StringUtils.isEmpty(item.getLeib())){
                item.setLeib("");
            }
            if (StringUtils.isEmpty(item.getGzmc())){
                item.setGzmc("");
            }
            if (StringUtils.isEmpty(item.getFlag())){
                item.setFlag("有效");
            }
            if (StringUtils.isEmpty(item.getCjwdno())){
                item.setCjwdno("");
            }
            if (item.getPxdj()==null){
                item.setPxdj(0);
            }

            // 新增
            item.setSynTaskNo(synTaskNo);
            if (item.getCreatedBy() ==null){
                item.setCreatedBy("system");
            }
            if (item.getCreatedDate() == null){
                item.setCreatedDate(new Date());
            }
            addRec.add(item);
        }
    }
}
