package com.zhongzheng.controller.user;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhongzheng.common.core.domain.model.LoginUser;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.bank.vo.QuestionImport;
import com.zhongzheng.modules.base.vo.UserProfileExportGaiVo;
import com.zhongzheng.modules.exam.bo.ExamApplyGoodsQueryBo;
import com.zhongzheng.modules.exam.service.IExamApplyGoodsService;
import com.zhongzheng.modules.exam.vo.ExamApplyGoodsVo;
import com.zhongzheng.modules.exam.vo.ExamApplyVo;
import com.zhongzheng.modules.grade.bo.ClassGradeUserQueryBo;
import com.zhongzheng.modules.grade.vo.ClassPeriodStudentExportVo;
import com.zhongzheng.modules.user.bo.*;
import com.zhongzheng.modules.user.domain.UserBankRecord;
import com.zhongzheng.modules.user.service.IUserExamGoodsService;
import com.zhongzheng.modules.user.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhongzheng.common.annotation.Log;
import com.zhongzheng.common.core.controller.BaseController;
import com.zhongzheng.common.core.domain.AjaxResult;
import com.zhongzheng.common.enums.BusinessType;
import com.zhongzheng.modules.user.service.IUserSubscribeService;
import com.zhongzheng.common.utils.poi.ExcelUtil;
import com.zhongzheng.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户预约考试Controller
 *
 * @author ruoyi
 * @date 2021-12-07
 */
