
package com.jeelowcode.module.biz.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.jeelowcode.core.framework.controller.BaseController;
import com.jeelowcode.core.framework.service.IFormService;
import com.jeelowcode.framework.exception.JeeLowCodeException;
import com.jeelowcode.framework.global.JeeLowCodeBaseConstant;
import com.jeelowcode.framework.tenant.annotation.JeeLowCodeTenantIgnore;
import com.jeelowcode.framework.utils.adapter.IJeeLowCodeAdapter;
import com.jeelowcode.framework.utils.model.JeeLowCodeUser;
import com.jeelowcode.framework.utils.model.ResultDataModel;
import com.jeelowcode.framework.utils.tool.CollectionUtil;
import com.jeelowcode.module.biz.service.IExamPlanService;
import com.jeelowcode.module.biz.service.IWorkItemService;
import com.jeelowcode.tool.framework.common.pojo.CommonResult;
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.*;
import java.util.stream.Collectors;

import static com.jeelowcode.tool.framework.common.pojo.CommonResult.success;

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

    @Autowired
    private IWorkItemService iWorkItemService;

    private final IJeeLowCodeAdapter jeeLowCodeAdapter;

    @Autowired
    private IFormService dbFormService;

    @GetMapping({"/addResult"})
    @ApiOperationSupport(order = 1)
    @Operation(summary = "下发考试记录数据")
    public CommonResult<String> savePlanIssus(String tableId, String ids, String userIds) {
        String[] idArr = ids.split(",");
        String[] userIdArr = userIds.split(",");
        if (Objects.isNull(idArr) || idArr.length == 0 || Objects.isNull(userIdArr) || userIdArr.length == 0) {
            throw new JeeLowCodeException("缺少必要参数");
        }

        String tableName="lc_item_result";
        Long dbFormId = dbFormService.getDbFormIdByTableName(tableName);
        List<Long> userIdList = Arrays.stream(userIdArr).map(Long::parseLong).collect(Collectors.toList());
        IPage<JeeLowCodeUser> userPage = (IPage<JeeLowCodeUser>) jeeLowCodeAdapter.getUserPageByUserIds(1, 10000, userIdList);

        if (CollectionUtil.isNotEmpty(userPage.getRecords())) {
            for (int i = 0; i < idArr.length; i++) {
                ResultDataModel resultDataModel = super.getDataDetail(Long.parseLong(tableId), Long.valueOf(idArr[i]), new HashMap<String, Object>());
                if (CollectionUtil.isNotEmpty(resultDataModel.getRecords())) {
                    if (resultDataModel.getRecords().get(0).containsKey("jeelowcode_subtable_data")) {
                        HashMap<String, Object> details = (HashMap<String, Object>) resultDataModel.getRecords().get(0).get("jeelowcode_subtable_data");
                        if (details.containsKey("lc_work_item_issus")) {
                            List<HashMap<String, Object>> detail = (List<HashMap<String, Object>>) details.get("lc_work_item_issus");

                            List<JSONObject> tasks = new ArrayList<JSONObject>();
                            if(Objects.isNull(detail)) {
                                detail = new ArrayList<HashMap<String, Object>>();
                            }
                            for (JeeLowCodeUser dbuser : userPage.getRecords()) {
                                HashMap<String, Object> user = CollectionUtil.isEmpty(detail) ? null : detail.stream().filter(t -> t.containsKey("chargeId") && t.get("chargeId").toString().equals(dbuser.getUserId())).findFirst().orElse(null);
                                if (Objects.isNull(user)) {
                                    HashMap<String, Object> newUser = new HashMap<>();
                                    newUser.put("chargeId", dbuser.getUserId());
                                    newUser.put("chargeName", dbuser.getNickName());
                                    newUser.put("deptId", dbuser.getDeptId());
                                    newUser.put("deptName", dbuser.getDeptName());
                                    newUser.put("workItemId", Long.valueOf(idArr[i]));
                                    detail.add(newUser);

                                    // 组装任务
                                    //查询待分发单据 workItemId 从 lc_work_item 根据Id查询数据
                                    Map<String, Object>  examPlan = iWorkItemService.getWorkItemById(Long.valueOf(idArr[i]));

                                    HashMap<String, Object> newRecord = new HashMap<>();

                                    newRecord.put("chargeId", dbuser.getUserId());
                                    newRecord.put("chargeName", dbuser.getNickName());
                                    newRecord.put("deptName", dbuser.getDeptName());
                                    newRecord.put("deptId", dbuser.getDeptId());

                                    newRecord.put("eDate", examPlan.get("edate"));
                                    newRecord.put("resultStatus", 2);
                                    newRecord.put("sDate", examPlan.get("sdate"));
                                    newRecord.put("itemName", examPlan.get("itemname"));
                                    newRecord.put("itemContext", examPlan.get("itemcontext"));
                                    newRecord.put("workItemId", examPlan.get("id"));

                                    newRecord.put("billNo", "SXJG" + System.currentTimeMillis());
                                    tasks.add(JSONUtil.parseObj(newRecord));
                                }
                            }
                            resultDataModel.getRecords().get(0).put("lc_work_item_issus", detail);
                            super.editJsonData(Long.valueOf(tableId), JSONUtil.parseObj(resultDataModel.getRecords().get(0)));

                            super.addJsonData(dbFormId, tasks);
                        }
                    }
                }
            }
        }
        return success("下发成功");
    }

}
