package com.testor.module.train.project.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
import com.testor.common.core.utils.StringUtils;
import com.testor.common.core.utils.bean.BeanUtils;
import com.testor.common.util.DateUtil;
import com.testor.common.util.PageUtil;
import com.testor.module.emergency.model.execl.ExportGoods;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.module.train.myManagement.controller.TTrainMyManagementController;
import com.testor.module.train.myManagement.model.dto.TTrainMyManagementParam;
import com.testor.module.train.project.model.domain.TrainExamsExternalInfo;
import com.testor.module.train.project.model.enums.TrainTabStatus;
import com.testor.module.train.project.model.enums.TrainTakeExamStateEnum;
import com.testor.module.train.project.model.stat.*;
import com.testor.module.train.project.service.TrainExamsExternalInfoService;
import com.testor.module.train.project.service.TrainProjectUserService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author caq
 * @date 2024/9/7
 * @description 个人培训档案列表
 */
@RestController
@RequestMapping("/projectUser")
@Api(value = "TrainProjectUserController", tags = "个人培训档案")
@Slf4j
public class TrainProjectUserController extends SuperController {
    @Autowired
    private TrainProjectUserService trainProjectUserService;
    @Autowired
    private TTrainMyManagementController trainMyManagementController;
    @Autowired
    private TrainExamsExternalInfoService trainExamsExternalInfoService;
    @Autowired
    private SysDictDataController sysDictDataController;
    @Autowired
    private NewSysOrgService newSysOrgService;
    @Resource
    private HttpServletResponse response;

    @ApiOperation(value = "指标下拉框列表 ", notes = "指标下拉框")
    @GetMapping(value = "/selectList")
    public BaseResponse<Map<String, List<JSONObject>>> findProjectDetailCount() {
        Map<String, List<JSONObject>> stringListMap = trainProjectUserService.professionalIndicatorScoreSelect();
        BaseResponse<Map<String, List<JSONObject>>> baseResponse = new BaseResponse<>();
        baseResponse.setData(stringListMap);
        return baseResponse;
    }

