package com.jeelowcode.module.biz.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.jeelowcode.core.framework.controller.BaseController;
import com.jeelowcode.core.framework.service.IFormService;
import com.jeelowcode.core.framework.utils.Func;
import com.jeelowcode.framework.global.JeeLowCodeBaseConstant;
import com.jeelowcode.framework.tenant.annotation.JeeLowCodeTenantIgnore;
import com.jeelowcode.framework.utils.model.ResultDataModel;
import com.jeelowcode.framework.utils.tool.CollectionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author LIFY
 * @create 2025-09-126
 * @dedescription:
 */
@JeeLowCodeTenantIgnore
@Tag(name = "低代码框架 - 个性化接口")
@RestController
@AllArgsConstructor
@RequestMapping(JeeLowCodeBaseConstant.REQUEST_URL_START +"/riskHazard")
public class RiskHazardController extends BaseController {

    @Autowired
    private IFormService formService;

    @GetMapping({"/syncData2RiskHazard"})
    @ApiOperationSupport(order = 1)
    @Operation(summary = "同步数据")
    public void SyncData2RiskHazard()
    {
        // 报表 code
        String reportCode="ali_risk_data";
        String syncTableName="lc_report_data_sync";
        String syncDetailTableName="lc_report_data_sync_detail";
        String riskTableName="lc_risk_hazard_manage";
        String campusTableName="campus_info";
        Long dbFormId = formService.getDbFormIdByTableName(syncTableName);
        Long detailFormId = formService.getDbFormIdByTableName(syncDetailTableName);
        Long riskFormId = formService.getDbFormIdByTableName(riskTableName);
        Long campusFormId = formService.getDbFormIdByTableName(campusTableName);

        // 根据 报表code获取所有未同步的主表List
        Map<String, Object> param = new HashMap<>();
        param.put("reportCode", reportCode);
        param.put("isSync", 0);
        ResultDataModel unSyncs = super.getDataPage(dbFormId, param);

        // 获取所有园区信息
        Map<String, Object> param3 = new HashMap<>();
        ResultDataModel allCampus = super.getDataPage(campusFormId, param3);

        if (CollectionUtil.isNotEmpty(unSyncs.getRecords()))
        {
            List<JSONObject> syncList = new ArrayList<>();
            List<JSONObject> syncDetailList = new ArrayList<>();
            for (Map<String, Object> unSync : unSyncs.getRecords()) {
                // 根据 同步表主表Id 获取所有未同步的明细表数据
                Map<String, Object> param2 = new HashMap<>();
                param2.put("syncId", unSync.get("id"));
                param2.put("isSync", 0);
                ResultDataModel unSyncDetails = super.getDataPage(detailFormId, param2);
                if(CollectionUtil.isNotEmpty(unSyncDetails.getRecords())) {
                    List<JSONObject> newRisks=new ArrayList<>();
                    for (Map<String, Object> data : unSyncDetails.getRecords()) {
                        Object result = data.get("resultData");
                        JSONObject sourceData = result instanceof JSONObject
                                ? (JSONObject) result
                                : JSONUtil.parseObj(String.valueOf(result));
                        // 生成 风险隐患表数据
                        HashMap<String, Object> newRisk = new HashMap<>();
                        newRisk.put("sync_Id", data.get("id"));
                        newRisk.put("source_Id", sourceData.get("sourceid"));
                        newRisk.put("billNo", sourceData.get("work_order_id"));
                        newRisk.put("source", 2); //来源 默认线上
                        newRisk.put("company_name", sourceData.get("company_name"));
                        newRisk.put("company_id", sourceData.get("company_id"));


                        newRisk.put("parkId", sourceData.get("campus_id"));
                        // 设置 园区名称
                        if(sourceData.containsKey("campus_id")) {
                            String campusId = Func.getMap2Str(sourceData, "campus_id");
                            // 根据name查找id
                            Map<String, Object> depMap = allCampus.getRecords().stream()
                                    .filter(t -> t.get("campus_id").toString()
                                            .equals(campusId)).findFirst().orElse(null);
                            if (Objects.nonNull(depMap)) {
                                newRisk.put("parkName", depMap.get("campus_name"));
                            }
                        }
                        //newRisk.put("check_area", sourceData.get("check_area"));
                        //newRisk.put("check_item", sourceData.get("check_item"));
                        newRisk.put("check_content", sourceData.get("item_name"));
                        newRisk.put("check_date", sourceData.get("creator_time"));
                        newRisk.put("check_people", sourceData.get("creator_name"));
                        newRisk.put("check_problem", sourceData.get("question_name"));
                        newRisk.put("corrective_action", sourceData.get("operate_content"));
                        newRisk.put("corrective_charge_people", sourceData.get("person_name"));
                        newRisk.put("risk_level", sourceData.get("level_name"));
                        newRisk.put("corrective_period", sourceData.get("confirm_time"));
                        newRisk.put("corrective_confirm_people", sourceData.get("confirm_person_name"));
                        newRisk.put("remarks", sourceData.get("remark"));

                        newRisks.add(JSONUtil.parseObj(newRisk));
                        // 更新明细表为已同步
                        data.put("isSync", 1);
                        syncDetailList.add(JSONUtil.parseObj(data));
                    }
                    // 插入新的 风险隐患数据
                    super.addJsonData(riskFormId,newRisks);
                }
                // 更新主表为已同步
                unSync.put("isSync", 1);
                syncList.add(JSONUtil.parseObj(unSync));

                // 更新同步数据表和同步数据明细表
                super.editJsonData(detailFormId, syncDetailList);
            }
            // 更新同步数据表和同步数据明细表
            super.editJsonData(dbFormId, syncList);
        }
    }
}