@Api(value = "报考数据控制器", tags = {"报考数据控制器"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/subscribe")
public class UserSubscribeController extends BaseController {

    private final IUserSubscribeService iUserSubscribeService;

    private final IUserExamGoodsService iUserExamGoodsService;

    private final IExamApplyGoodsService iExamApplyGoodsService;

    /**
     * 查询用户预约考试列表
     */
    @ApiOperation("查询报考数据列表")
    @PreAuthorize("@ss.hasPermi('system:subscribe:list')")
    @GetMapping("/list")
    public TableDataInfo<UserSubscribeVo> listSubscribe(UserSubscribeQueryBo bo) {
        startPage();
        List<UserSubscribeVo> list = iUserSubscribeService.listSubscribe(bo);
        return getDataTable(list);
    }



    /**
     * 修改用户预约考试
     */
    @ApiOperation("批量取消预约，批量选考试登记状态,批量修改预约状态，批量前培账号开通")
    @PreAuthorize("@ss.hasPermi('system:subscribe:edit')")
    @Log(title = "用户预约考试", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult<Void> edit(@RequestBody UserSubscribeEditBo bo) {
        return toAjax(iUserSubscribeService.updateByEditBo(bo) ? 1 : 0);
    }

    /**
     * 修改用户预约考试
     */
    @ApiOperation("批量改证书状态")
    @PreAuthorize("@ss.hasPermi('system:subscribe:edit')")
    @Log(title = "用户预约考试", businessType = BusinessType.UPDATE)
    @PostMapping()
    public AjaxResult<Void> editCertificate(@RequestBody List<UserSubscribeCertificateEditBo> bo) {
        return toAjax(iUserSubscribeService.editCertificate(bo) ? 1 : 0);
    }

    /**
     * 查询用户下这个商品的考试次数，前培次数列表
     */
    @ApiOperation("查询用户下商品的考试次数，前培次数列表")
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/listUserExam")
    public TableDataInfo<UserExamGoodsVo> listUserExam(UserExamGoodsQueryBo bo) {
        startPage();
        List<UserExamGoodsVo> list = iUserExamGoodsService.listUserExam(bo);
        return getDataTable(list);
    }


    /**
     * 查询详细商品考试次数，前培次数
     */
    @ApiOperation("查询详细商品考试次数，前培次数")
    @PreAuthorize("@ss.hasPermi('system:apply:query')")
    @GetMapping("/UserExam")
    public AjaxResult<UserExamGoodsVo> getUserExamInfo(UserExamGoodsQueryBo userExamGoodsQueryBo) {
        UserExamGoodsVo userExamGoodsVo = iUserExamGoodsService.getUserExamInfo(userExamGoodsQueryBo);
        return AjaxResult.success(userExamGoodsVo);
    }

    @Log(title = "导入预约考试模板", businessType = BusinessType.IMPORT)
    @ApiOperation("导入新增预约考试模板")
    @PreAuthorize("@ss.hasPermi('system:apply:import')")
    @PostMapping("/importData")
    public AjaxResult<UserSubscribeImport> importData(MultipartFile file) throws Exception {
        ExcelUtil<UserSubscribeImport> util = new ExcelUtil<UserSubscribeImport>(UserSubscribeImport.class);
        List<UserSubscribeImport> userSubscribeImportList = util.importExcel(file.getInputStream());
        List<UserSubscribeImport> userSubscribeImport = iUserSubscribeService.importData(userSubscribeImportList);

        if (!CollectionUtils.isEmpty(userSubscribeImport)) {
            return util.exportExcel(userSubscribeImport, "导入失败原因，请勿将此excel修改后再次上传，请在导入模板修改上传");
        }
        UserSubscribeImport userSubscribeImport1 = null;
        return AjaxResult.successNoMsg(userSubscribeImport1);
    }

    @Log(title = "导入修改预约考试模板", businessType = BusinessType.IMPORT)
    @ApiOperation("导入修改预约考试模板")
    @PreAuthorize("@ss.hasPermi('system:apply:import')")
    @PostMapping("/importUpdateData")
    public AjaxResult<UserSubscribeImport> importUpdateData(MultipartFile file) throws Exception {
        ExcelUtil<UserSubscribeImport> util = new ExcelUtil<UserSubscribeImport>(UserSubscribeImport.class);
        List<UserSubscribeImport> userSubscribeImportList = util.importExcel(file.getInputStream());
        List<UserSubscribeImport> userSubscribeImport = iUserSubscribeService.importUpdateData(userSubscribeImportList);
        if (!CollectionUtils.isEmpty(userSubscribeImport)) {
            return util.exportExcel(userSubscribeImport, "导入失败原因，请勿将此excel修改后再次上传，请在导入模板修改上传");
        }
        UserSubscribeImport userSubscribeImport1 = null;
        return AjaxResult.successNoMsg(userSubscribeImport1);
    }

    /**
     * 查询报考数据用户列表
     */
    @ApiOperation("查询报考数据用户列表")
    @PreAuthorize("@ss.hasPermi('system:subscribe:list')")
    @GetMapping("/listUser")
    public TableDataInfo<UserSubscribeVo> listSubscribeByUser(UserSubscribeQueryBo bo) {
        startPage();
        List<UserSubscribeVo> list = iUserSubscribeService.listSubscribeByUser(bo);
        return getDataTable(list);
    }

    @ApiOperation("预约考试身份证导入新增模板")
    @PreAuthorize("@ss.hasPermi('system:apply:import')")
    @PostMapping("/importIdsData")
    public AjaxResult<List<UserSubscribeIdsImport>> importIdsData(MultipartFile file) throws Exception {
        ExcelUtil<UserSubscribeIdsImport> util = new ExcelUtil<UserSubscribeIdsImport>(UserSubscribeIdsImport.class);
        List<UserSubscribeIdsImport> userSubscribeIdsImportList = util.importExcel(file.getInputStream());

        return AjaxResult.success(userSubscribeIdsImportList);
    }


    /**
     * 导出新增预约模板
     */
    @ApiOperation("导出新增预约模板")
    @PreAuthorize("@ss.hasPermi('system:profile:export')")
    @Log(title = "导出新增预约模板", businessType = BusinessType.EXPORT)
    @GetMapping("/exportNew")
    public AjaxResult<Map<String,Object>> exportNew(UserSubscribeExportBo bo) {
        Map<String,Object> map = new HashMap<>();
        ExamApplyGoodsQueryBo examApplyGoodsQueryBo = new ExamApplyGoodsQueryBo();
        examApplyGoodsQueryBo.setApplyId(bo.getApplyId());
        List<ExamApplyGoodsVo> goodsList = iExamApplyGoodsService.listGoods(examApplyGoodsQueryBo);
        ExcelUtil<ExamApplyGoodsVo> goodsUtil = new ExcelUtil<ExamApplyGoodsVo>(ExamApplyGoodsVo.class);
        String timeStr= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        map.put("goodsExcel",goodsUtil.exportEasyExcel(goodsUtil.exportEasyData(goodsList), bo.getApplyName()+"商品列表"+timeStr));

        if(Validator.isEmpty(bo.getApplySiteAddressTrain())){
            UserSubscribeExport export = new UserSubscribeExport();
            export.setRemark("导入时，请把示例删除");
            export.setUserName("李小米");
            export.setIdCard("44086921356895125365");
            export.setApplyName(bo.getApplyName());
            export.setApplySiteAddress(bo.getApplySiteAddress());
            export.setApplySiteExamTime("2021/10/21");
            export.setApplySiteTime("9:00-12:00");
            export.setCode("SP6415428604");
            export.setGoodsName("一级建造师继续教育（必修课+机电工程）");

            List<UserSubscribeExport> list = new ArrayList<>();
            list.add(export);
            ExcelUtil<UserSubscribeExport> util = new ExcelUtil<UserSubscribeExport>(UserSubscribeExport.class);
            map.put("demoExcel",util.exportEasyExcel(util.exportEasyData(list), bo.getApplyName()+"新增预约模板"+timeStr));
        }else{
            //有考培地点
            UserSubscribeTrainExport export = new UserSubscribeTrainExport();
            export.setRemark("导入时，请把示例删除");
            export.setUserName("李小米");
            export.setIdCard("44086921356895125365");
            export.setApplyName(bo.getApplyName());
            export.setApplySiteAddress(bo.getApplySiteAddress());
            export.setApplySiteExamTime("2021/10/21");
            export.setApplySiteTime("9:00-12:00");
            export.setCode("SP6415428604");
            export.setGoodsName("一级建造师继续教育（必修课+机电工程）");

            export.setApplySiteAddressTrain(bo.getApplySiteAddressTrain());
            export.setApplySiteExamTrainTime("2021/10/21");
            export.setApplySiteTrainTime("9:00-12:00");

            List<UserSubscribeTrainExport> list = new ArrayList<>();
            list.add(export);
            ExcelUtil<UserSubscribeTrainExport> util = new ExcelUtil<UserSubscribeTrainExport>(UserSubscribeTrainExport.class);
            map.put("demoExcel",util.exportEasyExcel(util.exportEasyData(list), bo.getApplyName()+"新增预约模板"+timeStr));
        }
        return AjaxResult.success(map);
    }

    /**
     * 导出登记模板
     */
    @ApiOperation("导出登记模板")
    @PreAuthorize("@ss.hasPermi('system:profile:export')")
    @Log(title = "导出登记模板", businessType = BusinessType.EXPORT)
    @GetMapping("/exportRegister")
    public AjaxResult exportRegister(UserSubscribeExportBo bo) {
        UserSubscribeQueryBo userSubscribeQueryBo = new UserSubscribeQueryBo();
        userSubscribeQueryBo.setApplyId(bo.getApplyId());
        userSubscribeQueryBo.setApplySiteAddress(bo.getApplySiteAddress());
        userSubscribeQueryBo.setIdCards(bo.getIdCards());
        userSubscribeQueryBo.setSubscribeStatus(1);
        List<UserSubscribeVo> list = iUserSubscribeService.listSubscribe(userSubscribeQueryBo);
        List<UserSubscribeExportVo> eList = new ArrayList<>();
        for(UserSubscribeVo vo : list){
            UserSubscribeExportVo export = BeanUtil.toBean(vo, UserSubscribeExportVo.class);
            export.setSubscribeStatus("正常");
            if(vo.getExamStatus()==0){
                export.setExamStatus("待登记");
            }
            else if(vo.getExamStatus()==1){
                export.setExamStatus("正常");
            }
            else if(vo.getExamStatus()==2){
                export.setExamStatus("缺考");
            }
            else if(vo.getExamStatus()==3){
                export.setExamStatus("作弊");
            }
            else if(vo.getExamStatus()==4){
                export.setExamStatus("替考");
            }

            if(Validator.isNotEmpty(vo.getResult())){
                if(vo.getResult()==1){
                    export.setResult("通过");
                }
                else if(vo.getResult()==0){
                    export.setResult("不通过");
                }
            }
            export.setApplySiteExamTime(DateUtils.timestampToDate(vo.getApplySiteExamTime()));
            export.setApplySiteTime(vo.getApplySiteStartTime()+"-"+vo.getApplySiteEndTime());
            eList.add(export);
        }
        String timeStr= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        ExcelUtil<UserSubscribeExportVo> util = new ExcelUtil<UserSubscribeExportVo>(UserSubscribeExportVo.class);
        return util.exportEasyExcel(util.exportEasyData(eList), bo.getApplyName()+"登记数据"+timeStr);
    }
}
