package com.malk.cloudpure.controller;

import com.alibaba.fastjson.JSON;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping("test")
public class TSController {

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private YDService ydService;

    @Autowired
    private YDClient ydClient;

    @SneakyThrows
    @GetMapping("test")
    McR test() {

        //updatePosition("2445432306884832");
//        tianhua618();

//        updateVersion("e6884e9b-fb5a-4e8b-822f-7cfb8ee4bfea");
//        lanyun621();

//        lanyun630();

        _lanyun0724();

        return McR.success();
    }

    // 蓝云 [采购付款更新]
    private void _lanyun0724() {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-BF9735C77D224D01B69BC1C517A89755OV4M")
                .build());
        log.info("项目点数据, {}", dataList.size());
        dataList.forEach(formData -> {
            updateVersion(UtilMap.getString(formData, "instanceId"));
        });
    }

    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @PostMapping("tmp")
    public void tmp() {
//        String token = ddClient.getAccessToken("dingfwn4kpmb4g3dy4fj", "OwdkUc9nvBivpwsg0AiaEcyWLtZ678fskqBJwP7B5CQNrycIoyKuWslFTCOOaZG4");

//        ddClient_workflow.getProcessInstanceId(token, "QVxpoRomSfOqOeuUqzwXvQ04851720676197");
//        ddClient_workflow.executeRunningApprove(token, "QVxpoRomSfOqOeuUqzwXvQ04851720676197", "396511732", "87755078200", "agree", "", null);

    }

    // 蓝云
    private void updateVersion(String formInstId) {
        ydClient.operateData(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formInstanceId(formInstId)
                .updateFormDataJson(JSON.toJSONString(new HashMap<>()))
                .useLatestVersion(true)
                .build(), YDConf.FORM_OPERATION.update);

    }

    /// 630 蓝云项目点数据更新
    private void lanyun630() {


        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-97BA6C6C8C50416A9E5854F2F4B5C3F3R4WC")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lrr3rg6h", "XM00363")))
                .build());
        log.info("项目点数据, {}", dataList.size());
        dataList.forEach(formData -> {
            List<Map> details = UtilMap.getList(formData, "tableField_lrru2tnq");
//            details = details.stream().filter(item -> UtilMap.isNotBlankString(item, "dateField_lrru2tnr")).collect(Collectors.toList());
            // 数据格式化
//            details.forEach(row -> {
//                row.put("textField_luh0k82j", UtilDateTime.format(new Date(UtilMap.getLong(row, "dateField_lrru2tnr")), "yyyy-MM"));
//            }
//            });
//            Collections.sort(details, Comparator.comparingLong(o -> UtilMap.getLong(o, "dateField_lrru2tnr")));

            // 查找当月数据
            LocalDateTime currentDate = UtilDateTime.firstDayOfLastMonth(LocalDateTime.now());
            Optional optional = details.stream().filter(item -> UtilDateTime.getLocalDateTimeTimeStamp(currentDate) == UtilMap.getLong(item, "dateField_lrru2tnr")).findAny();
            log.info("上个月数据, {}, {}", currentDate, optional);
            if (!optional.isPresent() || StringUtils.isNotBlank(UtilMap.getString((Map) optional.get(), "numberField_lrru2tnz"))) {
                return;
            }

            LocalDateTime lastMonthDate = UtilDateTime.firstDayOfLastMonth(currentDate);
            Map currentRow = (Map) optional.get();
            optional = details.stream().filter(item -> UtilDateTime.getLocalDateTimeTimeStamp(lastMonthDate) == UtilMap.getLong(item, "dateField_lrru2tnr")).findAny();
            log.info("上上月数据, {}, {}", lastMonthDate, optional);

            float price;
            if (!optional.isPresent() || StringUtils.isBlank(UtilMap.getString((Map) optional.get(), "numberField_lrru2tnz"))) {
                price = UtilMap.getFloat(currentRow, "numberField_lrru2tns");
                currentRow.put("numberField_lrru2tnz", price); // 取本月收入定额
            } else {
                price = UtilMap.getFloat((Map) optional.get(), "numberField_lrru2tnz");
                currentRow.put("numberField_lrru2tnz", price); // 取上月收入预估
            }
            price += UtilMap.getFloat(formData, "numberField_lutjev0u");
            log.info("price, {}", price);
            // 合计初始化
//            price = details.stream().map(item -> UtilMap.getFloat(item, "numberField_lrru2tnz")).collect(Collectors.toList()).stream().reduce(0f, (acc, cur) -> acc + cur);
            ydClient.operateData(YDParam.builder()
                    .appType("APP_ERBDTFS82HOVBPL3NFH0")
                    .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                    .formInstanceId(UtilMap.getString(formData, "formInstanceId"))
//                    .useLatestVersion(true)
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("tableField_lrru2tnq, numberField_lutjev0u", details, price)))
                    .build(), YDConf.FORM_OPERATION.update);
        });
    }

    /// 6.21 蓝云数据版本问题
    private void lanyun621() {

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-5A6C8B23015F44949F66543E5E684F5EF3SK")
                .build());
        dataList.forEach(item -> {
            updatePosition(UtilMap.getString(item, "textField_lxjl5kwm"));
            ydClient.operateData(YDParam.builder()
                    .appType("APP_ERBDTFS82HOVBPL3NFH0")
                    .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
                    .useLatestVersion(true)
                    .updateFormDataJson(JSON.toJSONString(new HashMap<>()))
                    .build(), YDConf.FORM_OPERATION.update);
        });
    }

    /// 6.18 苏州天华更新部门职位
    private void tianhua618() {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_GW0W0VPQ0FR53R258J6G")
                .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                .formUuid("FORM-120A6337A2034F4FB0E44949DB05C3BE5FTC")
                .build());
        dataList.forEach(item -> {
            updatePosition(UtilMap.getString(item, "textField_lxjl5kwm"));
            ydClient.operateData(YDParam.builder()
                    .appType("APP_GW0W0VPQ0FR53R258J6G")
                    .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
                    .build(), YDConf.FORM_OPERATION.delete);
        });
    }

    private void updatePosition(String userId) {
        String token = ddClient.getAccessToken("ding4h80bxhmsujcmkad", "gO9i1LvoExN3ozhKbJ6ZzZhHgvAXEfUfwJMJvYyaP0H5zt5jk2zhiWQLXQMCz9yd");
        Map userInfo = null;
        try {
            userInfo = ddClient_contacts.getUserInfoById(token, userId);
        } catch (McException e) {
            log.error(e.getMessage(), e);
            return;
        }
        String title = UtilMap.getString(userInfo, "title");
        if (StringUtils.isBlank(title)) {
            log.info("更新异常, {}, {}", userInfo);
            return;
        }
        List<Long> deptIds = (List<Long>) UtilMap.getList(userInfo, "dept_id_list").stream().map(item -> Long.parseLong(String.valueOf(item))).collect(Collectors.toList());
        List<Map> titles = deptIds.stream().map(dept_id -> UtilMap.map("dept_id, title", dept_id, title)).collect(Collectors.toList());
        ddClient_contacts.updateUser_dingTalk(token, userId, deptIds, UtilMap.map("dept_title_list", titles));
    }

}


