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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.plus.entity.ItfTblAzAssignXslxDowload;
import com.zfire.jiasm.syncdata.plus.entity.SysDict;
import com.zfire.jiasm.syncdata.plus.service.ItfTblAzAssignXslxDowloadService;
import com.zfire.jiasm.syncdata.plus.service.SysDictService;
import com.zfire.jiasm.syncdata.service.GLPPXSLXDownloadService;
import com.zfire.jiasm.syncdata.service.PublicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Slf4j
@Service
public class GLPPXSLXDownloadServiceImpl implements GLPPXSLXDownloadService {
    @Resource
    SysDictService sysDictService;
    @Resource
    ItfTblAzAssignXslxDowloadService itfTblAzAssignXslxDowloadService;
    @Resource
    private PublicService publicService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedXSLX(JSONArray jsonArray) {
        List<ItfTblAzAssignXslxDowload> addRec = new ArrayList<>();
        List<ItfTblAzAssignXslxDowload> updateRec = new ArrayList<>();

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

        // 数据同步到本地字典表
        extractedLocalXSLXAddOrUpdate(addRec, updateRec);
        addRec.clear();
        updateRec.clear();
    }


    private void extractedLocalXSLXAddOrUpdate(List<ItfTblAzAssignXslxDowload> addRec, List<ItfTblAzAssignXslxDowload> updateRec) {
        List<SysDict> addSysDict = new ArrayList<>();
        List<SysDict> updateSysDict = new ArrayList<>();
        List<Long> sxlxids = new ArrayList<>();

        // 提取大类字典数据  sysDictService
        List<SysDict> oldSysDictRec =  sysDictService.lambdaQuery().eq(SysDict::getDictType, DictTypeEnum.DICT_TYPE_SALE_TYPE.getCode()).list();
        Map<String, List<SysDict>> oldSysDictRecMap = oldSysDictRec.stream().collect(Collectors.groupingBy(SysDict::getDictCode));



        // 获取新增的
        if (addRec.size()>0){
            for (ItfTblAzAssignXslxDowload item : addRec){
                if (oldSysDictRecMap.containsKey(String.valueOf(item.getXslxid()))){
                    // 修改
                    upXslx(updateSysDict, oldSysDictRecMap, item);
                } else {
                    // 新增
                    if (!sxlxids.contains(item.getXslxid())){
                        addXslx(addSysDict, item);
                        sxlxids.add(item.getXslxid());
                    }
                }
            }
        }
        // 获取修改的
        if (updateRec.size()>0){
            for (ItfTblAzAssignXslxDowload item : updateRec){
                // 修改
                if (oldSysDictRecMap.containsKey(String.valueOf(item.getXslxid()))){
                    upXslx(updateSysDict, oldSysDictRecMap, item);
                } else {
                    // 新增
                    if (!sxlxids.contains(item.getXslxid())){
                        addXslx(addSysDict, item);
                        sxlxids.add(item.getXslxid());
                    }
                }
            }
        }

        // 新增的插入到表
        if (addSysDict.size()>0){
            sysDictService.saveBatch(addSysDict);
            log.info("格力品牌安装销售类型本地字典信息表新增插入了{}条数据",addSysDict.size());
            addSysDict.clear();
        }
        // 更新
        if (updateSysDict.size()>0){
            sysDictService.updateBatchById(updateSysDict);
            log.info("格力品牌安装销售类型本地字典信息表更新修改了{}条数据", updateSysDict.size());
            updateSysDict.clear();
        }
        sxlxids.clear();
    }

    private void upXslx(List<SysDict> updateSysDict, Map<String, List<SysDict>> oldSysDictRecMap, ItfTblAzAssignXslxDowload item) {
        Boolean flag = Boolean.FALSE;
        flag = Boolean.FALSE;

        SysDict v = oldSysDictRecMap.get(String.valueOf(item.getXslxid())).get(0);
        if (!v.getDictValue().equals(item.getXslxmc())){
            v.setDictValue(item.getXslxmc());
            flag = Boolean.TRUE;
        }
        // 修改的为有效
        if (item.getFlag().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
            if (v.getStatus().equals(DictTypeEnum.DICT_TYPE_OFF.getCode())){
                v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
                flag = Boolean.TRUE;
            }
        } else {
            if (v.getStatus().equals(DictTypeEnum.DICT_TYPE_ON.getCode())){
                v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
                flag = Boolean.TRUE;
            }
        }
        if (v.getSortNum() != item.getPxdj()){
            v.setSortNum(item.getPxdj());
            flag = Boolean.TRUE;
        }
        if (flag){
            updateSysDict.add(v);
        }
    }

