package jnpf.cultivate.controller.web.learn;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.config.ConfigValueUtil;
import jnpf.cultivate.FtbCultivateLearnTaskListApi;
import jnpf.cultivate.event.impl.certificate.JnpfApplicationEventCertificateService;
import jnpf.cultivate.service.CultivateIdentifyApplyService;
import jnpf.cultivate.service.FtbCultivateLearnTaskListService;
import jnpf.cultivate.utils.CultivateLearnUtils;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.cultivate.event.dto.certificate.CertificateEventDTO;
import jnpf.model.cultivate.req.learn.QueryLearnTaskListReq;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskInfoListVO;
import jnpf.model.cultivate.vo.learn.FtbExportCultivateLearnTaskInfoListVO;
import jnpf.model.cultivate.vo.learn.WebLearnTaskDto;
import jnpf.util.FtbUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import jnpf.util.excel.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * web学习任务列表模块
 *
 * @Author: xuguilin
 * @create: 2024/9/9:11:20
 */
@RestController
@Slf4j
@RequestMapping("/web/learnTaskList/")
public class FtbCultivateLearnTaskListController  implements FtbCultivateLearnTaskListApi {

    @Autowired
    private FtbCultivateLearnTaskListService taskListService;


    @Autowired
    private CultivateLearnUtils cultivateLearnUtils;

    @Autowired
    private CultivateIdentifyApplyService cultivateIdentifyApplyService;

    @Autowired
    JnpfApplicationEventCertificateService jnpfApplicationEventCertificateService;


    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
     * 查询任务列表
     *
     * @param req
     * @return {@link ActionResult}<{@link FtbCultivateLearnTaskInfoListVO}>
     */
    @GetMapping("/queryList")
    public ActionResult<PageListVO<FtbCultivateLearnTaskInfoListVO>> pageLists(@Validated QueryLearnTaskListReq req) {
        PageInfo<FtbCultivateLearnTaskInfoListVO> pageVo = taskListService.getWebPageList(req);
        return ActionResult.page(pageVo.getList(), FtbUtil.getPagination(pageVo));
    }

    /**
     * 导出搜索的任务列表
     *
     * @param req
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportSearchTaskList")
    public void exportSearchTaskList(@Validated QueryLearnTaskListReq req, HttpServletResponse response) throws IOException {
        req.setPageSize(-1);
        req.setCurrentPage(1);
        PageInfo<FtbCultivateLearnTaskInfoListVO> pageVo = taskListService.getWebPageList(req);
        List<FtbCultivateLearnTaskInfoListVO> list = pageVo.getList();
        List<FtbExportCultivateLearnTaskInfoListVO> exportList = CultivateLearnUtils.convertFtbExportCultivateLearnTaskInfoListVO(list);
        EasyExcelUtils.exportExcel(response, "任务列表-" + DateUtil.format(new Date(), "yyyyMMddHHmmss"), exportList, FtbExportCultivateLearnTaskInfoListVO.class);
    }


    /**
     * 统计任务数量
     *
     * @return
     */
    @GetMapping("/countTaskNumber")
    public ActionResult<WebLearnTaskDto> countTaskNumber() {
        return ActionResult.success(taskListService.countTaskNumber());
    }

    /**
     * 入职加入任务
     *
     * @return
     */
    @GetMapping("/entryCompany/{userId}")
    public void entryCompany(@PathVariable("userId") String userId) {
        cultivateLearnUtils.addNewPersonToTask(List.of(userId), UserProvider.getUser().getTenantId());
    }



    /**
     * 定时提醒任务（每天定点）
     *
     * @return
     */
    @GetMapping("/timingTaskLearningAlert/{tenantId}")
    public void timingTaskLearningAlert(@PathVariable("tenantId") String tenantId) {
        cultivateLearnUtils.timingTaskLearningAlert(tenantId);
    }


    /**
     * 定时加入任务
     *
     * @return
     */
    @GetMapping("/timing/timingAddNewPersonToTaskNew/{tenantId}")
    @NoDataSourceBind
    @Override
    public void timingAddNewPersonToTaskNew(@PathVariable("tenantId") String tenantId) {
        log.error("timingAddNewPersonToTaskNew{}",tenantId);
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
        cultivateLearnUtils.timingAddNewPersonToTask(tenantId);
    }


    /**
     * 定时提醒任务（每天定点）
     *
     * @return
     */
    @GetMapping("/timing/timingTaskLearningAlertNew/{tenantId}")
    @NoDataSourceBind
    @Override
    public void timingTaskLearningAlertNew(@PathVariable("tenantId") String tenantId) {
        log.error("timingTaskLearningAlertNew{}",tenantId);
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
        cultivateLearnUtils.timingTaskLearningAlert(tenantId);
    }



    /**
     * 触发考试完成（完成任务）
     *
     * @return
     */
    @GetMapping("/timingTaskExam/{tastkId}/{userId}")
    public void timingTaskExam(@PathVariable("tastkId") String tastkId, @PathVariable("userId") String userId) {
        cultivateIdentifyApplyService.turnOnVisibilityWithTaskId(tastkId, userId,0);

    }


    /**
     * 测试接口(触发鉴定接口)
     *
     * @return
     */
    @GetMapping("/jnpfApplicationEventCertificateService")
    public void timingTaskExam() {
//        CertificateEventDTO(postId=null, userId=583985483894499333, courseId=null, taskId=1845023199187787777, source=1, issuanceType=2)
        CertificateEventDTO dto =CertificateEventDTO.builder().userId("583985483894499333").taskId("1848549705067352066").source(2).issuanceType(2).build();
        jnpfApplicationEventCertificateService.handlerCourseEvent(dto);

    }

}
