package com.malk.ruisi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.malk.ruisi.service.QysApiService;
import com.malk.ruisi.service.QysService;
import com.malk.ruisi.service.dingshiqi;
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.service.dingtalk.DDClient_Contacts;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.malk.ruisi.constant.QysConstant.*;
import static jdk.nashorn.internal.objects.NativeError.printStackTrace;


@Service
@Slf4j
public class dingshiqiImpl implements dingshiqi {
    @Autowired
    private QysService qysService;
    @Autowired
    private QysServiceImpl qysServiceImpl;
    @Autowired
    private QysApiService qysApiService;
    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Override
    public JSONObject getYWFLid() throws Exception {
        Map<String, Object> data = new HashMap();
        //通过接口获取所有业务分类列表
        JSONObject ywfLid = qysApiService.sendGet(data, QYS_API_CATEGORIES, false);
        JSONArray ids = ywfLid.getJSONArray("categories");//得到所有业务分类数据
        if (ids != null && ids.size() > 0) {
            for (int i = 0; i < ids.size(); i++) {
                String scon = "";//签署配置
                //判断所需数据是否为空
                if (ids.getJSONObject(i).getString("name") != "" && ids.getJSONObject(i).getString("id") != ""
                        && ids.getJSONObject(i).getString("tenantName") != "" && ids.getJSONObject(i).getString("tenantId") != ""
                        && ids.getJSONObject(i).getString("config") != "") {
                    String name = ids.getJSONObject(i).getString("name");//业务分类名称
                    String id = ids.getJSONObject(i).getString("id");//业务分类id
                    String config = ids.getJSONObject(i).getString("config");
                    String tenantName = ids.getJSONObject(i).getString("tenantName");//公司名称
                    String tenantID = ids.getJSONObject(i).getString("tenantId");//公司id
                    String sc = "textField_lvkbxugq, textField_lvkbxugr, textField_lvyy8a3l";
                    String fd = "textField_lvkbxugq, textField_lvkbxugr, textField_lvyy8a3l, textField_lvyy8a3m, textareaField_lw1py1td";
                    //把配置数据转换成json
                    Gson gson = new Gson();
                    JsonObject jsonObject = gson.fromJson(config, JsonObject.class);
                    JsonArray signatories = jsonObject.getAsJsonArray("signatories");
                    if (signatories == null || signatories.size() == 0) {
                        signatories = new JsonArray();
                    }
                    //封装所需配置数据为列表
                    List<Map<String, Object>> signatoriesData = new ArrayList<>();
                    for (JsonElement signatory : signatories) {
                        JsonObject signatoryObj = signatory.getAsJsonObject();
                        String tenantType = signatoryObj.has("tenantType") ? signatoryObj.get("tenantType").getAsString() : "COMPANY";
                        int serialNo = signatoryObj.get("serialNo").getAsInt();
                        List<Map<String, Object>> actionData = new ArrayList<>();
                        JsonArray actions = signatoryObj.getAsJsonArray("actions");
                        for (JsonElement action : actions) {
                            JsonObject actionObj = action.getAsJsonObject();
                            String type = actionObj.get("type").getAsString();
                            String name1 = actionObj.get("name").getAsString();
                            int actionSerialNo = actionObj.get("serialNo").getAsInt();
                            Map<String, Object> actionMap = new HashMap<>();
                            actionMap.put("type", type);
                            actionMap.put("name", name1);
                            actionMap.put("serialNo", actionSerialNo);
                            actionData.add(actionMap);
                        }
                        Map<String, Object> signatoryMap = new HashMap<>();
                        if (tenantType != null) {
                            signatoryMap.put("tenantType", tenantType);
                        }
                        signatoryMap.put("serialNo", serialNo);
                        signatoryMap.put("actions", actionData);
                        signatoriesData.add(signatoryMap);
                    }
                    //把配置数据转换成json
                    Gson gson1 = new Gson();
                    scon = gson1.toJson(signatoriesData);
                    //把数据插入宜搭基础表单中
                    String tquid = ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-417576F4EE9F4AA1B2395BCD93B7A08C8ASN")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, id, tenantName)))
                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd, name, id, tenantName, tenantID, scon)))
                            .build(), YDConf.FORM_OPERATION.upsert).toString();
                    System.out.println("tquid:" + tquid);
                }
            }

        }
        return null;
    }

    @Override
    public JSONObject getYWFLid1() throws Exception {
        Map<String, Object> data = new HashMap();
        data.put("category", "PHYSICS");
        JSONObject qysid = qysApiService.sendGet(data, QYS_API_SEALLIST, false);
        JSONArray result = qysid.getJSONArray("result");//得到物理印章所有数据
        if (result != null && result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
                JSONObject sealData = result.getJSONObject(i);
                String charger = sealData.getString("charger"); // 印章负责人
                String name = sealData.getString("name"); // 公司名称
                String id = sealData.getString("id"); // 公司id
                JSONArray seals = sealData.getJSONArray("seals"); // 公司id
                String sc = "textField_lw6aecvd, textField_lw6aecvg, textField_lw6aecve, textField_lw6aecvh";
                String fd = "employeeField_lwr509pq, textField_lw6aecvd, textField_lw6aecvg, textField_lw6aecve, textField_lw6aecvh, textField_lwywohh0";
                String fd1 = "textField_lw6aecvd, textField_lw6aecvg, textField_lw6aecve, textField_lw6aecvh";

                // 如果 seals 为空,则设置 id、name、category 为空字符串
                if (seals != null && seals.size() > 0) {
                    for (int i1 = 0; i1 < seals.size(); i1++) {
                        JSONObject seal = seals.getJSONObject(i1);
                        String sealId = seal.getString("id"); // 印章id
                        String sealName = seal.getString("name"); // 印章名称
//                        String sealCategory = seal.getString("category"); // 印章类别
//                        if (sealCategory.equals("PHYSICS")) {
//                            sealCategory = "物理";
//                        }
                        Map<String, Object> data5 = new HashMap();
                        data5.put("sealId", sealId);
                        JSONObject detail = qysApiService.sendGet(data5, QYS_API_DETAIL, false);
                        JSONObject seal3 = detail.getJSONObject("seal");//得到电子印章所有数据
                        JSONArray users = seal3.getJSONArray("users");//得到电子印章所有数据

                        if (users != null && users.size() > 0) {
                            List<String> usersList = new ArrayList<>();
                            for (int k = 0; k < users.size(); k++) {
                                JSONObject usersData = users.getJSONObject(k);

                                String mobile = usersData.getString("mobile");
                                try {
                                    Map userInfoByMobile = ddClient_contacts.getUserInfoByMobile(ddClient.getAccessToken(), mobile);
                                    String userid = UtilMap.getString(userInfoByMobile, "userid");
                                    if (userid != null) {
                                        log.info("userInfoByMobile:{}", userInfoByMobile.get("userid"));
                                        usersList.add(userid);
                                    } else {
                                        usersList.add(null);
                                    }
                                } catch (McException e) {
                                    if (e.getCode() == "60121") {
                                        // 处理用户不存在的特定情况，如记录日志、添加特定消息等
                                        log.warn("用户不存在: 手机号={}", mobile);
                                    } else {
                                        // 其他错误处理
                                        log.error("获取用户信息时发生错误", e);
                                    }
                                }
                                System.out.println("物理印章使用人----------------" + mobile);
                                if (usersList != null){
                                    ydClient.operateData(YDParam.builder()
                                            .formUuid("FORM-7ACCB70D96FA4187BD2042243641E54CD6VH")
                                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId, sealName, id)))
                                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd, usersList, name, sealId, sealName, id, mobile)))
                                            .build(), YDConf.FORM_OPERATION.upsert);
                                }else{
                                    ydClient.operateData(YDParam.builder()
                                            .formUuid("FORM-7ACCB70D96FA4187BD2042243641E54CD6VH")
                                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId, sealName, id)))
                                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd1, name, sealId, sealName, id)))
                                            .build(), YDConf.FORM_OPERATION.upsert);
                                }

                            }
                        }

                    }
                } else {
                    String sealId = ""; // 印章id
                    String sealName = ""; // 印章名称
                    String sealCategory = ""; // 印章类别

                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-7ACCB70D96FA4187BD2042243641E54CD6VH")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId, sealName, id)))
                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd1,  name, sealId, sealName, id)))
                            .build(), YDConf.FORM_OPERATION.upsert).toString();
                }
            }
        }
        return null;
    }

    @Override
    public JSONObject getYWFLid2() throws Exception {
        Map<String, Object> data = new HashMap();
        data.put("category", "ELECTRONIC");
        JSONObject qysid = qysApiService.sendGet(data, QYS_API_SEALLIST, false);
        JSONArray result = qysid.getJSONArray("result");//得到电子印章所有数据
        if (result != null && result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
                JSONObject sealData = result.getJSONObject(i);
                String charger = sealData.getString("charger"); // 印章负责人
                String name = sealData.getString("name"); // 公司名称
                String id = sealData.getString("id"); // 公司id
                JSONArray seals = sealData.getJSONArray("seals"); // 印章id
                String sc = "textField_lu0k70cf, textField_lw5pfnr9";
                String fd = "employeeField_lwqbilgc, textField_lu0k70cf, textField_lw5pfnr9, textField_lu0k70cg, textField_lw5qtyzw, textField_lwywvrx9";
                String fd1 = "textField_lu0k70cf, textField_lw5pfnr9, textField_lu0k70cg, textField_lw5qtyzw";
                // 如果 seals 为空,则设置 id、name、category 为空字符串
                if (seals != null && seals.size() > 0) {
                    for (int i1 = 0; i1 < seals.size(); i1++) {
                        JSONObject seal = seals.getJSONObject(i1);
                        String sealId = seal.getString("id"); // 印章id
                        String sealName = seal.getString("name"); // 印章名称
//                        String sealCategory = seal.getString("category"); // 印章类别
//                        if (sealCategory.equals("ELECTRONIC")) {
//                            sealCategory = "电子";
//                        }
                        Map<String, Object> data5 = new HashMap();
                        data5.put("sealId", sealId);
                        JSONObject detail = qysApiService.sendGet(data5, QYS_API_DETAIL, false);
                        JSONObject seal3 = detail.getJSONObject("seal");//得到电子印章所有数据
                        JSONArray users = seal3.getJSONArray("users");//得到电子印章所有数据

                        if (users != null && users.size() > 0) {
                            List<String> usersList = new ArrayList<>();
                            for (int k = 0; k < users.size(); k++) {
                                JSONObject usersData = users.getJSONObject(k);
//                                String name3 = usersData.getString("name");
                                String mobile = usersData.getString("mobile");
                                try {
                                    Map userInfoByMobile = ddClient_contacts.getUserInfoByMobile(ddClient.getAccessToken(), mobile);
                                    String userid = UtilMap.getString(userInfoByMobile, "userid");
                                    if (userid != null) {
                                        log.info("userInfoByMobile:{}", userInfoByMobile.get("userid"));
                                        usersList.add(userid);
                                    } else {
                                        usersList.add(null);
                                    }
                                } catch (McException e) {
                                    if (e.getCode() == "60121") {
                                        // 处理用户不存在的特定情况，如记录日志、添加特定消息等
                                        log.warn("用户不存在: 手机号={}", mobile);
                                    } else {
                                        // 其他错误处理
                                        log.error("获取用户信息时发生错误", e);
                                    }
                                }
                                System.out.println("印章使用人----------------" + mobile);
                                if (usersList != null) {
                                    ydClient.operateData(YDParam.builder()
                                            .formUuid("FORM-6D5B2C469B45456F9287C3575BFF92C7KUF6")
                                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId)))
                                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd, usersList, name, sealId, sealName, id, mobile)))
                                            .build(), YDConf.FORM_OPERATION.upsert);
                                } else {
                                    ydClient.operateData(YDParam.builder()
                                            .formUuid("FORM-6D5B2C469B45456F9287C3575BFF92C7KUF6")
                                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId)))
                                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd1, name, sealId, sealName, id)))
                                            .build(), YDConf.FORM_OPERATION.upsert);
                                }
                            }
                        }
                    }
                } else {
                    String sealId = ""; // 印章id
                    String sealName = ""; // 印章名称
                    String sealCategory = ""; // 印章类别

                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-6D5B2C469B45456F9287C3575BFF92C7KUF6")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map(sc, name, sealId)))
                            .formDataJson(JSONObject.toJSONString(UtilMap.map(fd1, name, sealId, sealName, id)))
                            .build(), YDConf.FORM_OPERATION.upsert).toString();
                }
            }
        }
        return null;
    }

    @Override
    public void syncDelete() {
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formUuid("FORM-7ACCB70D96FA4187BD2042243641E54CD6VH")
                .build(), YDConf.FORM_QUERY.retrieve_search_form_id);

        System.out.println(ddrNew.getTotalCount());

        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-7ACCB70D96FA4187BD2042243641E54CD6VH")
                .asynchronousExecution(true)
                .formInstanceIdList((List<String>) ddrNew.getData())
                .build(), YDConf.FORM_OPERATION.delete_batch);

    }
}
