package com.qmth.sop.business.sync;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qmth.sop.business.service.SysConfigService;
import com.qmth.sop.business.sync.been.fxxk.FxxkAppAuthInfo;
import com.qmth.sop.business.sync.been.fxxk.FxxkAppAuthResult;
import com.qmth.sop.business.sync.been.fxxk.FxxkCrm;
import com.qmth.sop.business.sync.been.fxxk.FxxkUser;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.util.HttpUtil;
import com.qmth.sop.common.util.JacksonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 纷享销客开放接口工具类
 * @Author: CaoZixuan
 * @Date: 2023-10-10
 */
@Component
public class FxxkApiUtils {
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private CommonUtils commonUtils;

    private static final Logger log = LoggerFactory.getLogger(FxxkApiUtils.class);

    @Value("${fxxk.app.id}")
    String fxxkAppId;

    @Value("${fxxk.app.secrete}")
    String fxxkAppSecrete;

    @Value("${fxxk.permanent.code}")
    String fxxkPermanentCode;

    @Value("${fxxk.curren.open.user.id}")
    String fxxkCurrenOpenUserId;

    @Value("${fxxk.api.name.crm}")
    String fxxkApiNameCrm;

    @Value("${fxxk.api.name.crm.detail}")
    String fxxkApiNameCrmDetail;

