package com.malk.siku.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.siku.service.SikuTaskService;
import com.malk.siku.utils.MkBxUtil;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class SikuTaskServiceImpl implements SikuTaskService {
    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient ddClient;

    @Override
    public void syncLoanManage() {
        try {
            log.info("开始同步借还款台账");
            //删除宜搭借款台账
            List<List<String>> formInstanceIdListList = new ArrayList<>();//实例id集合，每100条

            DDR_New ddrNew = new DDR_New();
            int pageSize = 50;
            int pageNumber = 0;
            do {
                pageNumber++;

                ddrNew = retryQueryData(YDParam.builder()
                        .formUuid("FORM-14F79868B683481295062CD1D643E06EVB7B")
                        .searchFieldJson("")
                        .pageNumber(pageNumber)
                        .pageSize(pageSize)
                        .build(), YDConf.FORM_QUERY.retrieve_search_form_id);

                formInstanceIdListList.addAll(Collections.singleton((List<String>) ddrNew.getData()));

//                Thread.sleep(1000);
            }while (ddrNew.getPageNumber() * pageSize < ddrNew.getTotalCount());

            for (List<String> formInstanceIdList : formInstanceIdListList) {
                if (!formInstanceIdList.isEmpty()){
                    retryOperateData(YDParam.builder()
                            .formUuid("FORM-14F79868B683481295062CD1D643E06EVB7B")
                            .formInstanceIdList(formInstanceIdList)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //查询每刻最新借款台账
        List<Map> loanManageList = MkBxUtil.loanManageList();

        for (Map loanManage : loanManageList) {
            String code = UtilMap.getString(loanManage, "code");//台账编号\
            String formCode = UtilMap.getString(loanManage, "formCode");//借款单单据号

            String legalEntityName = UtilMap.getString(loanManage, "legalEntityName");//所属公司
            String departmentName = UtilMap.getString(loanManage, "departmentName");//借款部门
            String employeeName = UtilMap.getString(loanManage, "employeeName");//借款人
            List<String> employeeDdUser = getDdUserId(employeeName);
            String responseUserName = UtilMap.getString(loanManage, "responseUserName");//负责人
            List<String> responseDdUser = getDdUserId(responseUserName);

            String formName = UtilMap.getString(loanManage, "formName");//事由
            String formSubTypeName = UtilMap.getString(loanManage, "formSubTypeName");//单据类型
            long submittedAt = UtilMap.getLong(loanManage, "submittedAt");//提单时间
            long expectRepaymentTime = UtilMap.getLong(loanManage, "expectRepaymentTime");//预计归还时间
            int loanAge = UtilMap.getInt(loanManage, "loanAge");//账龄
            Double amount = UtilMap.getDouble(UtilMap.getMap(loanManage, "approvedAmount"), "amount");//借款金额
            Double owedAmount = UtilMap.getDouble(UtilMap.getMap(loanManage, "owedAmount"), "amount");//未归还(未核销)
            Double pendingAmount = UtilMap.getDouble(UtilMap.getMap(loanManage, "pendingAmount"), "amount");//核销中金额

            //借款单详情
            Map loanDetailInfo = MkBxUtil.loanDetailInfo(formCode);
            Map customObject = UtilMap.getMap(loanDetailInfo, "customObject");

            Map cf0 = UtilMap.getMap(customObject, "CF0");
            String projectCode = UtilMap.getString(cf0, "detailBusinessCode");//项目流水号
            String projectName = UtilMap.getString(cf0, "text");//项目名称

            long settledAt = UtilMap.getLong(loanDetailInfo, "settledAt");//支付时间

            Map formData = new HashMap();
            formData.put("textField_mnsly3li",code);
            formData.put("textField_mnsly3lb",legalEntityName);
            formData.put("textField_mnsly3lc",departmentName);
            formData.put("employeeField_mnsly3mc",employeeDdUser);
            formData.put("employeeField_mnsly3md",responseDdUser);
            formData.put("textField_mnsm8q6f",projectName);
            formData.put("textField_mnwtwu9z",projectCode);
            formData.put("textareaField_mnsly3ll",formName);
            formData.put("textField_mnsly3lg",formSubTypeName);
            formData.put("dateField_mnsly3lx",submittedAt);
            formData.put("dateField_mnsly3ly",expectRepaymentTime);
            formData.put("dateField_mnsly3m3",settledAt);
            formData.put("numberField_mnsly3m4",loanAge);
            formData.put("numberField_mnsly3m5",amount);
            formData.put("numberField_mnsly3ma",owedAmount);
            formData.put("numberField_mnsly3mb",pendingAmount);

            //同步宜搭借款台账
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-14F79868B683481295062CD1D643E06EVB7B")
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.create);
        }
        System.out.println("111");

    }


    //自带重试的operateData方法
    private Object retryOperateData(YDParam param, YDConf.FORM_OPERATION formOperation) {
        int maxAttempts = 3; // 尝试的最大次数
        int attempt = 0;

        Object result = null;

        while (attempt < maxAttempts) {
            try {
                result = ydClient.operateData(param, formOperation);

                return result;
            } catch (McException e) {
                log.info("错误信息：{}",e.getMessage());
                if (e.getMessage().equals("The request has failed due to a temporary failure of the server.")) {
                    attempt++;
                    // 线程睡眠3秒
                    try {
                        Thread.sleep(5000);
                        log.info("尝试第{}次,param:{},FORM_OPERATION:{},异常信息:{}", attempt, JSONObject.toJSONString(param), formOperation,e.getMessage());
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt(); // 重新设置中断状态
                        System.err.println("Sleep interrupted: " + ie.getMessage());
                    }
                }
            } catch (Exception e) {
                log.error("操作失败,param:{},FORM_OPERATION:{},异常信息:{}", JSONObject.toJSONString(param), formOperation,e.getMessage());

                throw new RuntimeException(e);
            }

        }

        throw new RuntimeException("超出最大重试次数,param:"+JSONObject.toJSONString(param)+",FORM_OPERATION:{}"+formOperation);
    }


    //自带重试的queryData方法
    private DDR_New retryQueryData(YDParam param, YDConf.FORM_QUERY formQuery) {
        int maxAttempts = 3; // 尝试的最大次数
        int attempt = 0;

        DDR_New result = null;

        while (attempt < maxAttempts) {
            try {
                result = ydClient.queryData(param, formQuery);

                return result;
            } catch (McException e) {
                log.info("错误信息：{}",e.getMessage());
                if (e.getMessage().equals("The request has failed due to a temporary failure of the server.")) {
                    attempt++;
                    // 线程睡眠3秒
                    try {
                        Thread.sleep(5000);
                        log.info("尝试第{}次,param:{},FORM_QUERY:{},异常信息:{}", attempt, JSONObject.toJSONString(param), formQuery,e.getMessage());
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt(); // 重新设置中断状态
                        System.err.println("Sleep interrupted: " + ie.getMessage());
                    }
                }
            } catch (Exception e) {
                log.error("操作失败,param:{},FORM_QUERY:{},异常信息:{}", JSONObject.toJSONString(param), formQuery,e.getMessage());

                throw new RuntimeException(e);
            }

        }

        throw new RuntimeException("超出最大重试次数,param:"+JSONObject.toJSONString(param)+",FORM_QUERY:{}"+formQuery);
    }

    //根据员工名字匹配员工id
    private List<String> getDdUserId(String Name){
        HashMap body = new HashMap();

        body.put("queryWord", Name);
        body.put("offset",0);
        body.put("size",1);

        String s1 = UtilHttp.doPost("https://api.dingtalk.com/v1.0/contact/users/search", ddClient.initTokenHeader(), null, body);

        List<String> list = JSONObject.parseObject(s1).getJSONArray("list").toJavaList(String.class);

        return list;
    }
}
