package cn.iocoder.yudao.module.base.controller.admin;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoach;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCoachService;
import cn.iocoder.yudao.module.base.vo.*;
import cn.iocoder.yudao.module.base.vo.BusinessRecordExportVO;
import cn.iocoder.yudao.module.course.vo.SchoolCommissionVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.*;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.excel.core.util.ExcelUtils.exportBlankTemplate;

@Tag(name = "管理后台 - 驾校教练")
@RestController
@RequestMapping("/base/dl-drive-school-coach")
@Validated
public class DlDriveSchoolCoachController {

    @Resource
    private DlDriveSchoolCoachService dlDriveSchoolCoachService;

    @Resource
    private RoleService roleService;

    /**
     * 驾校教练、普通员工列表
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @param pageNo    分页参数第几页
     * @param pageSize  分页参数每页多少条数据
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 14:58 2025/1/16
     **/
    @GetMapping("/page")
    @Operation(summary = "获得驾校教练分页")
    public CommonResult<IPage<?>> getDlDriveSchoolCoachPage(DlDriveSchoolCoachPageReqVO pageReqVO,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<DlDriveSchoolCoachRespVO> page = new Page<>(pageNo, pageSize);
        return success(dlDriveSchoolCoachService.queryListPage(pageReqVO, page));
    }

    /**
     * 不分页获取教练信息
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 14:25 2025/2/7
     **/
    @GetMapping("/list")
    @Operation(summary = "不分页获取教练信息")
    public CommonResult<List<?>> listSchoolCoach(DlDriveSchoolCoachPageReqVO pageReqVO) {
        return success(dlDriveSchoolCoachService.listSchoolCoach(pageReqVO));
    }

    @GetMapping("/businessList")
    @Operation(summary = "不分页获取业务经理信息")
    public CommonResult<List<?>> listSchoolBusiness(DlDriveSchoolCoachPageReqVO pageReqVO) {
        return success(dlDriveSchoolCoachService.listSchoolBusiness(pageReqVO));
    }

    /**
     * 不分页获取驾校人员信息
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 14:25 2025/2/7
     **/
    @GetMapping("/listPeople")
    @Operation(summary = "不分页获取教练信息")
    public CommonResult<List<?>> listSchoolPeople(DlDriveSchoolCoachPageReqVO pageReqVO) {
        return success(dlDriveSchoolCoachService.listSchoolPeople(pageReqVO));
    }

    /**
     * 保存驾校教练
     *
     * @param createReqVO {@link DlDriveSchoolCoachSaveReqVO}
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.String>
     * @author PQZ
     * @date 16:19 2025/1/16
     **/
    @PostMapping("/save")
    @Operation(summary = "创建驾校教练")
    public CommonResult<Boolean> saveSchoolCoach(@Valid @RequestBody DlDriveSchoolCoachSaveReqVO createReqVO) {
        dlDriveSchoolCoachService.saveSchoolCoach(createReqVO);
        return success(true);
    }

    /**
     * 通过id删除驾校教练
     *
     * @param id 教练id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 21:40 2025/1/16
     **/
    @DeleteMapping("/delete")
    @Operation(summary = "删除驾校教练")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteDlDriveSchoolCoach(@RequestParam("id") String id) {
        dlDriveSchoolCoachService.deleteDlDriveSchoolCoach(id);
        return success(true);
    }

    /**
     * 通过教练id获取驾校教练
     *
     * @param id 教练id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachRespVO>
     * @author PQZ
     * @date 21:41 2025/1/16
     **/
    @GetMapping("/get")
    @Operation(summary = "获得驾校教练")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DlDriveSchoolCoachRespVO> getDlDriveSchoolCoach(@RequestParam("id") String id) {
        DlDriveSchoolCoach dlDriveSchoolCoach = dlDriveSchoolCoachService.getDlDriveSchoolCoach(id);
        return success(BeanUtils.toBean(dlDriveSchoolCoach, DlDriveSchoolCoachRespVO.class));
    }

    /**
     * 通过id获取教练信息
     *
     * @param id id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author PQZ
     * @date 13:47 2025/2/12
     **/
    @GetMapping("/getCoachById")
    @Operation(summary = "获得驾校教练")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<?> appGetCoach(@RequestParam("id") String id) {
        return success(dlDriveSchoolCoachService.getCoachById(id));
    }

