package com.ruoyi.web.controller.wgz.controller;


import com.ruoyi.common.bo.AnnexQueryBo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.domain.Annex;
import com.ruoyi.common.service.IAnnexService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.wgz.bo.res.WgzAppGetTestPaperRes;
import com.ruoyi.wgz.bo.res.WgzAppSubmitATestPaperRes;
import com.ruoyi.wgz.bo.rests.WgzAppGetTestPaperThree;
import com.ruoyi.wgz.bo.rests.WgzAppGetTestPaperTwo;
import com.ruoyi.wgz.bo.rests.WgzAutonymAnnex;
import com.ruoyi.wgz.bo.req.*;
import com.ruoyi.wgz.bo.res.WgzAppAttachmentAcquisitionRes;
import com.ruoyi.wgz.bo.res.WgzAppPersonalBasicInformationRes;
import com.ruoyi.wgz.domain.WgzQuestionsConfiguration;
import com.ruoyi.wgz.service.IWgzQuestionBankService;
import com.ruoyi.wgz.service.IWgzQuestionSaveService;
import com.ruoyi.wgz.service.IWgzQuestionsConfigurationService;
import com.ruoyi.wgz.service.IWgzUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * APP务工者Controller
 *
 * @author ruoyi
 * @date 2025-02-14
 */