    @ApiOperation(value = "个人培训档案列表 ", notes = "个人培训档案列表")
    @GetMapping(value = "/findProjectUserPageList")
    public BaseResponse<BaseResponseList<TrainProjectUserListVo>> findProjectUserPageList(TrainProjectUserPara param) {
        convertPara(param);
        BaseResponseList<TrainProjectUserListVo> baseResponseList = trainProjectUserService.findProjectUserPageList(param);
        BaseResponse<BaseResponseList<TrainProjectUserListVo>> baseResponse = new BaseResponse<>();
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "个人培训档案列表-导出", notes = "个人培训档案列表-导出")
    @GetMapping(value = "/findProjectUserPageListExport")
    public void findProjectUserPageListExport(TrainProjectUserPara param) throws Exception {
        convertPara(param);
        param.setPage("1");
        param.setLimit(String.valueOf(Integer.MAX_VALUE));
        BaseResponseList<TrainProjectUserListVo> baseResponseList = trainProjectUserService.findProjectUserPageList(param);
        List<TrainProjectUserListVo> data = baseResponseList.getData();

        List<TrainProjectUserExcelVo> excelVoList = JSON.parseArray(JSON.toJSONString(data), TrainProjectUserExcelVo.class);


        String fileName = "个人培训档案列表";
        //内容策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 垂直居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                .head(TrainProjectUserExcelVo.class)
                // 合并策略：合并相同数据的行。第一个参数表示从哪一行开始进行合并，由于表头占了两行，因此从第2行开始（索引从0开始）
                //设置列宽
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(22))
                //设置内容样式（垂直居中）
                .registerWriteHandler(horizontalCellStyleStrategy)
                // 注意：需要先调用registerWriteHandler()再调用sheet()方法才能使合并策略生效！！！
                .sheet("个人培训档案列表")
                //数据源 dataList(List<List<Object>>)双层list集合
                .doWrite(excelVoList);
    }


    @ApiOperation(value = "培训数量统计 ", notes = "培训数量统计")
    @GetMapping(value = "/stat")
    public BaseResponse<TrainProjectUserStat> findProjectUserStat(String userId) {
        TrainProjectUserStat projectUserStat = trainProjectUserService.findProjectUserStat(userId);
        BaseResponse<TrainProjectUserStat> baseResponse = new BaseResponse<>();
        baseResponse.setData(projectUserStat);
        return baseResponse;
    }

    @ApiOperation(value = "人员信息", notes = "人员信息")
    @GetMapping(value = "/userInfo")
    public BaseResponse<ProjectUserInfo> findProjectUserInfo(String userId) {
        ProjectUserInfo projectUserInfo = trainProjectUserService.findProjectUserInfo(userId);
        BaseResponse<ProjectUserInfo> baseResponse = new BaseResponse<>();
        baseResponse.setData(projectUserInfo);
        return baseResponse;
    }

    @ApiOperation(value = "培训记录列表", notes = "培训记录列表")
    @PostMapping(value = "/findTrainList")
    public BaseResponse<BaseResponseList<TrainProjectUserDetailStat>> findTrainList(@RequestBody TTrainMyManagementParam param) {
        String userId = param.getUserId();
        List<TrainProjectUserDetailStat> trainList = trainProjectUserService.findTrainList(param);
        findExternalList(userId, param.getTabStatus(), trainList);
        List<TrainProjectUserDetailStat> list = PageUtil.startPage(trainList, Integer.valueOf(param.getPage()), Integer.valueOf(param.getLimit()));
        BaseResponseList<TrainProjectUserDetailStat> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(list);
        baseResponseList.setTotal(trainList.size());
        BaseResponse<BaseResponseList<TrainProjectUserDetailStat>> baseResponse = new BaseResponse<>();
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    public void findExternalList(String userId, String tabStatus, List<TrainProjectUserDetailStat> trainList) {
        String orgName = "";
        for (TrainProjectUserDetailStat item:trainList) {
            SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "EXAM_TYPE", item.getUserTypeCode()).getData();
            if (ObjectHelper.isNotEmpty(materials2)) {
                String materials = materials2.getDictValue();
                item.setUserTypeName(materials);
                orgName = item.getOrgName();
            }
        }
        List<TrainExamsExternalInfo> list = trainExamsExternalInfoService.lambdaQuery().eq(TrainExamsExternalInfo::getUserId, userId)
                .orderByDesc(TrainExamsExternalInfo::getUpdateDate)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        if (TrainTabStatus.A_M.getValue().equals(tabStatus)) {
            //外部培训列表
            for (TrainExamsExternalInfo trainExamsExternalInfo : list) {
                TrainProjectUserDetailStat queryVO = new TrainProjectUserDetailStat();
                queryVO.setTaskName(trainExamsExternalInfo.getTrainName());
                queryVO.setLearnWay(trainExamsExternalInfo.getTrainType());
                SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "EXAM_TYPE", trainExamsExternalInfo.getUserTypeCode()).getData();
                if (ObjectHelper.isNotEmpty(materials2)) {
                    String materials = materials2.getDictValue();
                    queryVO.setUserTypeName(materials);
                }
                queryVO.setVisitStartTime(trainExamsExternalInfo.getTrainStartTime());
                queryVO.setVisitEndTime(trainExamsExternalInfo.getTrainEndTime());
                queryVO.setOrgName(orgName);
                queryVO.setExternalDataStatus("1");
                queryVO.setId(trainExamsExternalInfo.getId());
                trainList.add(queryVO);
            }
        }
        if (TrainTabStatus.B_M.getValue().equals(tabStatus)) {
            //外部考试列表
            for (TrainExamsExternalInfo trainExamsExternalInfo : list) {
                String takeExamState = trainExamsExternalInfo.getTakeExamState();
                if (StringUtils.isNotBlank(takeExamState) && TrainTakeExamStateEnum.YES.getValue().equals(takeExamState)){
                    TrainProjectUserDetailStat queryVO = new TrainProjectUserDetailStat();
                    //考试名称
                    queryVO.setTaskName(trainExamsExternalInfo.getExamName());
                    //考试方式
                    queryVO.setLearnWay(trainExamsExternalInfo.getExamType());
                    queryVO.setVisitStartTime(trainExamsExternalInfo.getTrainStartTime());
                    queryVO.setVisitEndTime(trainExamsExternalInfo.getTrainEndTime());
                    queryVO.setExamDuration(trainExamsExternalInfo.getExamDuration());
                    queryVO.setTestScore(trainExamsExternalInfo.getExamScore());
                    queryVO.setExternalDataStatus("1");
                    queryVO.setId(trainExamsExternalInfo.getId());
                    queryVO.setExamSite(trainExamsExternalInfo.getExamAddress());
                    trainList.add(queryVO);
                }

            }
        }
    }

    private void convertPara(TrainProjectUserPara para) {
        String orgId = para.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            orgId = ContextUtils.getLoginUser().getOrgId();
            para.setOrgId(orgId);
            para.setUserId(ContextUtils.getLoginUser().getUserId());
        }else {
            List<String> list = Arrays.asList(orgId.split(","));
            para.setOrgIdList(list);
            para.setUserId(ContextUtils.getLoginUser().getUserId());
        }
    }

}
