package com.zfire.jiasm.syncdata.download.order;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.constant.SynStatusEnum;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.ItfTblAzAssignLcLsDownloadService;
import com.zfire.jiasm.syncdata.plus.service.OrderBaseService;
import com.zfire.jiasm.syncdata.plus.service.SysDictRefService;
import com.zfire.jiasm.syncdata.service.AddInstallBusiness;
import com.zfire.jiasm.syncdata.service.JiasmApi;
import com.zfire.jiasm.syncdata.service.PublicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/** 接口方式生成工单
 * 格力品牌安装工单下载后落本地数据表
 *    落业务表 - 修改下载主表处理结果
 */
@Slf4j
@Component
public class InstallBusinessApi {
    @Value("${installinc}")
    private String installinc = "";

    @Autowired
    JiasmApi jiasmApi;
    @Autowired
    OrderBaseService orderBaseService;
    @Resource
    ItfTblAzAssignLcLsDownloadService itfTblAzAssignLcLsDownloadService;
    @Resource
    BaseService baseService;
    @Resource
    AddInstallBusiness addInstallBusiness;
    @Resource
    SysDictRefService sysDictRefService;
    @Resource
    PublicService publicService;


    // 3：工单落入本地表
    @Scheduled(fixedDelayString = "${installin}")
    public void inputOrderInstall() {
        if (installinc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ItfTblAzAssignLcLsDownload> lcls = new ArrayList<>();
        Map<String, List<SysDictRef>> sysDictRefDLMap = new HashMap<>();
        Map<String, List<SysDictRef>> sysDictRefXLMap = new HashMap<>();
        Map<String, List<SysDictRef>> sysDictRefXiLieMap = new HashMap<>();
        Map<String,String> productMap = new HashMap<>();

        // 提取品牌信息
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }
        // 提取品牌商对应的大类信息
        sysDictRefDLMap = getStringListMap(brand);
        // 提取品牌商对应的小类信息
        sysDictRefXLMap = getListMap(brand);
        // 提取品牌商对应的系列信息
        sysDictRefXiLieMap = getMap(brand);

        // 提取现有数据
        publicService.getProductId(productMap);

        // 提取待落本地表的数据
        lcls = itfTblAzAssignLcLsDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignLcLsDownload::getSynStatus, SynStatusEnum.UN_SYN.getCode())
                .lt(ItfTblAzAssignLcLsDownload::getSynTimes, 2)
                .orderByAsc(ItfTblAzAssignLcLsDownload::getSynReqId)
                .list();

        // 测试使用
        /*lcls = itfTblAzAssignLcLsDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignLcLsDownload::getSynReqId,193181L)
                .list();*/


        if (lcls.size()<1){
            log.info("暂无待处理的安装工单: \uF0B7{}",sdf.format(new Date()));
            return;
        }

        log.info("安装工单落本地表开始处理: \uF0B7{}",sdf.format(new Date()));

        /* lclslist = lcls.stream().map(ItfTblAzAssignLcLsDownload::getPgguid).collect(Collectors.toList());
        // 提取已有的订单数据
        orderBasesRecs = orderBaseService.lambdaQuery()
                .select(OrderBase::getPgguid)
                .in(OrderBase::getPgguid,lclslist).list();
        orderBaselist = orderBasesRecs.stream().map(OrderBase::getPgguid).collect(Collectors.toList());*/

        // 按任务号download_task_no，按单来处理
        for (ItfTblAzAssignLcLsDownload item: lcls) {
            OrderBase oldorder = orderBaseService.lambdaQuery()
                    .eq(OrderBase::getPgguid,item.getPgguid()).last("limit 1").one();
            try{
                if (oldorder !=null){
                    // 修改 TL_SynDataFrom_tbl_az_assign_lc_ls_batch
                    addInstallBusiness.updateOrderApi(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                            brand, item, Boolean.FALSE, productMap);
                } else {
                    // 新增 TL_SynDataFrom_tbl_az_assign_lc_ls_batch
                    addInstallBusiness.addOrderApi(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                            brand, item,Boolean.TRUE, productMap);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("安装工单创建失败 销售单号-派工单号：【" + item.getXsdh() + "-"+ item.getPgid()+"】");
                String msg = "接口生成安装工单失败： ";
                if (ex.getMessage()!=null){
                    msg = msg + ex.getMessage();
                }
                item.setSynErrMsg(msg);
                if (msg.length()>1020){
                    item.setSynErrMsg(msg.substring(0,1020));
                }
                item.setSynTime(new Date());
                item.setSynTimes(item.getSynTimes()+1);
                itfTblAzAssignLcLsDownloadService.updateById(item);
            }
        }

        log.info("安装工单落本地表完成: \uF0B7{}",sdf.format(new Date()));
    }


    private Map<String, List<SysDictRef>> getListMap(Brand brand) {
        List<SysDictRef> sysDictxlRef;
        Map<String, List<SysDictRef>> sysDictRefXLMap;
        sysDictxlRef =  sysDictRefService.lambdaQuery()
                .select(SysDictRef::getDictCode,SysDictRef::getDictValue,SysDictRef::getRefDictCode)
                .eq(SysDictRef::getBrandId, brand.getBrandId())
                .eq(SysDictRef::getDictType, DictTypeEnum.DICT_TYPE_SMALL_TYPE.getCode())
                .list();
        sysDictRefXLMap = sysDictxlRef.stream().
                collect(Collectors.groupingBy(SysDictRef::getRefDictCode));
        return sysDictRefXLMap;
    }

    private Map<String, List<SysDictRef>> getStringListMap(Brand brand) {
        List<SysDictRef> sysDictRef;
        Map<String, List<SysDictRef>> sysDictRefDLMap;
        sysDictRef =  sysDictRefService.lambdaQuery()
                .select(SysDictRef::getDictCode,SysDictRef::getDictValue,SysDictRef::getRefDictCode)
                .eq(SysDictRef::getBrandId, brand.getBrandId())
                .eq(SysDictRef::getDictType, DictTypeEnum.DICT_TYPE_MAIN_TYPE.getCode())
                .list();
        sysDictRefDLMap = sysDictRef.stream().
                collect(Collectors.groupingBy(SysDictRef::getRefDictCode));
        return sysDictRefDLMap;
    }

    private void downInformation(ItfTblAzAssignLcLsDownload item) {
        ItfGreeToFaDownloadTaskList tl = new ItfGreeToFaDownloadTaskList();
        tl.setDownloadTaskNo(IdWorker.getIdStr());
        tl.setDownloadKeyValue(item.getPgguid());
        tl.setDownloadTaskType(2206);
        tl.setDownloadStatus(0);
        tl.insert();
    }
    private Map<String, List<SysDictRef>> getMap(Brand brand) {
        List<SysDictRef> sysDictxilieRef;
        Map<String, List<SysDictRef>> sysDictRefXiLieMap;
        sysDictxilieRef =  sysDictRefService.lambdaQuery()
                .select(SysDictRef::getDictCode,SysDictRef::getDictValue,SysDictRef::getRefDictCode)
                .eq(SysDictRef::getBrandId, brand.getBrandId())
                .eq(SysDictRef::getDictType, DictTypeEnum.DICT_TYPE_SERIES.getCode())
                .list();
        sysDictRefXiLieMap = sysDictxilieRef.stream().
                collect(Collectors.groupingBy(SysDictRef::getRefDictCode));
        return sysDictRefXiLieMap;
    }
}
