package com.prolog.cs.base.gsp.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.prolog.cs.base.gsp.model.GspUpkeepCheck;
import com.prolog.cs.base.gsp.resource.CommonClient;
import com.prolog.cs.base.gsp.resource.PrestoClient;
import com.prolog.cs.base.gsp.service.GspUpkeepCheckService;
import com.prolog.cs.basic.chain.model.dict.BaseCommonDictType;
import com.prolog.framework.authority.util.HystrixVarUtil;
import com.prolog.framework.bz.common.search.SearchApi;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.utils.JsonUtils;
import com.prolog.framework.utils.ObjectUtils;
import com.prolog.framework.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

@Component
public class AutoUpKeepTask {

    private static Logger logger = LoggerFactory.getLogger(AutoUpKeepTask.class);

    @Autowired
    private CommonClient commonClient;

    @Autowired
    private PrestoClient prestoClient;

    @Autowired
    private GspUpkeepCheckService gspUpkeepCheckService;

    @Resource
    private SearchApi searchApi;

    // 可配置自动养护定时任务的用户信息
    @Value("${prolog.autoUpkeep.enterpriseId:106}")
    private String autoEnterpriseId;

    //@Scheduled(cron="0 20 01 00 * ?")//每月20号，凌晨1点执行 //@Scheduled(cron="0 0 1 * * ?")//每天，凌晨1点执行
    public void autoUpKeepTask(String warehouseId,String cargoOwnerId,String enterpriseId) {
        logger.info("自动养护开始warehouseId="+warehouseId);
        try {
            HystrixRequestContext context = HystrixRequestContext.initializeContext();
            HystrixVarUtil.setUserKey("yj-test");
            RestMessage<BaseCommonDictType> result = commonClient.getDictTypeById("606904192438767616");
            //RestMessage<BaseCommonDictType> result=commonClient.getDictTypeByCode("GSP_YH_AUTO");
            if (result != null && result.isSuccess() && result.getData() != null && result.getData().getIsEnable() != 1) {
                return;
            }
//            Map mapBldg = new HashMap();
//            Map params = new HashMap();
//            params.put("warehouseId",warehouseId);
//            params.put("cargoOwnerId",cargoOwnerId);
//            mapBldg.put("num", "GSP_AUTO_UPKEEP_BLDGS");//GSP-自动养护，查询建筑物、货主
//            mapBldg.put("params",params);
//            RestMessage<List<Map>> bldgResult = prestoClient.search(mapBldg);
//            if (bldgResult == null || !bldgResult.isSuccess() || bldgResult.getData() == null) {
//                logger.info("数据为空" + JSON.toJSONString(bldgResult));
//                return;
//            }
//            List<Map> list = bldgResult.getData();
//
//            // 支持选择仓库 - by Huanglh 2022-01-21
//            if (!StringUtils.isBlank(warehouseId)) {
//                for (Map map : list) {
//                    if (warehouseId.equals(map.get("warehouseId").toString())) {
//                        // 如果仓库匹配，则列表变为只有此条记录
//                        list = Arrays.asList(map);
//                        break;
//                    }
//                }
//            }

            Map<String, String> currentUser = new HashMap<>();
            // 获取企业id
            currentUser.put("enterpriseId", enterpriseId);
//            for (int i = 0; i < list.size(); i++) {
//                Map map = list.get(i);

                Map sonMap = new HashMap();
//                sonMap.put("warehouseId", map.get("warehouseId").toString());
//                sonMap.put("cargoOwnerId", map.get("cargoOwnerId").toString());
                //sonMap.put("bldgId", map.get("bldgId").toString());
                sonMap.put("warehouseId", warehouseId);
                sonMap.put("cargoOwnerId", cargoOwnerId);
                // 查询中还需要企业id
                sonMap.put("currentUser", currentUser);

                Map importantMap = new HashMap();
                importantMap.put("id", "yj_592105438389080064");//GSP-质量管理模块-重点养护菜单
                importantMap.put("params", sonMap);
                RestMessage<List<Map>> importantResult = prestoClient.search(importantMap);
                //List<Map> importantResult = new ArrayList<>();
//                try {
//                    importantResult = searchApi.searchForMap("592105438389080064", sonMap);
//                } catch (Exception e1) {
//                    logger.info("查询重点养护计划失败,原因{}", e1);
//                }
//                if (!ObjectUtils.isNull(importantResult)) {
//                    batchAddGspUpkeepCheckList(importantResult);
//                }
                if (importantResult != null && importantResult.isSuccess() && importantResult.getData() != null) {
                    batchAddGspUpkeepCheckList(importantResult.getData());
                }
                Map normalMap = new HashMap();
                normalMap.put("id", "yj_592360607987142656");//GSP-质量管理模块-一般养护计划菜单
                normalMap.put("params", sonMap);
//                List<Map> normalResult = new ArrayList<>();
//                try {
//                    normalResult = searchApi.searchForMap("592360607987142656", sonMap);
//                } catch (Exception e1) {
//                    logger.info("查询重点养护计划失败,原因{}", e1);
//                }
//                if (!ObjectUtils.isNull(normalResult)) {
//                    batchAddGspUpkeepCheckList(normalResult);
//                }
                RestMessage<List<Map>> normalResult = prestoClient.search(normalMap);
                if (normalResult != null && normalResult.isSuccess() && normalResult.getData() != null) {
                    batchAddGspUpkeepCheckList(normalResult.getData());
                }
//            }
            logger.info("自动养护结束warehouseId="+warehouseId);
        } catch (Exception e) {
            logger.info("自动养护异常warehouseId="+warehouseId,e);
        }
    }

    @Transactional
    public void batchAddGspUpkeepCheckList(List<Map> list) throws Exception {
        List<GspUpkeepCheck> gspUpkeepCheckList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GspUpkeepCheck itemInfo = JsonUtils.parseJsonString(JsonUtils.toString(list.get(i)), new TypeReference<GspUpkeepCheck>() {
            });
            gspUpkeepCheckList.add(itemInfo);
        }
        gspUpkeepCheckService.batchAdd("1", gspUpkeepCheckList);
    }

}