    @GetMapping("/getCoachByIdAndTime")
    @Operation(summary = "获得驾校教练")
    public CommonResult<?> appGetCoachByIdAndTime(@RequestParam("id") String id,
                                                  @RequestParam(value = "timeType") String timeType,
                                                  @RequestParam(value = "startTime",required = false) String startTime,
                                                  @RequestParam(value = "endTime",required = false) String endTime) {
        return success(dlDriveSchoolCoachService.getCoachByIdAndTime(id,timeType,startTime,endTime));
    }

    @GetMapping("/getBusinessByIdAndTime")
    @Operation(summary = "获得驾校业务经理")
    public CommonResult<?> getBusinessByIdAndTime(@RequestParam("id") String id,
                                                  @RequestParam(value = "timeType") String timeType,
                                                  @RequestParam(value = "startTime",required = false) String startTime,
                                                  @RequestParam(value = "endTime",required = false) String endTime) {
        return success(dlDriveSchoolCoachService.getBusinessByIdAndTime(id,timeType,startTime,endTime));
    }

    /**
     *
     * @author vinjor-M
     * @date 15:41 2025/2/18
     * @param userId userId
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
    **/
    @GetMapping("/getCoachByUserId")
    @Operation(summary = "根据userId获得驾校教练信息")
    @Parameter(name = "userId", description = "用户id", required = true, example = "1024")
    public CommonResult<?> getCoachByUserId(@RequestParam("userId") Long userId) {
        return success(dlDriveSchoolCoachService.getDlDriveSchoolCoachByUserId(userId));
    }

    /**
     * 获取检测员工详情
     *
     * @param id
     * @return
     */
    @GetMapping("/getOnInternal")
    public CommonResult<?> getOnInternal(Long id) {
        return success(dlDriveSchoolCoachService.getOnInternal(id));
    }

    @PutMapping("/update")
    public CommonResult<?> update(@RequestBody CoachStaffSaveVo coachStaffSaveVo) {
        Assert.notNull(coachStaffSaveVo.getUserId(), "员工id不能为空");
        return success(dlDriveSchoolCoachService.edit(coachStaffSaveVo));
    }

    /**
     * 根据type查询教练列表
     */
    @GetMapping("/coachListByType")
    public CommonResult<?> coachListByType(String type) {
        return success(dlDriveSchoolCoachService.coachListByType(type));
    }

    /**
     * 新增驾校员工
     *
     * @param coachStaffSaveVo
     * @return
     */
    @PostMapping("/saveNew")
    public CommonResult<?> saveNew(@RequestBody CoachStaffSaveVo coachStaffSaveVo) {

        return success(dlDriveSchoolCoachService.saveCoachStaff(coachStaffSaveVo));
    }

    /**
     * 新增文件夹
     * @param userId 用户id
     * @return
     */
    @PostMapping("/addFolder")
    public CommonResult<?> addFolder(@RequestBody Long userId) {
        return success(dlDriveSchoolCoachService.addFolder(userId));
    }

