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.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.dto.RequestDTO;
import com.jeelowcode.tool.framework.common.pojo.CommonResult;
import com.jeelowcode.tool.framework.common.util.http.HttpUtils;
import com.jeelowcode.tool.framework.common.util.json.JsonUtils;
import com.mchange.lang.LongUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.ArraysUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

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

@JeeLowCodeTenantIgnore
@Tag(name = "低代码框架 - 自定义教育培训接口")
@RestController
@AllArgsConstructor
@RequestMapping(JeeLowCodeBaseConstant.REQUEST_URL_START + "/training")
public class TrainingController extends BaseController {

    private final IJeeLowCodeAdapter jeeLowCodeAdapter;

    @GetMapping({"/sendDept"})
    @ApiOperationSupport(order = 5)
    @Operation(summary = "下发计划给使用部门")
    public CommonResult<String> sendDept(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("缺少必要参数");
        }

        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())) {
                    //  resultDataModel.getRecords().get(0).get("jeelowcode_subtable_data")  lc_training_plan_area
                    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_training_plan_area")) {
                            List<HashMap<String, Object>> detail = (List<HashMap<String, Object>>) details.get("lc_training_plan_area");
                            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("userId") && t.get("userId").toString().equals(dbuser.getUserId())).findFirst().orElse(null);
                                if (Objects.isNull(user)) {
                                    HashMap<String, Object> newUser = new HashMap<>();
                                    newUser.put("userId", dbuser.getUserId());
                                    newUser.put("userName", dbuser.getNickName());
                                    newUser.put("deptId", dbuser.getDeptId());
                                    newUser.put("deptName", dbuser.getDeptName());
                                    newUser.put("planId", Long.valueOf(idArr[i]));
                                    detail.add(newUser);
                                }
                            }
                            resultDataModel.getRecords().get(0).put("lc_training_plan_area", detail);
                            super.editJsonData(Long.valueOf(tableId), JSONUtil.parseObj(resultDataModel.getRecords().get(0)));
                        }
                    }
                }
            }
        }
        return success("下发成功");
    }
}