@Api(value = "APP务工者接口", tags = {"APP务工者接口管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController

@RequestMapping("/wgz/app")
public class WgzAppController {

	private final IWgzUserService iWgzUserService;

	@Autowired
	private ISysDictTypeService dictTypeService;

	@Autowired
	private IAnnexService iAnnexService;

	@Autowired
	private IWgzQuestionBankService iWgzQuestionBankService;

	@Autowired
	private IWgzQuestionsConfigurationService iWgzQuestionsConfigurationService;

	@Autowired
	private IWgzQuestionSaveService iWgzQuestionSaveService;



	/**
	 * 【注册】务工者注册
	 */
	@ApiOperation("APP务工者注册")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:register')")
	@PostMapping("/wgzRegister")
	public AjaxResult<Boolean> userRegister(@Validated @RequestBody WgzAppUserRegisterReq bo) {
		return AjaxResult.success(iWgzUserService.userRegister(bo));
	}

	/**
	 * 【我的】【个人基本信息】修改用户头像
	 */
	@ApiOperation("APP务工者-修改用户头像")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userModifyingUserProfilePicture')")
	@PutMapping("/wgzUserModifyingUserProfilePicture")
	public AjaxResult<Boolean> userModifyingUserProfilePicture(@Validated @RequestBody WgzAppModifyingUserProfilePictureReq req) {
		return AjaxResult.success(iWgzUserService.userModifyingUserProfilePicture(req));
	}

	/**
	 * 【我的】【个人基本信息】查询基础用户信息（还未带附件信息）
	 */
	@ApiOperation("APP务工者-个人基本信息（还未带附件信息）")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userPersonalBasicInformation')")
	@GetMapping("/wgzUserPersonalBasicInformation")
	public AjaxResult<WgzAppPersonalBasicInformationRes> userPersonalBasicInformation(@Validated WgzAppPersonalBasicInformationReq req) {
		return AjaxResult.success(iWgzUserService.userPersonalBasicInformation(req));
	}

//	/**
//	 * 【我的】【实名认证】实名认证·删除附件
//	 */
//	@ApiOperation("APP务工者-实名认证·删除附件")
//	@PreAuthorize("@ss.hasPermi('wgzApp:user:userDeleteAttachment')")
//	@DeleteMapping("/WgzUserDeleteAttachment/{attachmentId}")
//	public AjaxResult<Boolean> userDeleteAttachment(@NotEmpty(message = "主键不能为空") @PathVariable Long attachmentId) {
//		return AjaxResult.success(iAnnexService.deleteByIds(attachmentId));
//	}

	/**
	 * 【我的】【实名认证】实名认证
	 */
	@ApiOperation("APP务工者-实名认证")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userRealNameAuthentication')")
	@PutMapping("/wgzUserRealNameAuthentication")
	public AjaxResult<Boolean> userRealNameAuthentication(@Validated @RequestBody WgzAppRealNameAuthenticationReq req) {
		return AjaxResult.success(iWgzUserService.userRealNameAuthentication(req));
	}


	/**
	 * 【我的】【岗前培训】获取安全教育考试试卷（随机获取）
	 */
	@ApiOperation("APP务工者-岗前培训·获取随机试卷")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userGetTestPaper')")
	@GetMapping("/WgzUserGetTestPaper")
	public AjaxResult<WgzAppGetTestPaperRes> userGetTestPaper() {
		//1、获取配置信息
		WgzQuestionsConfiguration configuration = iWgzQuestionsConfigurationService.appQueryLimitOne();
		if (configuration == null) {
			throw new RuntimeException("未查询到配置信息");
		}
		//2、随机获取数据，返回id和score
		Integer s = configuration.getSingleChoice();
		Integer m = configuration.getMultipleChoice();
		Integer e = configuration.getEstimate();
		List<WgzAppGetTestPaperThree> sEntity = iWgzQuestionBankService.appQueryList(1, s);
		List<WgzAppGetTestPaperThree> mEntity = iWgzQuestionBankService.appQueryList(2, m);
		List<WgzAppGetTestPaperThree> eEntity = iWgzQuestionBankService.appQueryList(3, e);
		//3、组装数据
		WgzAppGetTestPaperRes res = new WgzAppGetTestPaperRes();
		res.setSingleList(createQuestionSection("一、单选题", sEntity, configuration.getSingleScore(), s));
		res.setMultipleList(createQuestionSection("二、多选题", mEntity, configuration.getMultipleScore(), m));
		res.setEstimateList(createQuestionSection("三、判断题", eEntity, configuration.getEstimateScore(), e));
		//4、设置最大考试时间
		res.setMaximum(configuration.getAnswerTime());
		return AjaxResult.success(res);
	}

	/**
	 * 【我的】【岗前培训】提交用户的试卷（只保存最高分的试卷信息）
	 */
	@ApiOperation("APP务工者-岗前培训·提交试卷")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userSubmitATestPaper')")
	@PostMapping("/WgzUserSubmitATestPaper")
	public AjaxResult<WgzAppSubmitATestPaperRes> userSubmitATestPaper(@Validated @RequestBody WgzAppSubmitATestPaperReq req) {
		return AjaxResult.success(iWgzQuestionSaveService.userSubmitATestPaper(req));
	}

	/**
	 * 通用接口
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */

	/**
	 * 【我的】【实名认证】实名认证之务工者附件结构获取
	 		0-资格证书
	 * 【我的】【签协议】协议列表
	 		1-劳动合同
	 */
	@ApiOperation("APP务工者-通用·附件获取")
	@PreAuthorize("@ss.hasPermi('wgzApp:user:userAttachmentAcquisition')")
	@GetMapping("/wgzUserAttachmentAcquisition")
	public AjaxResult<WgzAppAttachmentAcquisitionRes> userAttachmentAcquisition(@Validated WgzAppAttachmentAcquisitionReq req) {
		//返回对象
		WgzAppAttachmentAcquisitionRes wgzAppAttachmentAcquisitionRes = new WgzAppAttachmentAcquisitionRes();
		List<WgzAutonymAnnex> resData = new ArrayList<>();
		//附件类型
		String userType = "wgz_attachment";
		//具体附件值
		String[] specifiedAttachment = req.getSpecifiedAttachment();
		//String[] SpecifiedAttachment = {"0"};

		//1、获取指定实名认证的附件结构返回
		List<SysDictData> data = dictTypeService.selectDictDataByType(userType);
		data.forEach(item -> {
			for (String val : specifiedAttachment) {
				String dictValue = item.getDictValue();
				if (dictValue.equals(val)) {
					//2、每个结构下有那些附件（附件可能有多个或一个）；查询附件表
					AnnexQueryBo annexQueryBo = new AnnexQueryBo();
					annexQueryBo.setUserId(req.getUserId());
					annexQueryBo.setUserType(userType);
					annexQueryBo.setAnnexType(val);
					List<Annex> annexes = iAnnexService.queryList(annexQueryBo);
					//3、具体附件结构
					WgzAutonymAnnex wgzAutonymAnnex = new WgzAutonymAnnex().
						setUserType(userType).
						setDictLabel(item.getDictLabel()).
						setDictValue(dictValue).setAnnex(annexes);
					resData.add(wgzAutonymAnnex);
				}
			}
		});
		return AjaxResult.success(wgzAppAttachmentAcquisitionRes.setWgzAutonymAnnex(resData));
	}

	/**
	 * 控制层业务
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */


	/**
	 * 创建题目板块
	 * @param topicPrefix 板块标题前缀
	 * @param questions 题目列表
	 * @param score 每题分数
	 * @param questionCount 题目数量
	 * @return 题目板块实体
	 */
	private WgzAppGetTestPaperTwo createQuestionSection(String topicPrefix, List<WgzAppGetTestPaperThree> questions, Float score, int questionCount) {
		WgzAppGetTestPaperTwo section = new WgzAppGetTestPaperTwo();
		section.setTopic(String.format("%s，共%d道题，每小题%.2f分，共计%.2f分", topicPrefix, questionCount, score, questionCount * score));
		questions.forEach(item -> item.setScore(score));
		section.setList(questions);
		return section;
	}
}
