package cn.iocoder.yudao.module.system.controller.admin.equipment;

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.system.controller.admin.equipment.vo.attendancemachine.AttendanceMachineRespVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UserExtImportVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UsersExtPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UsersExtRespVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UsersExtSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.yudao.module.system.convert.equipment.AttendanceMachineConvert;
import cn.iocoder.yudao.module.system.convert.equipment.UsersExtConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.AttendanceMachineDO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.DistributeRecordDO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.UsersExtDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.equipment.AttendanceMachineService;
import cn.iocoder.yudao.module.system.service.equipment.DistributeRecordService;
import cn.iocoder.yudao.module.system.service.equipment.UsersExtService;
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.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
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.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
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.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 用户信息拓展")
@RestController
@RequestMapping("/system/users-ext")
@Validated
public class UsersExtController {

    @Resource
    private UsersExtService usersExtService;

    @Resource
    private DeptService deptService;

    @Resource
    private AttendanceMachineService attendanceMachineService;

    @Resource
    private DistributeRecordService recordService;

    @RequestMapping(value = "/create",
            method = {RequestMethod.POST, RequestMethod.PUT}) // 解决 uni-app 不支持 Put 上传文件的问题)
    @Operation(summary = "上传照片")
    @Parameter(name = "createReqVO", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:users-ext:create')")
    public CommonResult<String> createUsersExt(@ModelAttribute UsersExtSaveReqVO createReqVO, @RequestParam("faceFile") MultipartFile file) throws Exception {

        UsersExtDO updateDO = BeanUtils.toBean(createReqVO, UsersExtDO.class);
        return success(usersExtService.createUsersExt(updateDO, file));
    }

    @PutMapping("/update")
    @Operation(summary = "删除用户已下发的设备")
    @PreAuthorize("@ss.hasPermission('system:users-ext:update')")
    public CommonResult<Boolean> updateUsersExt(@Valid @RequestBody UsersExtSaveReqVO updateReqVO) {
        usersExtService.updateUsersExt(updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户下发设备详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:users-ext:query')")
    public CommonResult<List<AttendanceMachineRespVO>> getAttendanceMachine(@RequestParam("id") Long id) {

        UsersExtDO usersExt = usersExtService.getUsersExt(id);

        // 获得用户已下发的设备列表
        List<AttendanceMachineDO> attendanceMachineDO = attendanceMachineService.getAttendanceMachineByDeviceNo(usersExt.getAttendanceMachineNos());

        // 获得部门信息Map
        Map<Long, DeptDO> deptDOMap = deptService.getDeptMap(convertList(attendanceMachineDO, AttendanceMachineDO::getDeptId));

        return success(AttendanceMachineConvert.INSTANCE.convertList(attendanceMachineDO, deptDOMap));
    }

    @GetMapping("/page")
    @Operation(summary = "获得考勤设备用户人脸信息分页")
    @PreAuthorize("@ss.hasPermission('system:users-ext:query')")
    public CommonResult<PageResult<UsersExtRespVO>> getUsersExtPage(@Valid UsersExtPageReqVO pageReqVO) {

        PageResult<UsersExtRespVO> pageResult = usersExtService.getUsersExtPage(pageReqVO);

        if (!CollUtil.isEmpty(pageResult.getList())) {

            //获得部门Map
            Map<Long, DeptDO> deptMap = deptService.getDeptMap(convertList(pageResult.getList(), UsersExtRespVO::getDeptId));

            // 获得 下发或修改状态信息
            List<Integer> type = Arrays.asList(1,2);
            List<DistributeRecordDO> recordDOs = recordService.getDistributeRecord(convertList(pageResult.getList(), UsersExtRespVO::getUserId), type);
            Map<Long, DistributeRecordDO> recordDOMap = convertMap(recordDOs, DistributeRecordDO::getUserId);

            List<UsersExtRespVO> respVOS = UsersExtConvert.INSTANCE.convertList(pageResult.getList(), deptMap, recordDOMap);

            // 判断是否已下发
            if (pageReqVO.getIsIssued() != null && pageReqVO.getIsIssued() == 0) {

                respVOS = respVOS.stream().filter(data -> data.getDevices() == null || !new HashSet<>(data.getDevices()).containsAll(pageReqVO.getDeviceNos())).collect(Collectors.toList());
            }else if (pageReqVO.getIsIssued() != null && pageReqVO.getIsIssued() == 1) {

                respVOS = respVOS.stream().filter(data -> data.getDevices() != null && new HashSet<>(data.getDevices()).containsAll(pageReqVO.getDeviceNos())).collect(Collectors.toList());
            }

            return success(new PageResult<>(respVOS, pageResult.getTotal()));
        }

        return success(BeanUtils.toBean(pageResult, UsersExtRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户信息拓展 Excel")
    @PreAuthorize("@ss.hasPermission('system:users-ext:export')")
    @OperateLog(type = EXPORT)
    public void exportUsersExtExcel(@Valid UsersExtPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {

        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UsersExtRespVO> list = usersExtService.getUsersExtPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户人脸图片.xlsx", "数据", UsersExtRespVO.class,
                        list);
    }

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

        UsersExtPageReqVO pageReqVO = new UsersExtPageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        pageReqVO.setIsEnter(0);

        //获得 所有未录入人脸得用户信息
        List<UsersExtRespVO> list = usersExtService.getUsersExtPage(pageReqVO).getList();

        // 输出
        ExcelUtils.write(response, "用户导入.xlsx", "用户列表", UserExtImportVO.class, BeanUtils.toBean(list, UserExtImportVO.class));
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户人脸")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {

        List<UserExtImportVO> list = ExcelUtils.read(file, UserExtImportVO.class);

        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        for (Sheet sheet : workbook) {
            if (sheet instanceof XSSFSheet) {
                XSSFSheet xssfSheet = (XSSFSheet) sheet;
                List<XSSFPictureData> pictures = xssfSheet.getWorkbook().getAllPictures();
                for (int i = 0; i < pictures.size(); i++) {

                    UserExtImportVO importVO = list.get(i);
                    importVO.setFaceFile(pictures.get(i).getData());
                }
            }
        }

        return success(usersExtService.importUserList(list, updateSupport));
    }
}