package cn.iocoder.yudao.module.smartfactory.controller.admin.staff;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.smartfactory.controller.admin.staff.vo.*;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.factoryinfo.FactoryInfoDO;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.staff.StaffDO;
import cn.iocoder.yudao.module.smartfactory.service.factoryinfo.FactoryInfoService;
import cn.iocoder.yudao.module.smartfactory.service.staff.StaffService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 员工")
@RestController
@RequestMapping("/smartfactory/staff")
@Validated
public class StaffController {

    @Resource
    private StaffService staffService;

    @Resource
    private FactoryInfoService factoryInfoService;

    @Resource
    private DictDataApi dictDataApi;

    @PostMapping("/create")
    @Operation(summary = "创建员工")
    public CommonResult<Long> createStaff(@Valid @RequestBody StaffSaveReqVO createReqVO) {
        return success(staffService.createStaff(createReqVO));
    }

    @GetMapping("/getTheFactoryOfTheCurrentlyLoggedInUser")
    @Operation(summary = "获取当前登录用户所属工厂Id（为null就是不属于任何工厂）")
    public CommonResult<Long> getTheFactoryOfTheCurrentlyLoggedInUser() {
        return success(staffService.getTheFactoryOfTheCurrentlyLoggedInUser());
    }

    @PutMapping("/update")
    @Operation(summary = "更新员工")
    public CommonResult<Boolean> updateStaff(@Valid @RequestBody StaffSaveReqVO updateReqVO) {
        staffService.updateStaff(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-salary")
    @Operation(summary = "更新员工")
    public CommonResult<Boolean> updateStaffSalary(@RequestBody StaffSalaryUpdateVO updateReqVO) {
        staffService.updateStaffSalary(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除员工")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteStaff(@RequestParam("id") Long id) {
        staffService.deleteStaff(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得员工")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<StaffDO> getStaff(@RequestParam("id") Long id) {
        StaffDO staff = staffService.getStaff(id);
        return success(staff);
    }

    @GetMapping("/getListByFactory")
    @Operation(summary = "获得指定厂区得员工")
    @Parameter(name = "factoryId", description = "厂区编号", required = true, example = "1024")
    @Parameter(name = "isIn", description = "是否获取该厂区得员工", required = true, example = "1024")
    public CommonResult<List<StaffRespVO>> getListByFactory(@RequestParam("factoryId") Long factoryId,
                                                            @RequestParam("isIn") Boolean isIn) {
        List<StaffDO> staffs = staffService.getListByFactory(factoryId, isIn);
        return success(BeanUtils.toBean(staffs, StaffRespVO.class));
    }


    @GetMapping("/getListByFactoryId")
    @Operation(summary = "获得指定厂员工")
    public CommonResult<List<StaffRespVO>> getListByFactoryId(@RequestParam("factoryId") Long factoryId,
                                                              @RequestParam(value = "nickName", required = false) String nickName,
                                                              @RequestParam(value = "workTypeId", required = false) Long workTypeId) {
        List<StaffDO> staffs = staffService.getListByFactoryId(factoryId, nickName, workTypeId);
        return success(BeanUtils.toBean(staffs, StaffRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得员工分页")
    public CommonResult<PageResult<StaffRespVO>> getStaffPage(@Valid StaffPageReqVO pageReqVO) {
        PageResult<StaffDO> pageResult = staffService.getStaffPage(pageReqVO);
        PageResult<StaffRespVO> result = BeanUtils.toBean(pageResult, StaffRespVO.class);
        if (CollUtil.isNotEmpty(result.getList())) {

            // 获取工厂详情
            Set<Long> factoryIds = convertSet(result.getList(), StaffRespVO::getFactoryId);
            Map<Long, FactoryInfoDO> factoryInfoMap = convertMap(factoryInfoService.getFactoryList(factoryIds), FactoryInfoDO::getId);
            result.getList().forEach(data -> {
                // 设置工厂名称
                data.setFactoryName(factoryInfoMap.containsKey(data.getFactoryId()) ? factoryInfoMap.get(data.getFactoryId()).getShortName() : null);
            });
        }

        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出员工 Excel")
    @OperateLog(type = EXPORT)
    public void exportStaffExcel(@Valid StaffPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        pageReqVO.setStatus(1);
        List<StaffDO> list = staffService.getStaffPage(pageReqVO).getList();

        // 获取工种字典值
        List<DictDataRespDTO> dictDataRespDTOS = dictDataApi.getDictDataList("user_work_type").getCheckedData();
        Map<String, String> workTypeMap = dictDataRespDTOS.stream().collect(Collectors.toMap(DictDataRespDTO::getValue, DictDataRespDTO::getLabel));

        // 获取工厂信息Map
        Map<Long, FactoryInfoDO> factoryInfoDOMap = convertMap(factoryInfoService.getFactoryList(), FactoryInfoDO::getId);

        List<StaffRespVO> respVOS = BeanUtils.toBean(list, StaffRespVO.class);
        respVOS.forEach(item -> {
            if (item.getWorkTypeId() != null) {
                item.setWorkTypeName(workTypeMap.getOrDefault(item.getWorkTypeId().toString(), ""));
            }
            // 设置性别
            item.setSexStr(item.getSex() == null ? null : item.getSex() == 1 ? "男" : "女");
            // 设置工厂名称
            item.setFactoryName(factoryInfoDOMap.get(item.getFactoryId()) != null ? factoryInfoDOMap.get(item.getFactoryId()).getShortName() : null);
        });

        // 导出 Excel
        ExcelUtils.write(response, "员工.xls", "数据", StaffRespVO.class, respVOS);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {

        //获取部门名称
        List<FactoryInfoDO> factoryInfoDOS = factoryInfoService.getFactoryListByType();
        List<String> factoryName = factoryInfoDOS.stream()
                .map(item -> item.getId() + ":" + item.getShortName())
                .collect(Collectors.toList());

        //获取工种名称
        List<DictDataRespDTO> workTypeVOs = dictDataApi.getDictDataList("user_work_type").getCheckedData();
        List<String> workTypeName = workTypeVOs.stream()
                .map(item -> item.getValue() + ":" + item.getLabel())
                .collect(Collectors.toList());

        // 获取业务类型名称
        List<DictDataRespDTO> businessTypeVOs = dictDataApi.getDictDataList("system_settlement_type").getCheckedData();
        List<String> businessTypeName = businessTypeVOs.stream()
                .map(item -> item.getValue() + ":" + item.getLabel())
                .collect(Collectors.toList());

        Map<Integer, List<String>> mapDropDown = new HashMap<>();
        mapDropDown.put(1, factoryName);
        mapDropDown.put(2, workTypeName);
        mapDropDown.put(3, businessTypeName);

        // 输出
        ExcelUtils.write(response, "工人导入模板.xlsx", "工人列表",
                StaffImportExcelVO.class, null,
                mapDropDown);
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<StaffImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                       @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<StaffImportExcelVO> list = ExcelUtils.read(file, StaffImportExcelVO.class);
        return success(staffService.importUserList(list, updateSupport));
    }
}
