package com.xjrsoft.module.personnel.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.ImageUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.personnel.dto.AddFaceManagementDto;
import com.xjrsoft.module.personnel.dto.FaceManagementPageDto;
import com.xjrsoft.module.personnel.dto.UpdateFaceManagementDto;
import com.xjrsoft.module.personnel.dto.UpdateFaceManagementStatusDto;
import com.xjrsoft.module.personnel.entity.FaceManagement;
import com.xjrsoft.module.personnel.entity.StundentFaceProcess;
import com.xjrsoft.module.personnel.entity.TeacherFaceProcess;
import com.xjrsoft.module.personnel.service.IFaceManagementService;
import com.xjrsoft.module.personnel.service.IStundentFaceProcessService;
import com.xjrsoft.module.personnel.service.ITeacherFaceProcessService;
import com.xjrsoft.module.personnel.vo.FaceManagementVo;
import com.xjrsoft.module.system.service.ICodeRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/personnel" + "/facemanager")
@Api(value = "/personnel" + "/facemanager", tags = "人脸管理")
@AllArgsConstructor
public class FaceManagementController {
    private final IFaceManagementService faceManagementService;
    private ICodeRuleService codeRuleService;
    private final ITeacherFaceProcessService teacherFaceProcessService;
    private final IStundentFaceProcessService stundentFaceProcessService;