    private void addXslx(List<SysDict> addSysDict, ItfTblAzAssignXslxDowload item) {
        SysDict v = new SysDict();
        v.setSysDictId(publicService.getUUID());
        v.setDictType(DictTypeEnum.DICT_TYPE_SALE_TYPE.getCode());
        v.setDictCode(String.valueOf(item.getXslxid()));
        v.setDictValue(item.getXslxmc());
        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.setSortNum(item.getPxdj());
        v.setCreateTime(new Date());
        if (item.getCjdt() !=null){
            v.setCreateTime(item.getCjdt());
        }
        addSysDict.add(v);
    }

    private void extractedXSLXAddOrUpdate(JSONArray jsonArray, List<ItfTblAzAssignXslxDowload> addRec, List<ItfTblAzAssignXslxDowload> updateRec) {
        Boolean flag = Boolean.FALSE;
        String synTaskNo = publicService.getUUID();
        // 提取现有的数据信息
        List<ItfTblAzAssignXslxDowload> oldRec =  itfTblAzAssignXslxDowloadService.lambdaQuery().list();
        List<Long> oldRecXslxId = oldRec.stream().map(ItfTblAzAssignXslxDowload::getXslxid).collect(Collectors.toList());
        Map<Long, List<ItfTblAzAssignXslxDowload>> oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblAzAssignXslxDowload::getXslxid));
        for (int i = 0; i < jsonArray.size(); i++) {
            flag = Boolean.FALSE;
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblAzAssignXslxDowload item = JSON.toJavaObject(aData,ItfTblAzAssignXslxDowload.class);
            // 新增或修改数据
            // 修改
            if (oldRecXslxId.contains(item.getXslxid())){
                ItfTblAzAssignXslxDowload old = oldRecMap.get(item.getXslxid()).get(0);
                if (!old.getXslxmc().equals(item.getXslxmc())){
                    old.setXslxmc(item.getXslxmc());
                    flag = Boolean.TRUE;
                }
                if (!old.getPxdj().equals(item.getPxdj())){
                    old.setPxdj(item.getPxdj());
                    flag = Boolean.TRUE;
                }
                if (!old.getFlag().equals(item.getFlag())){
                    old.setFlag(item.getFlag());
                    flag = Boolean.TRUE;
                }
                if (!old.getYxlr().equals(item.getYxlr())){
                    old.setYxlr(item.getYxlr());
                    flag = Boolean.TRUE;
                }
                if (old.getDmc() !=null || item.getDmc() !=null){
                    if (old.getDmc() !=null && item.getDmc() !=null){
                        if (!old.getDmc().equals(item.getDmc())){
                            old.setDmc(item.getDmc());
                            flag = Boolean.TRUE;
                        }
                    } else {
                        flag = Boolean.TRUE;
                        if (item.getDmc() !=null) {
                            old.setDmc(item.getDmc());
                        } else {
                            old.setDmc("");
                        }
                    }
                }
                if (old.getSituation() !=null || item.getSituation() !=null){
                    if (old.getSituation() !=null && item.getSituation() !=null){
                        if (!old.getSituation().equals(item.getSituation())){
                            old.setSituation(item.getSituation());
                            flag = Boolean.TRUE;
                        }
                    } else {
                        flag = Boolean.TRUE;
                        if (item.getSituation() !=null) {
                            old.setSituation(item.getDmc());
                        } else {
                            old.setSituation("");
                        }
                    }
                }
                if (flag){
                    old.setLastModifiedBy("system");
                    old.setLastModifiedDate(new Date());
                    // 操作人
                    if (item.getLastModifiedBy() != null){
                        old.setLastModifiedBy(item.getLastModifiedBy());
                    }
                    // 修改时间
                    if (item.getLastModifiedDate() != null){
                        old.setLastModifiedDate(item.getLastModifiedDate());
                    }
                    updateRec.add(old);
                }
            } else {
                // 新增
                item.setSynTaskNo(synTaskNo);
                if (item.getCreatedBy() ==null){
                    item.setCreatedBy("system");
                }
                if (item.getCreatedDate() == null){
                    item.setCreatedDate(new Date());
                }
                addRec.add(item);
            }
        }
        // 新增的插入到表
        if (addRec.size()>0){
            itfTblAzAssignXslxDowloadService.saveBatch(addRec);
            log.info("格力品牌安装销售类型信息同步新增插入了{}条数据", addRec.size());
        }

        // 更新
        if (updateRec.size()>0){
            itfTblAzAssignXslxDowloadService.updateBatchById(updateRec);
            log.info("格力品牌安装销售类型信息同步更新修改了{}条数据", updateRec.size());
        }
    }
}
