package com.hzya.frame.sysnew.comparison.masterData.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.mdm.mdmModuleSource.dao.impl.MdmModuleSourceDaoImpl;
import com.hzya.frame.mdm.mdmModuleSource.entity.MdmModuleSourceEntity;
import com.hzya.frame.sysnew.application.service.impl.ApplicationCache;
import com.hzya.frame.sysnew.comparison.entity.ComparisonEntity;
import com.hzya.frame.sysnew.comparison.masterData.dao.impl.MasterDataDaoImpl;
import com.hzya.frame.sysnew.comparison.masterData.service.IMasterDataService;
import com.hzya.frame.sysnew.comparison.service.impl.ComparisonServiceImpl;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("MasterDataServiceImpl")
public class MasterDataServiceImpl extends BaseService<ComparisonEntity, String>  implements IMasterDataService {

   @Autowired
    private MasterDataDaoImpl masterDataDaoImpl;
   @Autowired
   private ComparisonServiceImpl comparisonServiceimpl;
   @Autowired
   private MdmModuleSourceDaoImpl mdmModuleSourceDaoImpl;

   @Autowired
   private ApplicationCache applicationCache;
    private String ts = "";

    /**
     *
     * @content 查询经过配置的主数据信息进行同步主数据档案接口
     * @author laborer
     * @date 2024/6/24 0024 9:56
     *
     */

