package com.malk.huagao.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.huagao.entity.KdYdCustomerLiaison;
import com.malk.huagao.entity.KdYdCustomerReferrer;
import com.malk.huagao.mapper.KdYdCustomerReferrerMapper;
import com.malk.huagao.service.IKdYdCustomerReferrerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-14
 */
@Service
@Slf4j
public class KdYdCustomerReferrerServiceImpl extends ServiceImpl<KdYdCustomerReferrerMapper, KdYdCustomerReferrer> implements IKdYdCustomerReferrerService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdCustomerReferrerMapper kdYdCustomerReferrerMapper;
    @Value(value = "${kd.host}")
    private String kdHost;
    @Override
    public Map<String, Object> insertCustomerReferrer(Map map) {
        Map<String, Object> result = new HashMap<>();

        try {
            MDC.put("MDC_KEY_PID", "1003");
            String formInstId = UtilMap.getString(map, "formInstId");
            String action = UtilMap.getString(map, "type");

            // 处理特殊操作类型
            if ("del".equals(action)) {
                String bm = UtilMap.getString(map, "bm");

                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                Map<String, Object> formParams = new HashMap<>();
                Map<String, Object> djbh = new HashMap<>();
                djbh.put("djbh", bm);
                result.put("data", djbh);
                String jsonStr = JSON.toJSONString(result);
                formParams.put("jsons", jsonStr);

                System.out.println("====" + formParams);
                HttpResponse response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();

                String responseBody = response.body();
                // 返回删除操作的格式
                result.put("table", "KD_YD_CUSTOMER_REFERRER");
                result.put("action", "del");
                result.put("data", new HashMap<String, Object>() {{
                    put("bm", bm);  // 删除的主键或标识
                    put("msg", "删除成功");
                }});
                return result;
            }

            // 查询表单数据
            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                    .formInstId(formInstId)
                    .build(), YDConf.FORM_QUERY.retrieve_id);
            Map formData = ddrNew.getFormData();

            // 提取表单字段
            String mc = UtilMap.getString(formData, "textField_mgqbiouh");
//            String mc = "张三11";
            String sfzh = UtilMap.getString(formData, "textField_mgqbioux");
//            String sfzh = "1656455654";
            String sjh = UtilMap.getString(formData, "textField_mgqbioui");
//            String sjh = "1656455654";
            String bm = UtilMap.getString(formData, "serialNumberField_mhiycezm");
//            String bm = "TJR202615000";

            String xsy = UtilMap.getString(formData, "employeeField_mgqbiouz").replace("[\"", "").replace("\"]", "").trim();

            // 构建返回数据
            Map<String, Object> cusRefData = new HashMap<>();
            cusRefData.put("mc", mc);
            cusRefData.put("sfzh", sfzh);
            cusRefData.put("sjh", sjh);
            cusRefData.put("bm", bm);
            cusRefData.put("xsy", xsy);

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");

            result.put("data", cusRefData);
// 将result转换为JSON字符串
            String jsonStr = JSON.toJSONString(result);
// 构建form参数
            Map<String, Object> formParams = new HashMap<>();
            formParams.put("jsons", jsonStr);
// 发送请求
            System.out.println("formParams====" + formParams);
            HttpResponse response = null;
            if ("add".equals(action)) {
                response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/hgdjydtbcreatecusttjr")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();
            } else {
                response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();
            }

            String responseBody = response.body();
//            System.out.println("res"+responseBody);
            try {
                String code = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("code");
                String msg = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("msg");
                System.out.println("msg"+msg);
                ydClient.operateData(
                        YDParam.builder()
                                .formInstanceId(formInstId)
                                .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_ml08nk3y, textareaField_mkxqgrvq",code, msg)))
                                .useLatestVersion(true).build(),
                        YDConf.FORM_OPERATION.update);
            } catch (Exception e) {
                System.out.println("解析JSON失败: " + e.getMessage());
            }
            log.info("客户推荐人信息同步成功: formInstId={}, mc={}, bm={}", formInstId, mc, bm);

        } catch (Exception e) {
            log.error("客户推荐人信息同步异常", e);

            // 异常处理
            result.put("table", "KD_YD_ORDER");
            result.put("action", "error");
            result.put("data", new HashMap<String, Object>() {{
                put("errorMsg", "操作失败：" + e.getMessage());
            }});
        }

        return result;
    }

}
