package cn.iocoder.yudao.module.inspection.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.module.inspection.enums.DriverLicenseType;
import cn.iocoder.yudao.module.inspection.query.InspectionStaffQuery;
import cn.iocoder.yudao.module.inspection.service.InspectionStaffService;
import cn.iocoder.yudao.module.inspection.vo.InspectionStaffExportVo;
import cn.iocoder.yudao.module.inspection.vo.InspectionStaffSaveVo;
import cn.iocoder.yudao.module.inspection.vo.StaffImportExcelVO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

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

/**
 * inspectionFileController
 *
 * @author zcy
 * @date 2023-10-13
 */
@RestController
@RequestMapping("/admin-api/inspectionStaff")
public class InspectionStaffController extends BaseController {
    @Autowired
    private InspectionStaffService inspectionStaffService;
    @Autowired
    DictDataApi dictDataApi;
    @Resource
    private RoleService roleService;

    /**
     * 获取检测员工列表
     *
     * @param query 查询条件
     * @return
     */
    @GetMapping("/list")
    public CommonResult<?> list(InspectionStaffQuery query,
                                @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<InspectionStaffSaveVo> page = new Page<>(pageNum, pageSize);
        IPage<InspectionStaffSaveVo> list = inspectionStaffService.getList(page, query);
        return success(list);
    }

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

    /**
     * 新增检测员工
     *
     * @param inspectionStaff
     * @return
     */
    @PostMapping("/save")
    public CommonResult<?> save(@RequestBody InspectionStaffSaveVo inspectionStaff) {
        //校验
        verify(inspectionStaff);
        return success(inspectionStaffService.saveInspectionStaff(inspectionStaff));
    }

    /**
     * 编辑检测员工
     *
     * @param inspectionStaff 员工信息
     * @return
     */
    @PutMapping("/update")
    public CommonResult<?> update(@RequestBody InspectionStaffSaveVo inspectionStaff) {
        Assert.notNull(inspectionStaff.getUserId(), "员工id不能为空");
        //校验
        verify(inspectionStaff);
        return success(inspectionStaffService.edit(inspectionStaff));
    }

    /**
     * 模板
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/get-import-template")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String[] head = {"部门名称", "员工姓名", "岗位", "身份证号码", "居住地址", "学历", "毕业院校", "电话号码", "短号", "入职时间", "试用期", "社保购买日期", "紧急联系人", "紧急联系人电话", "驾驶证类型", "备注"};

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

        //查询学历
        List<DictDataRespDTO> education = dictDataApi.getDictDataList("company_staff_edu");
        String[] array1 = education.stream()
                .map(DictDataRespDTO::getLabel)
                .toArray(String[]::new);
        dropdownColumns.put(5, array1);

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

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

        dropdownColumns.put(2, roles);

        List<List<String>> exampleDataList = Arrays.asList(
                Arrays.asList("测试部门", "测试员工", "岗位时下拉框选择", "xxxxxxxxxxxxxxxxx", "居住地", "学历是下拉框", "xxx学校", "手机号", "短号", "2023/5/2（日期格式）", "2023/5/2（日期格式)", "2023/5/2（日期格式", "紧急联系人", "xxxxxxxx", "A1,C1（有多个驾驶证类型使用逗号分割）", "备注")
        );

        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(InspectionStaffQuery query,
                               HttpServletResponse response) throws IOException {
        List<InspectionStaffExportVo> list = inspectionStaffService.getAll(query);
        // 输出 Excel
        ExcelUtils.write(response, "用户数据.xls", "数据", InspectionStaffExportVo.class,
                list);
    }

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

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

    /**
     * 获取已完成项目
     * @param userId 用户id
     * @return
     */
    @GetMapping("/getFinishProjectByUserId")
    public CommonResult<?> getFinishProjectByUserId(@RequestParam("userId") Long userId,
                                                    @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                    @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        return success(inspectionStaffService.getFinishProjectByUserId(page, userId));
    }

    /**
     * 校验信息
     *
     * @param inspectionStaff
     */
    public void verify(InspectionStaffSaveVo inspectionStaff) {
        if (ObjectUtil.isNotEmpty(inspectionStaff.getIdCard())) { //身份证
            boolean validCard = IdcardUtil.isValidCard(inspectionStaff.getIdCard());
            if (!validCard) {
                throw new RuntimeException("身份证格式不正确");
            }
        }
        if (ObjectUtil.isNotEmpty(inspectionStaff.getMobile())) { //手机号
            boolean phone = PhoneUtil.isPhone(inspectionStaff.getMobile());
            if (!phone) {
                throw new RuntimeException("手机号格式不正确");
            }
        }
        if (ObjectUtil.isNotEmpty(inspectionStaff.getEmail())) { //邮箱
            boolean email = Validator.isEmail(inspectionStaff.getEmail());
            if (!email) {
                throw new RuntimeException("邮箱格式不正确");
            }
        }
        if (ObjectUtil.isNotEmpty(inspectionStaff.getEmergencyContactPhone())) { //紧急联系人手机号
            boolean phone = PhoneUtil.isPhone(inspectionStaff.getEmergencyContactPhone());
            if (!phone) {
                throw new RuntimeException("紧急联系人手机号格式不正确");
            }
        }
        if (CollUtil.isNotEmpty(inspectionStaff.getDriverLicenseTypeArr())) {
            // 以逗号隔开
            String driverLicenseType = CollUtil.join(inspectionStaff.getDriverLicenseTypeArr(), ",");
            inspectionStaff.setDriverLicenseType(driverLicenseType);
        }
    }
}