    @GetMapping(value = "/page")
    @ApiOperation(value = "人脸列表(分页)")
    @SaCheckPermission("facemanager:detail")
    public RT<PageOutput<FaceManagementVo>> Page(@Valid FaceManagementPageDto dto) {
        MPJLambdaWrapper<FaceManagement> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .like(StrUtil.isNotBlank(dto.getFaceCode()), FaceManagement::getFaceCode, dto.getFaceCode())
                .like(ObjectUtil.isNotNull(dto.getName()), FaceManagement::getName, dto.getName())
                .select(FaceManagement.class, x -> VoToColumnUtil.fieldsToColumns(FaceManagementVo.class).contains(x.getProperty()))
                .select(FaceManagement::getId);

        IPage<FaceManagement> page = faceManagementService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<FaceManagementVo> pageOutput = ConventPage.getPageOutput(page, FaceManagementVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "根据id查询人脸信息")
    @SaCheckPermission("facemanager:detail")
    public RT<FaceManagementVo> info(@RequestParam Long id) {
        FaceManagement faceManagement = faceManagementService.getByIdDeep(id);
        if (faceManagement == null) {
            return RT.error("找不到此数据！");
        }

        return RT.ok(BeanUtil.toBean(faceManagement, FaceManagementVo.class));
    }

    @GetMapping(value = "/detail")
    @ApiOperation(value = "根据当前用户查询人脸信息")
    @SaCheckPermission("facemanager:detail")
    public RT<FaceManagementVo> detail() {
        FaceManagement faceManagement = faceManagementService.getOneDeep(
                MPJWrappers.<FaceManagement>lambdaJoin()
                .eq(FaceManagement::getDeleteMark, DeleteMark.NODELETE.getCode())
                .eq(FaceManagement::getUserId, StpUtil.getLoginIdAsLong())
        );
        if (faceManagement == null) {
            return RT.error("找不到此数据！");
        }

        List<Long> ids=new ArrayList<>();
        ids.add(faceManagement.getId());
        faceManagement.setVerifyStatus(1);
        if (faceManagement.getUserType() == 1) {
            // 查询 teacher_face_process 审核通过
            MPJLambdaWrapper<TeacherFaceProcess> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(TeacherFaceProcess::getUserId, faceManagement.getUserId())
                    .eq(TeacherFaceProcess::getFacePhoto, faceManagement.getFileId())
                    .eq(TeacherFaceProcess::getDeleteMark, 0)
//                    .eq(TeacherFaceProcess::getStatus, 1)
            ;
            TeacherFaceProcess teacherFaceProcess = teacherFaceProcessService.getOne(queryWrapper);
            if (teacherFaceProcess != null) {
                if (teacherFaceProcess.getStatus() == 1)
                    faceManagement.setVerifyStatus(2);
                if (teacherFaceProcess.getStatus() == 2)
                    faceManagement.setVerifyStatus(3);
            }else{
                faceManagementService.delete(ids);
                return RT.error("找不到此数据！");
            }
        }

        if (faceManagement.getUserType() == 2) {
            // 查询 teacher_face_process 审核通过
            MPJLambdaWrapper<StundentFaceProcess> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(StundentFaceProcess::getUserId, faceManagement.getUserId())
                    .eq(StundentFaceProcess::getFacePhoto, faceManagement.getFileId())
                    .eq(StundentFaceProcess::getDeleteMark, 0)
//                    .eq(StundentFaceProcess::getStatus, 1)
            ;
            StundentFaceProcess stundentFaceProcess = stundentFaceProcessService.getOne(queryWrapper);
            if (stundentFaceProcess != null) {
                if (stundentFaceProcess.getStatus() == 1)
                    faceManagement.setVerifyStatus(2);
                if (stundentFaceProcess.getStatus() == 2)
                    faceManagement.setVerifyStatus(3);
            }else{
                faceManagementService.delete(ids);
                return RT.error("找不到此数据！");
            }
        }
        return RT.ok(BeanUtil.toBean(faceManagement, FaceManagementVo.class));
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "新增人脸")
    @SaCheckPermission("facemanager:add")
    public RT<Boolean> add(AddFaceManagementDto dto, @RequestParam("file") MultipartFile file) {
        FaceManagement faceManagement = BeanUtil.toBean(dto, FaceManagement.class);
        try {
            faceManagement.setRegisterBase64(ImageHandler(file));
        } catch (Exception e) {
            return RT.error(e.getMessage());
        }
        boolean isSuccess = faceManagementService.add(faceManagement);
        codeRuleService.useEncode("FACECODE");
        return RT.ok(isSuccess);

    }

    @PostMapping(value = "/update")
    @ApiOperation(value = "修改人脸")
    @SaCheckPermission("facemanager:edit")
    public RT<Boolean> update(UpdateFaceManagementDto dto, @RequestParam(name = "file",required = false) MultipartFile file) {
        FaceManagement faceManagement = BeanUtil.toBean(dto, FaceManagement.class);
        if (file != null) {
            try {
                faceManagement.setRegisterBase64(ImageHandler(file));
            } catch (Exception e) {
                return RT.error(e.getMessage());
            }
        }
        return RT.ok(faceManagementService.update(faceManagement));

    }

    @PutMapping("/status")
    @ApiOperation(value = "修改人脸状态")
    @SaCheckPermission("facemanager:edit-status")
    public RT<Boolean> updateEnabled(@Valid @RequestBody UpdateFaceManagementStatusDto dto) {
        //根据id修改表单enabledMark
        return RT.ok(faceManagementService.update(Wrappers.<FaceManagement>update().lambda().set(FaceManagement::getEnabledMark, dto.getEnabledMark()).eq(FaceManagement::getId, dto.getId())));
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @SaCheckPermission("facemanager:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids) {
        return RT.ok(faceManagementService.delete(ids));
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除")
    @SaCheckPermission("facemanager:delete-current")
    public RT<Boolean> delete() {
        return RT.ok(faceManagementService.remove(Wrappers.<FaceManagement>query().lambda().eq(FaceManagement::getUserId,StpUtil.getLoginIdAsLong())));
    }

    // 图片处理
    public String ImageHandler(@NotNull MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
        String[] imgSuffix = new String[]{"png", "jpg", "jpeg"};

        if (!Arrays.asList(imgSuffix).contains(suffix)) {
            throw new MyException("图片格式不正确！");
        }
        Map<String, String> map = new HashMap<String, String>() {
            {
                put("jpg", "data:image/jpg;base64,");
                put("jpeg", "data:image/jpeg;base64,");
                put("png", "data:image/png;base64,");
            }
        };

        Long maxSize = 1048576L; // 最大文件1M
        byte[] resultImg = ImageUtil.compressUnderSize(file.getBytes(), maxSize);

        return map.get(suffix) + ImageUtil.bytesEncode2Base64(resultImg);
    }
}
