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.dto.CheckModelDto;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckModel;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckReport;
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 com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

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
    CheckModelMapper checkModelMapper;

    @Autowired
    IdxFeignService idxFeignService;

    @Autowired
    RuleTrigger ruleTrigger;

    @Override
    public IPage<CheckModelDto> selectByOrgCode(int current, int size, String amosOrgCode) {
        Page page = new Page(current,size);

        return checkModelMapper.selectByOrgCode(page,amosOrgCode);

    }


    @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
                .isNotNull(CheckModel::getCheckDate)
                .orderByDesc(CheckModel::getCheckDate)
                .last("limit 1");
        if(!ValidationUtil.isEmpty(amosOrgCode)){
            wrapper.eq(CheckModel::getAmosOrgCode, amosOrgCode);
        }
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void checkAllMode(String amosOrgCode, AgencyUserModel userInfo) {
        String userName = userInfo.getUserName();
        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, userName);
            });
        }
    }

    @Override
    public void checkSingleMode(String modelId, AgencyUserModel userInfo) {
        String userName = userInfo.getUserName();
        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(), userName);
        }
    }

    @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, String userName) {
        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);
        map.put("checkPeopleName", userName);

        // 查询表所有字段
        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();
        }
    }
}

