package com.yeejoin.amos.boot.module.tdc.biz.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckModel;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckResult;
import com.yeejoin.amos.boot.module.tdc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.tdc.api.service.CheckModelService;
import com.yeejoin.amos.boot.module.tdc.api.service.CheckReportService;
import com.yeejoin.amos.boot.module.tdc.api.service.CheckResultService;
import com.yeejoin.amos.boot.module.tdc.api.vo.SubjectTreeVo;
import com.yeejoin.amos.boot.module.tdc.biz.action.model.IdxProjectModel;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author DELL
 */

@Component
@RuleActionBean(beanLabel = "动态预案")
public class CheckModelAction {

    @Autowired
    CheckReportService checkReportService;

    @Autowired
    CheckModelService checkModelService;

    @Autowired
    CheckResultService checkResultService;

    @Autowired
    IdxFeignService idxFeignService;

    @Autowired
    private EmqKeeper emqKeeper;

    @Value("${mqtt.topic.check.complete}")
    private String checkComplete;

    @RuleMethod(methodLabel = "更新检查项结果", project = "保存模型检查项结果")
    public void saveCheckItemResult(@MethodParam(paramLabel = "结果") String result,
                                    @MethodParam(paramLabel = "规范标签内容") String checkExplain,
                                    @MethodParam(paramLabel = "校验项") String checkItem,
                                    @MethodParam(paramLabel = "校验项值") String checkItemValue,
                                    @MethodParam(paramLabel = "对象") IdxProjectModel idxProjectModel) {

        // 1. 检验结果入库
        CheckResult checkResult = new CheckResult();

        Map propertyValues = idxProjectModel.getPropertyValues();
        String batchNo = String.valueOf(propertyValues.get("batch_no"));
        Long submitRecordId = Long.valueOf(String.valueOf(propertyValues.get("submitRecordId")));
//        Integer checkType = Integer.valueOf(String.valueOf(propertyValues.get("checkType")));
        String orgCode = String.valueOf(propertyValues.get("org_code"));
        String checkPeopleName = String.valueOf(propertyValues.get("checkPeopleName"));
        String itemName = idxProjectModel.getItemName();

        // 获取模型
        CheckModel checkModel = checkModelService.selectCheckModelByNameCode(itemName, orgCode);
        if (ObjectUtils.isEmpty(checkModel)) {
            return;
        }

//        if (!CollectionUtils.isEmpty(idxProjectModel.getPropertys()) && StringUtils.isNotEmpty(checkItem)) {
//            Map<String, Object> item = idxProjectModel.getPropertys().stream().filter(map -> checkItem.equals(map.get("name"))).findFirst().orElse(null);
//            if (ObjectUtils.isNotEmpty(item)) {
//                checkResult.setCheckItemLabel(String.valueOf(item.get("title")));
//            }
//        }

        checkResult.setBatchNo(StringUtils.isNotEmpty(batchNo) ? batchNo : String.valueOf(propertyValues.get("id")));
        checkResult.setCheckItemResult(result);
        checkResult.setCheckExplain(checkExplain);
        checkResult.setCheckItem(checkItem);
        checkResult.setCheckItemLabel(checkItem);
        checkResult.setCheckItemValue(checkItemValue);
        checkResult.setModelId(String.valueOf(checkModel.getSequenceNbr()));
        checkResult.setAmosOrgCode(checkModel.getAmosOrgCode());
        checkResult.setAmosOrgName(checkModel.getAmosOrgName());
        checkResult.setSubmitRecordId(submitRecordId);
        checkResult.setCheckDate(new Date());
//        checkResult.setCheckType(ObjectUtils.isNotEmpty(checkType) ? checkType : 1);
        checkResult.setModelName(checkModel.getModelName());
        checkResultService.save(checkResult);

//        // 2. 判断是否检验结束
//        if (ObjectUtils.isNotEmpty(checkType)) {
//            if (checkType == 1) {
//                // 2.2 单独模型校验,根据批次号查询已经入库的属性
//                sendWebMessage(batchNo, checkModel.getCheckItemAmount(), orgCode, checkPeopleName, checkType, itemName);
//            } else if (checkType == 0) {
//                // 2.1 全站校验
//                List<CheckModel> checkModels = checkModelService.selectByOrgCode(orgCode);
//                int sum = checkModels.stream().mapToInt(CheckModel::getCheckItemAmount).sum();
//                sendWebMessage(batchNo, sum, orgCode, checkPeopleName, checkType, itemName);
//            }
//        }
//        else {
//            // 指标填报完自动调用，暂时不需要推送前端
//            String number = ObjectUtils.isNotEmpty(checkType) ? batchNo : String.valueOf(propertyValues.get("id"));
//            Integer itemCount = checkResultService.selectItemCount(number);
//            List property = projectModel.getPropertys();
//            if (itemCount == property.size()) {
//                // 所有属性已全部入库，给前端发送消息
//            }
//        }
    }

    private void sendWebMessage(String batchNo, Integer itemSize, String orgCode, String checkPeopleName, Integer checkType, String itemName) {
        Integer itemCount = checkResultService.selectItemCount(batchNo);
        if (itemCount.equals(itemSize)) {
            // 所有属性已全部入库，给前端发送消息
            HashMap<String, Object> map = new HashMap<>();
            map.put("itemCount", itemCount);
            map.put("batchNo", batchNo);
            String json=JSONObject.toJSONString(map, SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue);
            try {
                emqKeeper.getMqttClient().publish(checkComplete, json.getBytes(), RuleConfig.DEFAULT_QOS, false);
            } catch (MqttException e) {
                e.printStackTrace();
            }

            if (checkType == 0) {
                // 全站校验生成报告
                checkResultService.saveSql(orgCode, checkPeopleName, batchNo);
                List<CheckModel> checkModels = checkModelService.selectByOrgCode(orgCode);
                checkModels.forEach(checkModel -> {
                    saveCheckModel(checkModel, batchNo);
                });
            } else {
                // 更改校验结果
                CheckModel checkModel = checkModelService.selectCheckModelByNameCode(itemName, orgCode);
                saveCheckModel(checkModel, batchNo);
            }
        }
    }

    private void saveCheckModel (CheckModel checkModel, String batchNo) {
        Integer integer = checkResultService.selectItemNo(batchNo, checkModel.getSequenceNbr());
        if (0 == integer) {
            checkModel.setCheckStatus(1);
        } else {
            checkModel.setCheckStatus(2);
        }
        checkModel.setCheckDate(new Date());
        checkModelService.updateById(checkModel);
    }
}