    /**
     * 查询纷享销客应用级授权
     *
     * @return 应用级授权信息
     */
    public FxxkAppAuthInfo findFxxkAppAuthInfo() {
        String postUrl = sysConfigService.findByConfigKey(SystemConstant.FXXK_APP_AUTH_URL).getConfigValue();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appId", commonUtils.validParam(fxxkAppId, null, true, "纷享销客AppID"));
            map.put("appSecret", commonUtils.validParam(fxxkAppSecrete, null, true, "纷享销客APPSecret"));
            map.put("permanentCode", commonUtils.validParam(fxxkPermanentCode, null, true, "纷享销客永久授权码"));
            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(postUrl, requestJson, null, null, false);
            FxxkAppAuthResult fxxkAppAuthResult = JSONObject.parseObject(result, FxxkAppAuthResult.class);
            if (Objects.isNull(fxxkAppAuthResult) || fxxkAppAuthResult.getErrorCode() != 0) {
                throw ExceptionResultEnum.ERROR.exception("获取纷享销客应用级授权信息失败 : " + fxxkAppAuthResult.getErrorMessage());
            }
            FxxkAppAuthInfo fxxkAppAuthInfo = new FxxkAppAuthInfo();
            fxxkAppAuthInfo.setCorpId(fxxkAppAuthResult.getCorpId());
            fxxkAppAuthInfo.setCorpAccessToken(fxxkAppAuthResult.getCorpAccessToken());
            fxxkAppAuthInfo.setExpiresIn(fxxkAppAuthResult.getExpiresIn());
            return fxxkAppAuthInfo;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 获取当前登录人openUserId
     *
     * @return currentOpenUserId
     */
    public String findCurrentOpenUserId() {
        // 获取openUserId的手机号
        final String mobile = "###";
        String postUrl = sysConfigService.findByConfigKey(SystemConstant.FXXK_USER_BY_MOBILE_URL).getConfigValue();

        try {
            FxxkAppAuthInfo fxxkAppAuthInfo = this.findFxxkAppAuthInfo();
            String corpAccessToken = fxxkAppAuthInfo.getCorpAccessToken();
            String corpId = fxxkAppAuthInfo.getCorpId();

            Map<String, Object> map = new HashMap<>();
            map.put("corpAccessToken", commonUtils.validParam(corpAccessToken, null, true, "企业应用访问公司合法性凭证"));
            map.put("corpId", commonUtils.validParam(corpId, null, true, "开放平台公司帐号"));
            map.put("mobile", commonUtils.validParam(mobile, null, true, "员工手机号"));
            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(postUrl, requestJson, null, null, false);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Long errorCode = jsonObject.getLong("errorCode");
            String errorMessage = jsonObject.getString("errorMessage");
            if (errorCode != 0) {
                throw ExceptionResultEnum.ERROR.exception("获取员工信息失败 : " + errorMessage);
            }
            JSONArray empList = jsonObject.getJSONArray("empList");
            JSONObject emp = empList.getJSONObject(0);
            return emp.getString("openUserId");
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 根据id获取纷享销客用户信息
     *
     * @param userId userId
     * @return 纷享销客用户信息
     */
    public FxxkUser findFxxkUserById(String userId) {
        final String apiName = "PersonnelObj";
        String postUrl = sysConfigService.findByConfigKey(SystemConstant.FXXK_USER_QUERY_URL).getConfigValue();
        try {
            FxxkAppAuthInfo fxxkAppAuthInfo = this.findFxxkAppAuthInfo();
            String corpAccessToken = fxxkAppAuthInfo.getCorpAccessToken();
            String corpId = fxxkAppAuthInfo.getCorpId();

            Map<String, Object> map = new HashMap<>();
            map.put("corpAccessToken", commonUtils.validParam(corpAccessToken, null, true, "企业应用访问公司合法性凭证"));
            map.put("corpId", commonUtils.validParam(corpId, null, true, "开放平台公司帐号"));
            map.put("currentOpenUserId", commonUtils.validParam(fxxkCurrenOpenUserId, null, true, "当前操作人OpenUserID"));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("dataObjectApiName", apiName);

            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("offset", 0.0);
            queryMap.put("limit", 1);

            // 查询
            List<Map<String, Object>> filterMapList = new ArrayList<>();
            // 查询条件1 : 派单状态为正常的
            Map<String, Object> filterMap1 = new HashMap<>();
            filterMap1.put("field_name", "user_id");
            List<String> fieldValues = new ArrayList<>();
            fieldValues.add(userId);
            filterMap1.put("field_values", fieldValues);
            filterMap1.put("operator", "EQ");
            filterMapList.add(filterMap1);
            queryMap.put("filters", filterMapList);
            dataMap.put("search_query_info", queryMap);
            map.put("data", dataMap);

            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(postUrl, requestJson, null, null, false);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Long errorCode = jsonObject.getLong("errorCode");
            String errorMessage = jsonObject.getString("errorMessage");
            if (errorCode != 0) {
                throw ExceptionResultEnum.ERROR.exception("获取自定义对象列表失败 : " + errorMessage);
            }
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataList = data.getJSONArray("dataList");
            JSONObject cell = dataList.getJSONObject(0);
            String fullName = cell.getString("full_name");
            String phone = cell.getString("phone");
            String id = cell.getString("user_id");

            FxxkUser fxxkUser = new FxxkUser();
            fxxkUser.setId(id);
            fxxkUser.setFullName(fullName);
            fxxkUser.setPhone(phone);
            return fxxkUser;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 查询自定义对象列表
     */
    public List<FxxkCrm> findCustomList() {
        String postUrl = sysConfigService.findByConfigKey(SystemConstant.FXXK_CUSTOM_QUERY_URL).getConfigValue();
        try {
            FxxkAppAuthInfo fxxkAppAuthInfo = this.findFxxkAppAuthInfo();
            String corpAccessToken = fxxkAppAuthInfo.getCorpAccessToken();
            String corpId = fxxkAppAuthInfo.getCorpId();

            Map<String, Object> map = new HashMap<>();
            map.put("corpAccessToken", commonUtils.validParam(corpAccessToken, null, true, "企业应用访问公司合法性凭证"));
            map.put("corpId", commonUtils.validParam(corpId, null, true, "开放平台公司帐号"));
            map.put("currentOpenUserId", commonUtils.validParam(fxxkCurrenOpenUserId, null, true, "当前操作人OpenUserID"));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("dataObjectApiName", fxxkApiNameCrm);

            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("offset", 0.0);
            queryMap.put("limit", 1000.0);

            // 查询
            List<Map<String, Object>> filterMapList = new ArrayList<>();
            // 查询条件1 : 派单状态为正常的
            Map<String, Object> filterMap1 = new HashMap<>();
            filterMap1.put("field_name", "life_status");
            List<String> fieldValues = new ArrayList<>();
            fieldValues.add("normal");
            filterMap1.put("field_values", fieldValues);
            filterMap1.put("operator", "EQ");
            filterMapList.add(filterMap1);

//            // 查询条件2 : 派单号为
//            Map<String, Object> filterMap2 = new HashMap<>();
//            filterMap2.put("field_name", "name");
//            List<String> fieldValues2 = new ArrayList<>();
//            fieldValues2.add("Od-2023-11-0903");
//            filterMap2.put("field_values", fieldValues2);
//            filterMap2.put("operator", "EQ");
//            filterMapList.add(filterMap2);

            // 查询条件3 : 同步状态为ture的
            Map<String, Object> filterSyncMap = new HashMap<>();
            filterSyncMap.put("field_name", "field_f4uvT__c");
            List<String> fieldSyncValues = new ArrayList<>();
            fieldSyncValues.add("option1");
            filterSyncMap.put("field_values", fieldSyncValues);
            filterSyncMap.put("operator", "EQ");
            filterMapList.add(filterSyncMap);

            queryMap.put("filters", filterMapList);

            // 排序
            List<Map<String, Object>> orderMapList = new ArrayList<>();
            // 最后更新时间降序
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("fieldName", "last_modified_time");
            orderMap.put("isAsc", false);
            orderMapList.add(orderMap);
            queryMap.put("orders", orderMapList);

            dataMap.put("search_query_info", queryMap);
            map.put("data", dataMap);

            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(postUrl, requestJson, null, null, false);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Long errorCode = jsonObject.getLong("errorCode");
            String errorMessage = jsonObject.getString("errorMessage");
            if (errorCode != 0) {
                throw ExceptionResultEnum.ERROR.exception("获取自定义对象列表失败 : " + errorMessage);
            }
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataList = data.getJSONArray("dataList");

            List<FxxkCrm> fxxkCrmList = new ArrayList<>();

            // 纷享销客用户map
            Map<String,FxxkUser> fxxkUserMap = new HashMap<>();
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject cell = dataList.getJSONObject(i);

                String crmName = cell.getString("display_name");
                String crmNo = cell.getString("name");
                Long beginTime = cell.getLong("create_time");

                JSONArray ownerArr = cell.getJSONArray("owner");
                if (CollectionUtils.isEmpty(ownerArr)){
                    throw ExceptionResultEnum.ERROR.exception("获取自定义对象用户uuid失败");
                }
                String userId = ownerArr.getString(0);
                FxxkUser fxxkUser;
                if (fxxkUserMap.containsKey(userId)){
                    fxxkUser = fxxkUserMap.get(userId);
                } else {
                    fxxkUser = this.findFxxkUserById(userId);
                    fxxkUserMap.put(userId,fxxkUser);
                }
                String managerName = fxxkUser.getFullName();
                String managerMobileNumber = fxxkUser.getPhone();

                String customTypeStr = cell.getString("field_spOcm__c");
                ProductTypeEnum productType = null;
                if (customTypeStr != null && customTypeStr.length() > 0) {
                    switch (customTypeStr) {
                        case "kvdZqVYXU":
                            productType = ProductTypeEnum.OFFICE;
                            break;
                        case "yD18iX9oz":
                            productType = ProductTypeEnum.CLOUD_MARK;
                            break;
                    }
                }

                String customName = cell.getString("field_6TD92__c__r");
                String customCounty = cell.getString("field_O0l25__c__r");
                String customProvince = cell.getString("field_Nc2M6__c__r");
                String customCity = cell.getString("field_270tB__c__r");
                String customAddress = cell.getString("field_KmXg2__c");

                Long examStartTime = cell.getLong("field_Fl84j__c");
                Long examEndTime = cell.getLong("field_Gcsmt__c");

                Boolean sync = null;
                String syncStr = cell.getString("field_f4uvT__c");
                if (syncStr != null && syncStr.length() > 0) {
                    switch (syncStr) {
                        case "option1":
                            sync = true;
                            break;
                        case "cJB5sxeMC":
                            sync = false;
                            break;
                    }
                }


                FxxkCrm fxxkCrm = new FxxkCrm();
                fxxkCrm.setCrmName(crmName);
                fxxkCrm.setCrmNo(crmNo);
                fxxkCrm.setBeginTime(beginTime);
                fxxkCrm.setManagerName(managerName);
                fxxkCrm.setManagerMobileNumber(managerMobileNumber);
                fxxkCrm.setCustomType(productType);
                fxxkCrm.setCustomName(customName);
                fxxkCrm.setCustomCounty(customCounty);
                fxxkCrm.setCustomProvince(customProvince);
                fxxkCrm.setCustomCity(customCity);
                fxxkCrm.setCustomAddress(customAddress);
                fxxkCrm.setExamStartTime(examStartTime);
                fxxkCrm.setExamEndTime(examEndTime);
                fxxkCrm.setSync(sync);
                fxxkCrmList.add(fxxkCrm);
            }
            return fxxkCrmList;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }
}
