package com.malk.lilin.Controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.lilin.Service.LiLinService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Configuration
@Slf4j
@EnableScheduling
@ConditionalOnProperty(name = {"enable.scheduling"})
@RequestMapping("/ll")
public class taskController {
    @Autowired
    private LiLinService lilinService;

    public static void main(String[] args) throws IOException {

        System.out.println(token().getData());
//        OkHttpClient client = new OkHttpClient();

//        Request request = new Request.Builder()
//                .url("https://openapi.xencio.com/sandbox/cfa/api/bs/dailyBalance?securityCode=15d6b107643f2b2114a157bcd87f3feb&dateId=20230901&pageNow=1&pageSize=20")
//                .get()
//                .addHeader("x-xencio-client-id", "sandbox")
//                .build();
//        HttpUtil.downloadFile("ss", FileUtil.file())
//        Response response = client.newCall(request).execute();
//        System.out.println(response.body().string());
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://openapi.xencio.com/sandbox/cfa/api/bank/searchBranch?securityCode=" + token().getData() + "&queryType=full")
                .get()
                .addHeader("x-xencio-client-id", "4d9414e89bc24b0d89b678d9f20bc56a")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();
        Response response = client.newCall(request).execute();
    }

    @GetMapping("/token")

    public String token1() {
        return (String) token().getData();
    }

    //    @Scheduled(cron = "0 44 14 * * ?")
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void task() {
        log.info("定时获取单笔付款结果开始：{}", LocalDateTime.now());
        try {
            lilinService.lilinJG(null);
        } catch (Exception e) {
            // 记录错误信息
            e.printStackTrace();
        }


    }

        @Scheduled(fixedRate = 60 * 60 * 1000)
    public void taskLS() {
        log.info("定时获取银行流水结果开始：{}", LocalDateTime.now());
        try {
            lilinService.lilinLS(null);
        } catch (Exception e) {
            // 记录错误信息
            e.printStackTrace();
        }
    }

        @Scheduled(fixedRate = 30 * 60 * 1000)
    public void taskPLJG() {
        log.info("定时获取支付结果发起批量审批开始：{}", LocalDateTime.now());
        try {
            lilinService.taskPLJG();
        } catch (Exception e) {
            // 记录错误信息
            e.printStackTrace();
        }
    }

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDConf ddConf;

