package com.malk.lilin.Controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.aliwork.YDSearch;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

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

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


//        Map<String, String> accountMap = new HashMap<>();
//        accountMap.put("上海韵林礼品有限公司", "1001260509024819590");
//        accountMap.put("上海礼林文化科技有限公司", "1001260509424880696");
//        accountMap.put("上海泰辰印务科技有限公司", "1001260509324868573");
//        accountMap.put("允临实业（上海）有限公司", "1001260509324808614");


//        if (fromAccountName != null && !fromAccountName.trim().isEmpty()) {
//            fromAccountCode = accountMap.get(fromAccountName.trim());
//        }
//        String jsonStr = "[{\"selectField_m9ze3rjf_id\":\"采购付款单\",\"associationFormField_ma13k7v2_id\":\"\\\"[{\\\\\\\"formType\\\\\\\":\\\\\\\"receipt\\\\\\\",\\\\\\\"formUuid\\\\\\\":\\\\\\\"FORM-754586D31BF6414586E5C20DB3774A7320CV\\\\\\\",\\\\\\\"instanceId\\\\\\\":\\\\\\\"FINST-QDD66PD1XGAXX17CDYL045FI3SY933KKC71EM1AC\\\\\\\",\\\\\\\"appType\\\\\\\":\\\\\\\"APP_RPH7R3LF3SMXLRDY1ZJW\\\\\\\",\\\\\\\"title\\\\\\\":\\\\\\\"FK20250807210\\\\\\\"}]\\\"\",\"textField_m9ze3rjl\":\"礼林-支付宝\",\"selectField_m9ze3rjf\":\"采购付款单\",\"employeeField_maoqsosw_id\":[\"2836573524682418\"],\"employeeField_maoqsosw\":[\"刘磊\"],\"textField_mb7lyjy7\":\"上海礼林文化科技有限公司\",\"textField_m9ze3rjx\":\"/\",\"textField_ma13k7v4\":\"CGFK20250807154\",\"textField_ma13k7v3\":\"FK20250807210\",\"textField_m9ze3rjs\":\"info@pppmerch.com\",\"numberField_m9ze3rk4\":51.9,\"numberField_m9ze3rk4_value\":\"51.9\",\"textField_m9ze3rjr\":\"支付宝\",\"textField_m9ze3rk3\":\"货款\"}]";
//
//        JSONArray outerArray = JSON.parseArray(jsonStr);
//
//        JSONObject firstItem = outerArray.getJSONObject(0);
//
//        // Step 2: 获取嵌套的JSON字符串（包含转义字符）
//        String nestedJsonStr = firstItem.getString("associationFormField_ma13k7v2_id");
//
//        // Step 3: 清理字符串（去除首尾引号和转义符）
//        String cleanedJsonStr = nestedJsonStr
//                .replaceAll("^\"|\"$", "")  // 去除首尾双引号
//                .replace("\\\"", "\"");     // 将\"转义符还原为"
//        log.info("cleanedJsonStr:{}", cleanedJsonStr);
//
//        // Step 4: 解析内部JSON数组
//        JSONArray innerArray = JSON.parseArray(cleanedJsonStr);
//        log.info("innerArray:{}", innerArray);
//        JSONObject innerObj = innerArray.getJSONObject(0);
//        log.info("innerObj:{}", innerObj);


// 过滤长度大于3的名字并转换为大写
//        List<String> result = names.stream()
//                .filter(name -> name.length() > 3)
//                .map(String::toUpperCase)
//                .collect(Collectors.toList());
    }

    @GetMapping("/token")

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

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


    }

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