    /**
     * 导入
     */
    @PostMapping("/import")
    public CommonResult<?> importUser(@RequestParam("file") MultipartFile file) {
        try {
            List<SchoolStaffImportExcelVO> list = ExcelUtils.read(file, SchoolStaffImportExcelVO.class);
            Map<String, Object> map = dlDriveSchoolCoachService.importStaff(list);
            return success(map);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 模板
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/get-import-template")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String[] head = {"员工姓名", "岗位", "身份证号码", "年龄", "电话号码", "性别", "教龄", "车牌号", "居住地址", "户籍地址", "个人简介"};

        // 下拉框列及选项：列索引 -> 下拉框选项
        Map<Integer, String[]> dropdownColumns = new HashMap<>();


        //查询岗位
        RoleDO roleDO = new RoleDO();
        roleDO.setServicePackageId("jiaxiao");
        List<RoleDO> roleDOS = roleService.pageByQuery(roleDO);

        String[] roles = roleDOS.stream()
                .map(RoleDO::getName)
                .toArray(String[]::new);

        dropdownColumns.put(1, roles);
        String[] genders = {"男", "女"};
        dropdownColumns.put(5, genders);

        List<List<String>> exampleDataList = Arrays.asList(
                Arrays.asList("测试员工", "岗位是下拉框选择", "xxxxxxxxxxxxxxxxx", "年龄", "电话号码", "性别", "教龄", "车牌号", "居住地址", "户籍地址", "个人简介")
        );

        List<Integer> textColumns = Collections.singletonList(3);

        // 导出空白模板到Excel
        exportBlankTemplate(response, "staff_template.xlsx", "员工信息", head, dropdownColumns, true, exampleDataList, textColumns);
    }

    @GetMapping("/export")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserList(SchoolStaffImportExcelVO query,
                               HttpServletResponse response) throws IOException {
        List<SchoolStaffImportExcelVO> list = dlDriveSchoolCoachService.getAll(query);
        // 输出 Excel
        ExcelUtils.write(response, "员工数据.xls", "数据", SchoolStaffImportExcelVO.class,
                list);
    }

    /**
     * 业务经理招生信息
     */
    @GetMapping("/getBusinessManager")
    public CommonResult<IPage<BusinessRecordVO>> getBusinessManager(BusinessRecordReqVO reqVO,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<BusinessRecordReqVO> page = new Page<>(pageNo, pageSize);
        return success(dlDriveSchoolCoachService.getBusinessManager(reqVO, page));
    }


    /**
     * 业务经理招生补贴计算
     */
    @GetMapping("/getBusinessManagerMoney")
    public CommonResult<List<SchoolCommissionVO>> getBusinessManagerMoney(BusinessRecordReqVO reqVO) {
        return success(dlDriveSchoolCoachService.getBusinessManagerMoney(reqVO));
    }


    /**
     * 获取导出数据列表
     */
    @GetMapping("/getBusinessRecordExportData")
    public CommonResult<IPage<BusinessRecordExportVO>> getOrderExportData(BusinessRecordExportVO exportVO,
                                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<BusinessRecordExportVO> page = new Page<>(pageNo, pageSize);
        return success(dlDriveSchoolCoachService.getBusinessRecordExportData(exportVO, page));
    }

    @GetMapping("/getBusinessRecordExportCount")
    public CommonResult<BusinessRecordExportCountVO> getBusinessRecordExportCount(BusinessRecordExportVO exportVO) {
        return success(dlDriveSchoolCoachService.getBusinessRecordExportCount(exportVO));
    }

    /**
     * 导出
     * @param exportVO
     * @param response
     * @throws IOException
     */
    @GetMapping("/businessRecordExport")
    public void exportCommission(BusinessRecordExportVO exportVO, HttpServletResponse response) throws IOException {
        // 校验导出类型
        if (exportVO.getExportType() == null || !Arrays.asList("current", "all", "range").contains(exportVO.getExportType())) {
            throw new IllegalArgumentException("无效的导出类型: " + exportVO.getExportType());
        }

        // 根据不同类型查询数据
        List<BusinessRecordExportVO> exportData;
        String fileName = "学员记录";

        switch (exportVO.getExportType()) {
            case "current":
                exportData = dlDriveSchoolCoachService.getBusinessRecordList(exportVO);
                fileName += "_第" + exportVO.getPageNo() + "页";
                break;
            case "all":
                exportData = dlDriveSchoolCoachService.getAllBusinessRecordList(exportVO);
                fileName += "_全部数据";
                break;
            case "range":
                exportData = dlDriveSchoolCoachService.getBusinessRecordListByRange(exportVO);
                fileName += "_" + exportVO.getStartPage() + "-" + exportVO.getEndPage() + "页";
                break;
            default:
                throw new IllegalArgumentException("无效的导出类型: " + exportVO.getExportType());
        }


        // 导出Excel
        ExcelUtils.write(response, fileName + ".xlsx", "业务经理招生记录", BusinessRecordExportVO.class, exportData);
    }

    /**
     * 获取当前登录教练的详细信息
     */
    @GetMapping("getLoginCoachInfo")
    public CommonResult<DlDriveSchoolCoach> getLoginCoachInfo() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        return success(dlDriveSchoolCoachService.getLoginCoachInfo(userId));
    }


}
