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

import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.plus.entity.Brand;
import com.zfire.jiasm.syncdata.plus.entity.ItfTblAssignDownload;
import com.zfire.jiasm.syncdata.plus.entity.OrderBase;
import com.zfire.jiasm.syncdata.plus.entity.SysDictRef;
import com.zfire.jiasm.syncdata.plus.service.ItfTblAssignDownloadService;
import com.zfire.jiasm.syncdata.plus.service.OrderBaseService;
import com.zfire.jiasm.syncdata.service.AddRepairBusinessService;
import com.zfire.jiasm.syncdata.service.PublicService;
import lombok.extern.slf4j.Slf4j;
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 RepairBusinessApiT {
    @Value("${repairinc}")
    private String repairinc = "";


    @Resource
    ItfTblAssignDownloadService itfTblAssignDownloadService;
    @Resource
    BaseService baseService;
    @Resource
    OrderBaseService orderBaseService;
    @Resource
    PublicService publicService;
    @Resource
    AddRepairBusinessService addRepairBusinessService;


    // 1：工单落入本地表 TL_SynDataFrom_tbl_assign_batch
    @Scheduled(fixedDelayString = "${repairin}")
    public void inputOrder() {
        if (repairinc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ItfTblAssignDownload> repairRec = new ArrayList<>();
        Map<String,String> productMap = new HashMap<>();

        // 提取品牌信息
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }

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

        // 提取品牌商对应的大类信息
        Map<String, List<SysDictRef>> sysDictRefDLMap = publicService.getStringListMap(brand);
        // 提取品牌商对应的小类信息
        Map<String, List<SysDictRef>> sysDictRefXLMap = publicService.getListMap(brand);
        // 提取品牌商对应的系列信息
        Map<String, List<SysDictRef>> sysDictRefXiLieMap = publicService.getMap(brand);

        // 提取品牌商对应的需求大类信息
        Map<String, List<SysDictRef>> sysDictRefDLMapXq = publicService.getStringListMapXq(brand);
        // 提取品牌商对应的需求小类信息
        Map<String, List<SysDictRef>> sysDictRefXLMapXq = publicService.getListMapXq(brand);

        // 提取待落本地表的数据
        repairRec = itfTblAssignDownloadService.lambdaQuery()
                .eq(ItfTblAssignDownload::getSynStatus, 0)
                // .eq(ItfTblAssignDownload::getSynReqId, 35484L)// 测试使用
                .ge(ItfTblAssignDownload::getSynTimes, 2)
                .orderByAsc(ItfTblAssignDownload::getSynReqId)
                .list();

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

        /*pgids = repairRec.stream().map(ItfTblAssignDownload::getPgid).collect(Collectors.toList());

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

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

        // 按任务号download_task_no，按单来处理
        for (ItfTblAssignDownload item: repairRec){
            OrderBase oldorder = orderBaseService.lambdaQuery()
                    .eq(OrderBase::getPgid,item.getPgid()).last("limit 1").one();
            try{
                if (oldorder !=null){
                    // 修改
                    addRepairBusinessService.updateRepairOrderApi(brand, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, item,
                            sysDictRefDLMapXq, sysDictRefXLMapXq,Boolean.FALSE, productMap);
                } else {
                    // 新增 TL_SynDataFrom_tbl_assign_batch
                    addRepairBusinessService.addRapairOrderApi(brand, item, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                            sysDictRefDLMapXq, sysDictRefXLMapXq,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);
                itfTblAssignDownloadService.updateById(item);
            }
        }
        log.info("维修工单落本地表处理完成: \uF0B7{}",sdf.format(new Date()));
    }

}
