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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.CheckResult;
import com.yeejoin.amos.boot.module.tdc.api.enums.ModeNameProjectIdEnum;
import com.yeejoin.amos.boot.module.tdc.api.enums.ModelNameEnum;
import com.yeejoin.amos.boot.module.tdc.api.enums.TableIdEnum;
import com.yeejoin.amos.boot.module.tdc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.tdc.api.feign.PrivilegeFeignService;
import com.yeejoin.amos.boot.module.tdc.api.feign.UruleFeignService;
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.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
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
    UruleFeignService uruleFeignService;

    @Autowired
    CheckModelService checkModelService;

    @Autowired
    PrivilegeFeignService privilegeFeignService;

    @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();
        }
    }


    @Override
    public String getOrgCode(String companyName) {
        Collection<CompanyModel> companyModelCollection = Privilege.companyClient.queryAgencyTree(companyName).getResult();
        Iterator<CompanyModel> iterator = companyModelCollection.iterator();
        CompanyModel companyModel = iterator.next();
        return companyModel.getOrgCode();
    }

    @Override
    public JSONArray getDataTree() {
        ResponseModel<List> listResponseModel = idxFeignService.dataTree();
        List result = listResponseModel.getResult();
        JSONArray jsonArray = new JSONArray();
        for(Object object: result){
            jsonArray = JSONArray.parseArray(JSONObject.parseObject(JSON.toJSONString(object)).getString("tables"));
        }
        JSONArray jsonArray1 = new JSONArray();
        for(Object object: jsonArray){
            JSONObject ob = JSONObject.parseObject(JSON.toJSONString(object));
            String tableId = ob.getString("tableId");
            String tableName = ob.getString("tableName");
            String url = tableId + "$" + tableName;
            ob.put("url",url);
            jsonArray1.add(ob);

        }
        return jsonArray1;

    }



    @Override
    public List<JSONObject> getRule(String project) {
        List result = uruleFeignService.getRule(project).getResult();
        List<JSONObject> objectList = new ArrayList<>();
        for(Object object: result){
            JSONArray array = JSONObject.parseObject(JSON.toJSONString(object)).getJSONArray("resourceItems");
            for(Object object1: array){
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object1));
                String modelRule = jsonObject.getString("path");
                if(!ValidationUtil.isEmpty(modelRule)){
                    modelRule = modelRule.substring(modelRule.indexOf("/")+1,modelRule.indexOf("."));
                }
                jsonObject.put("path",modelRule);
                objectList.add(jsonObject);
            }
        }
        return objectList;
    }


    @Override
    public List<Object> getCompanyName() {
        List result = privilegeFeignService.getCompanyName().getResult();
        List<Object> objectList = new ArrayList<>();
        for(Object object: result){
            JSONArray array = JSONObject.parseObject(JSON.toJSONString(object)).getJSONArray("children");
            for(Object object1: array){
//                JSONObject ob = JSONObject.parseObject(JSON.toJSONString(object1));
//                String companyName = ob.getString("companyName");
//                String orgCode = ob.getString("orgCode");
//                String text = orgCode + "$" + companyName;
//                ob.put("text",text);
                objectList.add(object1);
            }

        }

        return objectList;
    }



    @Override
    public String saveModel(JSONObject jsonObject){

        List<CheckModel> checkModelList = new ArrayList<>();
        String modelName = jsonObject.getString("model_name");
//        String text = jsonObject.getString("text");
//                截取$之前的所有字符串
//        String amosOrgCode = text.substring(0,text.indexOf("$"));
//                截取$之后的所有字符串
//        String amosOrgName = text.substring(text.indexOf("$")+1);
        String url = jsonObject.getString("idx_table_name");
        //        截取$之前的所有字符串
        String tableId = url.substring(0,url.indexOf("$"));
        //        截取$之后的所有字符串
        String idxTableName = url.substring(url.indexOf("$")+1);
        JSONArray modelPictureUrl = jsonObject.getJSONArray("model_picture_url");
        String pictureUrl = "";
        if(!ValidationUtil.isEmpty(modelPictureUrl)){
            for (Object o : modelPictureUrl) {
                JSONObject jo = JSON.parseObject(JSON.toJSONString(o));
                pictureUrl = jo.getString("url");
                break;
            }
        }
        String modelRule = jsonObject.getString("model_rule");
//        if(!ValidationUtil.isEmpty(modelRule)){
//            modelRule = modelRule.substring(modelRule.indexOf("/")+1,modelRule.indexOf("."));
//        }
        JSONArray modelFile = jsonObject.getJSONArray("model_file");
        String fileUrl = "";
        Iterator iterator = modelFile.iterator();
        if(iterator.hasNext()){
            Object o = iterator.next();
            JSONObject jo = JSON.parseObject(JSON.toJSONString(o));
            fileUrl = fileUrl+jo.getString("url");
            if(iterator.hasNext()){
                fileUrl = fileUrl + ",";
            }
        }

        JSONArray jsonArray = jsonObject.getJSONArray("amos_org_code");
        for (Object o:jsonArray){
            CheckModel checkModel = new CheckModel();
            checkModel.setAmosOrgName(ModelNameEnum.map.get(String.valueOf(o)));
//            checkModel.setAmosOrgCode(amosOrgCode);
//            checkModel.setAmosOrgName(amosOrgName);
            checkModel.setProjectId(ModeNameProjectIdEnum.map.get(ModelNameEnum.map.get(String.valueOf(o))));
            checkModel.setModelName(modelName);
            checkModel.setIdxTableName(idxTableName);
            checkModel.setModelPictureUrl(pictureUrl);
            checkModel.setModelRule(modelRule);
            checkModel.setTableId(tableId);
            checkModel.setModelFile(fileUrl);
            checkModel.setAmosOrgCode(String.valueOf(o));
            checkModelList.add(checkModel);
        }

        checkModelService.saveBatch(checkModelList);
//        .saveBatch(checkModelList);
        return null;
    }



    @Override
    public Boolean modifyModel(JSONObject jsonObject){

        String modelName = jsonObject.getString("modelName");

        String idxTableName = jsonObject.getString("idxTableName");

//        String tableId = url.substring(0,url.indexOf("$"));
        //        截取$之后的所有字符串
//        String idxTableName = url.substring(url.indexOf("$")+1);

        JSONArray PictureUrl = jsonObject.getJSONArray("modelPictureUrl");
        String modelPictureUrl = "";
        if(!ValidationUtil.isEmpty(PictureUrl)){
            for (Object o : PictureUrl) {
                JSONObject jo = JSON.parseObject(JSON.toJSONString(o));
                modelPictureUrl = jo.getString("url");
                break;
            }
        }
        
        String modelRule = jsonObject.getString("modelRule");

//        if(!ValidationUtil.isEmpty(modelRule)){
//            modelRule = modelRule.substring(modelRule.indexOf("/"),modelRule.indexOf("."));
//        }

//        String modelFile = jsonObject.getString("modelFile");
        JSONArray modelFile1 = jsonObject.getJSONArray("modelFile");
        String modelFile = "";
        Iterator iterator = modelFile1.iterator();
        if(iterator.hasNext()){
            Object o = iterator.next();
            JSONObject jo = JSON.parseObject(JSON.toJSONString(o));
            modelFile = modelFile+jo.getString("url");
            if(iterator.hasNext()){
                modelFile = modelFile + ",";
            }
        }


        String amosOrgCode = jsonObject.getString("amosOrgCode");

            CheckModel checkModel = this.getById(jsonObject.getString("sequenceNbr"));
            checkModel.setAmosOrgCode(amosOrgCode);
            checkModel.setModelName(modelName);
            checkModel.setIdxTableName(idxTableName);
            checkModel.setModelPictureUrl(modelPictureUrl);
            checkModel.setModelRule(modelRule);
            checkModel.setModelFile(modelFile);
            checkModel.setTableId(TableIdEnum.map.get(idxTableName));
            checkModel.setAmosOrgName(ModelNameEnum.map.get(amosOrgCode));
            checkModel.setProjectId(ModeNameProjectIdEnum.map.get(ModelNameEnum.map.get(amosOrgCode)));

            checkModelService.updateById(checkModel);


        return null;
//                checkModelMapper.modifyModel(jsonObject);

    }


}

