package com.yeejoin.amos.boot.module.tdc.biz.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.mapper.CheckModelMapper;
import com.yeejoin.amos.boot.module.tdc.api.mapper.CheckResultMapper;
import com.yeejoin.amos.boot.module.tdc.api.service.CheckModelService;
import com.yeejoin.amos.boot.module.tdc.api.vo.SubjectTreeVo;
import com.yeejoin.amos.boot.module.tdc.api.vo.TableColumnsVo;
import com.yeejoin.amos.boot.module.tdc.biz.action.model.IdxProjectModel;
import com.yeejoin.amos.component.rule.RuleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;

/**
 * @author xxz
 */
@Service
public class CheckModelImpl extends ServiceImpl<CheckModelMapper, CheckModel> implements CheckModelService {

    @Autowired
    CheckResultMapper checkResultMapper;

    @Autowired
    IdxFeignService idxFeignService;

    @Autowired
    RuleTrigger ruleTrigger;

    @Override
    public IPage<CheckModel> selectByOrgCode(int current, int size, String amosOrgCode) {
        Page page = new Page(current,size);
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckModel::getAmosOrgCode, amosOrgCode);
//        return baseMapper.selectList(wrapper);
        return this.page(page,wrapper);
    }

    @Override
    public List<CheckModel> selectByOrgCode(String amosOrgCode) {
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckModel::getAmosOrgCode, amosOrgCode);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public CheckModel selectOneByDate(String amosOrgCode) {
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(CheckModel::getAmosOrgCode, amosOrgCode)
                .isNotNull(CheckModel::getCheckDate)
                .orderByDesc(CheckModel::getCheckDate)
                .last("limit 1");
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void checkAllMode(String amosOrgCode) {
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckModel::getAmosOrgCode, amosOrgCode);
        List<CheckModel> checkModels = this.baseMapper.selectList(wrapper);
        String batchNo = UUID.randomUUID().toString();
        if (!CollectionUtils.isEmpty(checkModels)) {
            checkModels.forEach(checkModel -> {
                checkModelRule(checkModel, 0, batchNo, amosOrgCode);
            });
        }
    }

    @Override
    public void checkSingleMode(String modelId) {
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckModel::getSequenceNbr, modelId);
        CheckModel checkModel = this.baseMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(checkModel)) {
            // 调用规则校验模型
            String batchNo = UUID.randomUUID().toString();
            checkModelRule(checkModel, 1, batchNo, checkModel.getAmosOrgCode());
        }
    }

    @Override
    public CheckModel selectCheckModelByNameCode(String modelName, String amosOrgCode) {
        LambdaQueryWrapper<CheckModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckModel::getAmosOrgCode, amosOrgCode);
        wrapper.eq(CheckModel::getModelName, modelName);
        return this.baseMapper.selectOne(wrapper);
    }

    private void checkModelRule(CheckModel checkModel, int checkType, String batchNo, String amosOrgCode) {
        IdxProjectModel idxProjectModel = new IdxProjectModel();
        // 查询表最新一条数据
        String idxTableName = checkModel.getIdxTableName();
        Map<String, Object> map = checkResultMapper.getTables(idxTableName, amosOrgCode);
//        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(map)) {
            new RuntimeException("暂无填报数据");
        }
        map.put("batch_no", batchNo);
        map.put("checkType", checkType);

        // 查询表所有字段
        ResponseModel<JSONObject> model = idxFeignService.queryByTableId(checkModel.getTableId());
        JSONObject result = model.getResult();
        SubjectTreeVo subjectTreeVo = JSON.parseObject(JSON.toJSONString(result), SubjectTreeVo.class);

        List<TableColumnsVo> columns = subjectTreeVo.getTableCols();
        List<Map<String, Object>> list = new ArrayList<>();
        columns.forEach(tableColumnsVo -> {
            Map<String, Object> itemMap = new HashMap<>(3);
            itemMap.put("name", tableColumnsVo.getColumnName());
            itemMap.put("title", tableColumnsVo.getName());
            itemMap.put("type", tableColumnsVo.getColumnType());
            list.add(itemMap);
        });

        idxProjectModel.setPropertys(list);
        idxProjectModel.setItemName(checkModel.getModelName());
        idxProjectModel.setPropertyValues(map);

        // 调用规则校验模型
        try {
            // 没有配决策流，processIds传null即可
            ruleTrigger.publish(idxProjectModel, checkModel.getModelRule(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