    @SneakyThrows
    @PostMapping("/insetRLW")
    McR insetRLW(@RequestBody JSONObject param) {
        String formInstanceId = param.getString("formInstanceId");
        log.info("formInstanceId:{}", formInstanceId);
        // 根据实例ID获取表单数据
        Map data = (Map) ydClient.queryData(YDParam.builder()
                .formInstId(formInstanceId)
                .appType(ydConf.getAppType())
                .systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator())
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        if (data == null) {
            log.warn("formData 为空, formInstanceId:{}", formInstanceId);
            return McR.errorParam("formData 为空");
        }

        // 提取字段值
        String xm = (String) data.get("textField_cbp011r");
        String lxdh = (String) data.get("textField_e03i1pp");
        String zjhm = (String) data.get("textField_zzw8p5a");
        Object cbgszt = data.get("textField_047q8sa");
        String jzgw = (String) data.get("textField_th8v2yz");
        Long htksrq = (Long) data.get("dateField_vcsn4ij");
        Long htjsrq = (Long) data.get("dateField_8hefkvf");
        Long syksrq = (Long) data.get("dateField_v0mq0eh");
        Long syjsrq = (Long) data.get("dateField_5m94qor");
        Integer htqx = (Integer) data.get("numberField_pcryupm");
        String gzd = (String) data.get("textField_mds5v9ws");
        String gzzd = (String) data.get("textField_5ug31ny");
        Integer jbgzzs = (Integer) data.get("numberField_6yzgnbn");
        String sbd = (String) data.get("textField_kvingds");
        Integer sbjs = (Integer) data.get("numberField_49g9wy0");
        Integer gjjjs = (Integer) data.get("numberField_ptdrap4");
        String yglx = (String) data.get("textField_idzudk7");

        // 查询人力窝标志
        List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-3B6D99D1B3E1422BBC848E5AD5FD3B99KQYW")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_md5p9nay", gzd)))
                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();


        String sfrlw = "否"; // 默认值

        if (list != null && !list.isEmpty()) {
            try {
                Map<?, ?> formData = null;
                Object firstItem = list.get(0);

                // 尝试获取 formData 内部数据，如果不存在则使用顶层数据
                if (firstItem instanceof Map) {
                    Map<?, ?> itemMap = (Map<?, ?>) firstItem;
                    Object rawData = itemMap.get("formData");
                    formData = (rawData instanceof Map) ? (Map<?, ?>) rawData : itemMap;
                }

                if (formData != null) {
                    Object val = formData.get("radioField_mde59hby");
                    if (val != null && "是".equals(val.toString().trim())) {
                        sfrlw = "是";
                    }
                }
            } catch (Exception e) {
                log.warn("解析人力窝标志失败", e);
                // 异常时保持 sfrlw = "否"
            }
        }


        // 构建目标表单数据
        Map<String, Object> formData = new HashMap<>();

        formData.put("textField_swflbna", xm);
        formData.put("textField_wlfqmpt", lxdh);
        formData.put("textField_jkc1eg0", zjhm);
        formData.put("textField_ans20nj", cbgszt);
        formData.put("textField_eefjs16", jzgw);
        formData.put("dateField_973ypn3", htksrq);
        formData.put("dateField_1udu9fe", htjsrq);
        formData.put("dateField_uzg03bt", syksrq);
        formData.put("dateField_zqyq80r", syjsrq);
        formData.put("numberField_eeaqsst", htqx);
        formData.put("textField_d4nmf4u", gzd);
        formData.put("textField_1n9ndz9", gzzd);
        formData.put("numberField_ivcq47u", jbgzzs);
        formData.put("textField_6t648n0", sbd);
        formData.put("numberField_ker1ufe", sbjs);
        formData.put("numberField_4b3vaj2", gjjjs);
        formData.put("textField_0jfrjiw", yglx);

        // 设置人力窝相关标志
        if ("是".equals(sfrlw)) {
            formData.put("textField_pqh9s53", "是");
            formData.put("textField_2q3356p", "否");
        } else {
            formData.put("textField_pqh9s53", "否");
            formData.put("textField_2q3356p", "是");
        }

        // 提交到目标表单
        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-4292D265889B4759A29F37F535FE306AP4ER")
                .formDataJson(JSON.toJSONString(formData))
                .userId("01150949543132101208")
                .build(), YDConf.FORM_OPERATION.create);

        return McR.success();
    }

    @PostMapping("/test")
    String  test(@RequestBody Map param) {
//        List<Map> khlist = (List<Map>) ydClient.queryData(
//                YDParam.builder()
//                        .formUuid("FORM-2C2D6EAC04FD48D295590EB6BD287B13DVMV")
//                        .build(),
//                YDConf.FORM_QUERY.retrieve_list_all
//        ).getData();
//
//        List<String> khdaList = khlist.stream()
//                .map(item -> (Map<String, Object>) item.get("formData"))
//                .filter(Objects::nonNull) // 过滤掉 formData 为 null 的
//                .map(formData -> (String) formData.get("textField_mdwiyspj"))
//                .filter(yhzh -> yhzh != null && !yhzh.trim().isEmpty())
//                .collect(Collectors.toList());
        List<String> khdaList = Arrays.asList(
                "1001260509024819590",
                "1001260509424880696",
                "1001260509324868573",
                "1001260509324808614"
        );
        for (String accountNo : khdaList) {
            try {
                // 假设这是你要对每个 accountNo 做的业务逻辑
                System.out.println("正在处理账号: " + accountNo);
            } catch (Exception e) {
                log.error("处理账号失败: {}", accountNo, e);

            }
        }
// 使用结果
//        System.out.println("所有银行账号: " + yhzhList);

//        for (Map<String, Object> item : khlist) {
//            String formInstanceId = (String) item.get("formInstanceId");
//
//            Map<String, Object> formData = (Map<String, Object>) item.get("formData");
//            String textFieldValue = (String) formData.get("textField_m8sjaafp");
//
//            Map<String, Object> formData1 = new HashMap<>();
//
//            formData1.put("associationFormField_mdwt4s1d", Arrays.asList(getkhAss(textFieldValue,formInstanceId)));
//
//            ydClient.operateData(YDParam.builder()
//                    .formUuid("FORM-DAEFD29BDE4D4A7D9DA8DDA848DA3D12X5S8")
//                    .processCode("TPROC--9DD668C1KMQXI9A68YLJ26K02B4M210H4TWDM0")
//                    .formDataJson(JSON.toJSONString(formData1))
//                    .userId("275412081437800471")
//                    .build(), YDConf.FORM_OPERATION.start);
//        }
        return "aa";
    }
    private Object getkhAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_RPH7R3LF3SMXLRDY1ZJW", "FORM-E18CC7F3495B45BB852CB386F325BF03IAS3", "receipt", id, title, "");
    }
    private static McR token() {
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String s = SecureUtil.md5("}bH5%t4_)6e3#" + today);
        return McR.success(s);
    }


}