//    @Scheduled(fixedRate = 30 * 60 * 1000)
@Scheduled(cron = "0 0 * * * *")
    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")
    McR test(@RequestBody Map param) throws IOException{

//        List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder()
//                .formUuid("FORM-754586D31BF6414586E5C20DB3774A7320CV")
//                .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
//                        new YDSearch("selectField_ma0w9yrb",
//                                Arrays.asList("未审批"),
//                                "SelectField",
//                                YDSearch.Type.RADIO_FIELD,
//                                YDSearch.Operator.CONTAINS)
//                )))
//                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        List<String> khdaList = Arrays.asList(
                "1001260509024819590"

        );

        // 获取 token 一次
        String securityCode;
        try {
            securityCode = String.valueOf(token().getData());
            if (securityCode == null || securityCode.isEmpty()) {
                log.error("获取 securityCode 失败");
                return McR.errorParam("安全码获取失败");
            }
        } catch (Exception e) {
            log.error("调用 token() 异常", e);
            return McR.errorParam("认证信息获取失败");
        }

        OkHttpClient client = new OkHttpClient();

        for (String accountNo : khdaList) {
            Response response = null;
            try {
                if (accountNo == null || accountNo.trim().isEmpty()) {
                    log.warn("跳过空 accountNo");
                    continue;
                }
                accountNo = accountNo.trim();

                log.info("开始对账单同步，accountNo: {}", accountNo);

                // 准备时间范围
                String dayFromId = LocalDate.now().minusDays(10).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                String dayToId = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

                // 构建 POST 请求体
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                String requestBodyStr = "securityCode=" + securityCode +
                        "&accountNo=" + accountNo +
                        "&dayFromId=" + dayFromId +
                        "&dayToId=" + dayToId +
                        "&instructionIdFlag=1" +
                        "&pageNow=1" +
                        "&trxFlag=R" +
                        "&pageSize=20";

                okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, requestBodyStr);

                Request request = new Request.Builder()
                        .url("https://x.xencio.com/c4c3/api/bs/list")
                        .post(body)
                        .addHeader("x-xencio-client-id", "7dc3a31209b94a91ba40a44358fe70eb")
                        .addHeader("content-type", "application/x-www-form-urlencoded")
                        .build();

                response = client.newCall(request).execute();

                if (!response.isSuccessful()) {
                    log.error("银行接口调用失败，HTTP状态码: {}", response.code());
                    continue; // 跳过当前账号
                }

                String jsonStr = response.body().string();
                log.debug("银行接口响应原始数据: {}", jsonStr);

                JSONObject jsonObject = JSON.parseObject(jsonStr);
                JSONObject data = jsonObject.getJSONObject("data");
                System.out.println(data);
//                JSONArray statementList = data.getJSONArray("searchBankStatementList");
//                if (statementList == null || statementList.isEmpty()) {
//                    log.info("银行接口返回空列表，accountNo: {}", accountNo);
//                    continue;
//                }
//
//                List<Map<String, String>> extractedList = new ArrayList<>();
//
//                for (int i = 0; i < statementList.size(); i++) {
//                    JSONObject item = statementList.getJSONObject(i);
//                    if (item == null) continue;
//
//                    Map<String, String> extractedItem = new HashMap<>();
//                    String bankStatementId = getStringValue(item, "bankStatementId");
//                    String bankComments = getStringValue(item, "bankComments");
//                    String crAmount = getStringValue(item, "crAmount");
//                    String trxDate = getStringValue(item, "trxDate");
//                    String createDate = getStringValue(item, "createDate");
//                    String accountName = getStringValue(item, "accountName"); // 本方账号名称
//                    String userRemarks = getStringValue(item, "userRemarks");
//                    String userMemo = getStringValue(item, "userMemo");
//                    String transFlag = getStringValue(item, "transFlag");
//                    String catalogName = getStringValue(item, "catalogName");
//                    String customerName = getStringValue(item, "customerName"); // 对手方账户名称
//               extractedItem.put("customerName", customerName);
//                    extractedList.add(extractedItem);
//                }
//                System.out.println("==="+extractedList);
//
//                extractedList.forEach(item -> {
//                    String customerName = item.get("customerName");
//                    System.out.println("====="+JSON.toJSONString(UtilMap.map("textField_m8sjaafp, aa", customerName,"")));
//                    log.info("银行接口返回数据: {}", item);
//                    List<Map> khlist = (List<Map>) ydClient.queryData(
//                            YDParam.builder()
//                                    .formUuid("FORM-E18CC7F3495B45BB852CB386F325BF03IAS3")
//                                    .appType("APP_RPH7R3LF3SMXLRDY1ZJW")
//                                    .systemToken("7M866K91D4LVACB4EADAZ5UJG7IN3OGA33WAMNT")
//                                    .searchCondition(JSON.toJSONString(UtilMap.map("textField_m8sjaafp", customerName)))
//                                    .build(),
//                            YDConf.FORM_QUERY.retrieve_list_all
//                    ).getData();
//                });

            }
            catch (Exception e) {
                log.error("调用银行接口异常", e);
                continue;
            }
        }

