package jnpf.cultivate.mock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.ImmutableMap;
import jnpf.base.ActionResult;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskAssignmentMapper;
import jnpf.cultivate.service.CultivateIdentifyApplyService;
import jnpf.cultivate.service.FtbCultivateCertificateUserService;
import jnpf.cultivate.service.FtbCultivateExamService;
import jnpf.cultivate.service.FtbCultivateOfflineTrainService;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.cultivate.dto.certificate.FtbCertificateUserForm;
import jnpf.model.cultivate.dto.offline.FtbCultivateOfflineTrainDTO;
import jnpf.model.cultivate.po.certificate.CertificateUserPagination;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.permission.UserApi;
import jnpf.permission.V2UserApi;
import jnpf.permission.eum.v2.OrganizeCategoryEnums;
import jnpf.permission.vo.v2.user.UserBoundInfoVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.AuthUtil;
import jnpf.util.Constants;
import jnpf.util.NoDataSourceBind;
import jnpf.utils.FeignHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 培训模拟数据
 *
 * @author wangchunxiang
 * @date 2025/09/02
 */
@RestController
@Slf4j
@RequestMapping("/cultivate-mock")
public class CultivateMockController {


    @Resource
    FtbCultivateOfflineTrainService ftbCultivateOfflineTrainService;

    @Resource
    private FtbCultivateCertificateUserService ftbCultivateCertificateUserService;

    @Autowired
    UserApi userApi;

    @Autowired
    FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;

    @Resource
    CultivateIdentifyApplyService applyService;

    @Resource
    FtbCultivateExamService examService;

    @Resource
    V2UserApi v2UserApi;

    /**
     * 线下培训mock
     */
    private final static  String offlineTrainingDataMock="{\n" +
            "    \"id\": null,\n" +
            "    \"name\": \"线下全员培训\",\n" +
            "    \"userId\": \"349057407209541\",\n" +
            "    \"userName\": \"管理员\",\n" +
            "    \"headUserId\": \"712307395245893253\",\n" +
            "    \"userIds\": [\n" +
            "        \"732526335339233477\"\n" +
            "    ],\n" +
            "    \"offlinePlace\": \"公司办公室\",\n" +
            "    \"trainStartTime\": 1756875600000,\n" +
            "    \"trainEndTime\": 1756980000000,\n" +
            "    \"timeList\": [\n" +
            "\n" +
            "    ],\n" +
            "    \"trainContent\": \"线下全员培训\",\n" +
            "    \"courseIds\": [\n" +
            "\n" +
            "    ],\n" +
            "    \"files\": [\n" +
            "\n" +
            "    ],\n" +
            "    \"courseInfo\": [\n" +
            "\n" +
            "    ],\n" +
            "    \"signWay\": 0\n" +
            "}";
    /**
     * 证书颁发mock
     *
     */
    private final static  String certificateDataMock="{\"certificateId\":\"1945677502821244930\",\"userInfoFormList\":[{\"userId\":\"349057407209541\",\"userName\":\"管理员\",\"positionId\":\"\",\"organizeId\":\"\",\"reason\":\"经岗位学习考试合格颁发\"}]}";
    /**
     * mock数据培训统一接口
     */
    @GetMapping("/mock")
    @NoDataSourceBind
    public void mock(@RequestParam String tenantId) {
        log.info("开始模拟数据");
         String token = AuthUtil.loginTempUser("349057407209541", tenantId);
         Map<String, String> headers = ImmutableMap.of(Constants.AUTHORIZATION.toLowerCase(), token);
        ActionResult<List<UserBoundVO>> userInfoBatch = v2UserApi.getAllUserInfoBatch(List.of(), tenantId);
        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantId);
            userInfoBatch.getData().stream().filter(a->!OrganizeCategoryEnums.TEAM.getCode().equals(a.getOrganizeCategory()))
                .forEach(usersBoundData -> {
                    String userId = usersBoundData.getId();
                    // 证书颁发
                    FtbCertificateUserForm certificateUserForm = JSONObject.parseObject(certificateDataMock, FtbCertificateUserForm.class);
                    List<FtbCertificateUserForm.UserInfoForm> userInfoFormList = certificateUserForm.getUserInfoFormList();
                    FtbCertificateUserForm.UserInfoForm userInfoForm = userInfoFormList.get(0);
                    userInfoForm.setUserName(usersBoundData.getUserName());
                    userInfoForm.setPositionId(usersBoundData.getPositionId());
                    userInfoForm.setOrganizeId(usersBoundData.getOrganizeId());
                    userInfoForm.setUserId(userId);
                    CertificateUserPagination certificateUserPagination = new CertificateUserPagination();
                    certificateUserPagination.setCertificateId(certificateUserForm.getCertificateId());
                    certificateUserPagination.setUserId(userId);
                    List<FtbCertificateUserEntity> list = ftbCultivateCertificateUserService.getList(certificateUserPagination);
                    List<FtbCertificateUserEntity> collect = list.stream().filter(vo -> vo.getStatus() == 0).collect(Collectors.toList());
                    if (CollUtil.isEmpty(collect)){
                        ftbCultivateCertificateUserService.create(certificateUserForm);
                    }
                    // 线下培训
                    FtbCultivateOfflineTrainDTO offlineTrainDTO = JSONObject.parseObject(offlineTrainingDataMock, FtbCultivateOfflineTrainDTO.class);
                    offlineTrainDTO.setTrainStartTime(getNextDayTimestamp(14));
                    offlineTrainDTO.setTrainEndTime(getNextDayTimestamp(16));
                    offlineTrainDTO.setHeadUserId(userId);
                    offlineTrainDTO.setUserIds(List.of(userId));
                    ftbCultivateOfflineTrainService.add(offlineTrainDTO);
                    // 培训任务
                    FtbCultivateLearnTaskAssignment taskAssignment = new FtbCultivateLearnTaskAssignment();
                    // 已有任务
                    taskAssignment.setTaskId("1950031757292150786");
                    taskAssignment.setUserId(userId);
                    taskAssignment.setStudyStats(0);
                    ftbCultivateLearnTaskAssignmentMapper.insert(taskAssignment);
                    // 实操鉴定
                    CultivateMockUtils.mockPracticalAppraisal(userId, usersBoundData, applyService);
                    // 自定义考试
                    CultivateMockUtils.mockCustomExamination(userId, usersBoundData, examService);
                });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            FeignHolder.clear();
        }
        log.info("模拟数据结束");
    }
    public static Date getNextDayTimestamp(int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1); // 加一天
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

}