    @Override
    public JsonResultEntity queryArchives(JSONObject json){
//        logger.info("第一次入参"+String.valueOf(json));
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        //查询主数据来源表，根据来源类型为插件得进行分类，获取来源名称和编码
        List<MdmModuleSourceEntity> list = mdmModuleSourceDaoImpl.MdmModuleSourceentityGroupByType();
        if (CollectionUtils.isEmpty(list)) {
            logger.info("数据来源表中没有类型为插件得数据,无法获取来源名称和来源编码");
            return BaseResult.getFailureMessageEntity("数据来源表无插件类型");
        }
        for (MdmModuleSourceEntity mdmModuleSourceEntity : list) {
//            applicationCache.get()
//            logger.info("入参数据"+jsonObject.toString());
             String startTime = DateUtil.format(json.getDate("startTime"),"yyyy-MM-dd HH:mm:ss");//定时任务执行时传入的开始时间
             String endTime =  DateUtil.format(json.getDate("endTime"),"yyyy-MM-dd HH:mm:ss");//定时任务执行时传入的结束时间
//            logger.info("本次任务查询区间开始时间：{} 结束时间：{}",startTime,endTime);
            String tableName = "";
            try {
                //通过不同的应用类型用于拼接sql
                String appTyp = mdmModuleSourceEntity.getAppType();
                String dbCode = mdmModuleSourceEntity.getDbCode();
                String mdmCode = mdmModuleSourceEntity.getMdmCode();
                List<JSONObject> listAll  = new ArrayList<>();
                if("10007".equals(mdmCode)){
                continue;
                }
//                if(!"10003".equals(mdmCode)){
//                    continue;
//                }
                switch (appTyp) {//1、致远OA 2、用友U8C 3、用友BIP
                    case "1":
                        //通过主数据编码判断，不同的接口走不通的查询逻辑
                        switch (mdmCode){
                            case "10003"://致远用户信息
                                tableName = "mdm_user";
                                listAll = bindingUser(jsonObject, mdmModuleSourceEntity, dbCode,startTime,endTime);
                                break;
                            case "10004"://致远客商信息
                                tableName = "mdm_customer";
                                listAll = binDingCust(jsonObject, mdmModuleSourceEntity, dbCode,startTime,endTime);
                                break;
                            case "10007"://银行信息
                                tableName = "mdm_bank";
                                listAll = binDingBank(jsonObject, mdmModuleSourceEntity, dbCode);
                                break;
                            default:
                                logger.info("未匹配到主数据的编码，请检查");
                                break;
                        }
                }
                //调用主数据接口进行数据推送或更新
                if (null != listAll && listAll.size() > 0) {
                    ParametricAssembly(mdmModuleSourceEntity, listAll, mdmCode, tableName);
                } else {
                    logger.info("U8C主数据档案没有需要同步中台的数据");
                }
            } catch (Exception e) {
                logger.info("主数据同步错误:{}",e.getMessage());
                e.printStackTrace();
            }
        }
        return BaseResult.getSuccessMessageEntity("主数据同步成功");
    }
    //绑定银行
    private List<JSONObject> binDingBank(JSONObject jsonObject, MdmModuleSourceEntity mdmModuleSourceEntity, String dbCode)throws Exception {
        List<JSONObject> list = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        if(null != jsonObject && StrUtil.isNotEmpty(jsonObject.getString("code"))){
            String code = jsonObject.getString("code");
            sb.append(" and a.code = '"+code+"'");
        }else{
//            ts = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
            sb.append(" and a.update_time >= '"+ts+"'");
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select id as data_id,a.* from bank a");
        mdmModuleSourceEntity.setDataSourceCode(dbCode);
        List<HashMap<String, Object>> hashMaps = masterDataDaoImpl.queryArchivesByDataSource(stringBuffer.toString(),mdmModuleSourceEntity);
        int i = 0;
        if(CollectionUtils.isNotEmpty(hashMaps)){
            for (HashMap<String, Object> hashMap : hashMaps) {
                JSONObject main = new JSONObject();
                JSONObject mdm = new JSONObject();
                for(String key:hashMap.keySet()) {
                    mdm.put(key, hashMap.get(key));
                }
                main.put("mdm_bank",mdm);
                list.add(main);
            }
        }
        return list;
    }

    //绑定客户档案
    private List<JSONObject> binDingCust(JSONObject jsonObject, MdmModuleSourceEntity mdmModuleSourceEntity, String dbCode,String startTime,String endTime)throws Exception {
        List<JSONObject> list = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        if(null != jsonObject && StrUtil.isNotEmpty(jsonObject.getString("code"))){
            String code = jsonObject.getString("code");
            sb.append(" and a.code = '"+code+"'");
        }else{
//            ts = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
            sb.append(" and a.modify_date >= '"+startTime+"'");
            sb.append(" and a.modify_date < '"+endTime+"'");
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT id as data_id,field0013 AS code,field0014 AS name,field0016 AS pk_custclass,field0015 AS shortname,field0012 AS pk_org FROM formmain_0177 a WHERE 1=1 " +sb.toString());
        mdmModuleSourceEntity.setDataSourceCode(dbCode);
        List<HashMap<String, Object>> hashMaps = masterDataDaoImpl.queryArchivesByDataSource(stringBuffer.toString(),mdmModuleSourceEntity);
        if(CollectionUtils.isNotEmpty(hashMaps)){
            for (HashMap<String, Object> hashMap : hashMaps) {
                JSONObject main = new JSONObject();
                JSONObject mdm_cust = new JSONObject();
                for(String key:hashMap.keySet()) {
                    mdm_cust.put(key, hashMap.get(key));
                }
                //获取明细信息
                Long formmainId = (Long) hashMap.get("data_id");
                StringBuffer stringBufferDetails = new StringBuffer();
                stringBufferDetails.append("SELECT id as data_id ,field0019 AS pk_bankdoc,field0020 AS accnum,field0021 AS combinenum FROM formson_0230 WHERE formmain_id = '"+formmainId+"' " );
                List<HashMap<String, Object>> hashMapsDetails = masterDataDaoImpl.queryArchivesByDataSource(stringBufferDetails.toString(),mdmModuleSourceEntity);
                JSONArray mdm_customer_bank = new JSONArray();
                if(CollectionUtils.isNotEmpty(hashMapsDetails)){
                    for (HashMap<String, Object> detailsMap : hashMapsDetails) {
                        JSONObject details = new JSONObject();
                        for (String key : detailsMap.keySet()) {
                            details.put(key, detailsMap.get(key));
                        }
                        mdm_customer_bank.add(details);
                    }
                }
                main.put("mdm_customer_bank",mdm_customer_bank);
                main.put("mdm_customer",mdm_cust);
                list.add(main);
            }
        }
        return list;
    }

    //绑定OA用户参数
    private List<JSONObject> bindingUser(JSONObject jsonObject, MdmModuleSourceEntity mdmModuleSourceEntity, String dbCode,String startTime,String endTime)throws Exception {
        List<JSONObject> list = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        if(null != jsonObject && StrUtil.isNotEmpty(jsonObject.getString("code"))){
            String code = jsonObject.getString("code");
            sb.append(" and a.code = '"+code+"'");
        }else{
//            ts = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
            sb.append(" and a.update_time >= '"+startTime+"'");
            sb.append(" and a.update_time <> '"+endTime+"'");
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select   a.id as data_id, a.name as user_name,  a.code AS user_code,e.LOGIN_NAME as login_name,CASE WHEN EXT_ATTR_11 = '1' \n" +
                "THEN '男' WHEN EXT_ATTR_11 = '2' THEN '女' ELSE NULL END AS gender,CASE WHEN (a.EXT_ATTR_1 IS NULL OR a.EXT_ATTR_1 ='') THEN '11111111111' ELSE a.EXT_ATTR_1 END  AS mobile FROM org_member a left join org_principal e on a.id = e.MEMBER_ID\n" +
                " WHERE 1=1 and e.LOGIN_NAME IS not null " + sb.toString());
//                " WHERE 1=1 and a.id = '-2698997042624247722'");
        mdmModuleSourceEntity.setDataSourceCode(dbCode);
        List<HashMap<String, Object>> hashMaps = masterDataDaoImpl.queryArchivesByDataSource(stringBuffer.toString(),mdmModuleSourceEntity);
        int i = 0;
        if(CollectionUtils.isNotEmpty(hashMaps)){
            for (HashMap<String, Object> hashMap : hashMaps) {
                JSONObject main = new JSONObject();
               JSONObject mdm_user = new JSONObject();
                for(String key:hashMap.keySet()) {
                    mdm_user.put(key, hashMap.get(key));
                }
                main.put("mdm_user",mdm_user);
                list.add(main);
            }
        }
        return list;
    }


    //查询档案参数组装
    public JsonResultEntity ParametricAssembly(MdmModuleSourceEntity mdmModuleSourceEntity,List<JSONObject>  hashMaps,String mdmCode,String tableName)throws Exception{
            for (JSONObject hashMap : hashMaps) {
                JSONObject main = hashMap.getJSONObject(tableName);

                JSONObject jsonObjectUser = new JSONObject();
                JSONObject jsonStr = new JSONObject();
                jsonObjectUser.put("data_id", main.get("data_id"));
                jsonObjectUser.put("mdmCode", mdmCode);
                jsonStr.put("jsonStr", jsonObjectUser);
                //先查询编码和名称查询是否存在
                Object attribute = comparisonServiceimpl.queryEntityPage(jsonStr);
                logger.info("得到的attribute值为：{}", jsonStr.toJSONString(attribute));
                JSONObject jsonObjectAttribute = (JSONObject) JSON.toJSON(attribute);
                JSONArray jsonArrayList = jsonObjectAttribute.getJSONArray("list");
                //如果jsonArrayList为null，说明没有值，在表中不存在
                if (jsonArrayList == null || jsonArrayList.size() == 0) {
//                    //将查询出来得数据调用通用接口新增，保存到表中
//                    JSONObject main = new JSONObject();
//                    for(String key:hashMap.keySet()) {
//                        main.put(key, hashMap.get(key));
//                    }
//                    jsonObjectUser.put("main", main);
                    hashMap.put("appName","数智中台");
                    hashMap.put("appCode","800004");
                    hashMap.put("mdmCode", mdmCode);
                    hashMap.put("optionName", "数智中台");
                    jsonStr.put("jsonStr", hashMap);
                    Object result = comparisonServiceimpl.saveEntity(jsonStr);
                    logger.info("新增结果为：{}", JSON.toJSONString(result));
//                    if(!result.isFlag()){
//                        throw new BaseSystemException("主数据保存失败"+ result.getMsg());
//                    }
                } else {
                    hashMap.put("appName","数智中台");
                    hashMap.put("appCode","800004");
                    hashMap.put("mdmCode", mdmCode);
                    hashMap.put("optionName", "数智中台");
                    jsonStr.put("jsonStr", hashMap);
                    Object result = comparisonServiceimpl.updateEntity(jsonStr);
                    logger.info("更新结果为：{}", JSON.toJSONString(result));
//                    if(!result.isFlag()){
//                        //throw new BaseSystemException("主数据更新失败"+ result.getMsg());
//                    }
                }
            }
            return null;
    }

}