//        return McR.success(list);
//        lilinService.taskPLJG();
//        String formInstanceId = String.valueOf(param.get("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 xmdbh = (String) data.get("textField_m25j5gxk");//项目点编号
//        String kpzq = (String) data.get("textField_m25j5gxv");//开票周期
//        String hsxjStr = (String) data.get("numberField_lvdnme0z");//含税小计
//        BigDecimal hsxj = hsxjStr != null && hsxjStr.trim().length() > 0 ? new BigDecimal(hsxjStr) : BigDecimal.ZERO;
//        List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-97BA6C6C8C50416A9E5854F2F4B5C3F3R4WC")
//                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_ltxrn8h1", xmdbh)))
//                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
//
//        for (Map<String, Object> item : list) {
//            String formInstanceIdItem = (String) item.get("formInstanceId");
//            Map<String, Object> formData = (Map<String, Object>) item.get("formData");
//            List<Map> tableFieid = (List<Map>) formData.get("tableField_lrru2tnq");
////            List<Map> updateList = new ArrayList<>();
//            if (tableFieid != null) {
//                for (Map<String, Object> tableItem : tableFieid) {
//                    String zq = (String) tableItem.get("textField_luh0k82j");
//                    if (kpzq.equals(zq)) {
//                        String xjStr = (String) tableItem.get("numberField_lrru2to2");//开票金额保留两位小数
//                        BigDecimal xj = xjStr != null && !xjStr.trim().isEmpty() ? new BigDecimal(xjStr) : BigDecimal.ZERO;
//                        BigDecimal newXj = xj.add(hsxj); // 原金额 + 含税小计
//                        // 保留两位小数，四舍五入
//                        tableItem.put("numberField_lrru2to2", newXj);
////                        updateList.add(tableItem);
//                    }
////                    updateList.add(tableItem);
//                }
//            }
//            formData.put("tableField_lrru2tnq", tableFieid);
//            ydClient.operateData(YDParam.builder()
//                    .formInstanceId(formInstanceIdItem)
//                    .updateFormDataJson(JSON.toJSONString(formData))
//                    .build(), YDConf.FORM_OPERATION.update);
//        }

        return McR.success();
    }
    private String getStringValue(JSONObject json, String key) {
        Object value = json.get(key);
        return value == null ? "" : value.toString();
    }
    @Autowired
    private DDClient ddClient;

    @PostMapping("/table")
    McR cszbd(@RequestBody Map param) {
        String formInstanceId = String.valueOf(param.get("formInstanceId"));
        ArrayList<Object> objects = new ArrayList<>();
        HashMap<Object, Object> formData1 = new HashMap<>();
        formData1.put("textField_m8sjaagi", "中国工商银行");
        objects.add(formData1);
        HashMap<Object, Object> formData = new HashMap<>();
        formData.put("tableField_m8sjaagh", objects);
        Map query = new HashMap();
        query.put("userId", "275412081437800471");
        query.put("tableFieldIds", "tableField_m8sjaagh");
        query.put("formInstanceId", formInstanceId);
        query.put("appType", "APP_V25MK3XKODKB02UVTGSH");
        query.put("systemToken", "IQC66GC1L5TW5HKF6SX645RC4AXG2CFGQOMCMOQ4");
        query.put("updateFormDataJson", JSON.toJSONString(formData));
        DDR_New ddrNew = (DDR_New) UtilHttp.doPost("https://api.dingtalk.com/v2.0/yida/forms/updateSubTable", ddClient.initTokenHeader(), query, DDR_New.class);
        return McR.success(ddrNew);
    }

    @PostMapping("/updateBd")
    McR updateBd(@RequestBody Map param) {
        String formInstanceId = String.valueOf(param.get("formInstanceId"));
        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();
        Map<String, Object> formData = (Map<String, Object>) data.get("formData");
        List<Map> tableFieid = (List<Map>) formData.get("tableField_lrru2tnq");
        if (tableFieid != null) {
            for (Map<String, Object> tableItem : tableFieid) {
                String zq = (String) tableItem.get("textField_luh0k82j");
                tableItem.put("numberField_lrru2to2", "3020");

            }
        }
        return McR.success(tableFieid);
    }

    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);
    }


}

