package com.xjrsoft.module.personnel.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.ImageUtil;
import com.xjrsoft.module.hikvision.mapper.HikvisionDataMapper;
import com.xjrsoft.module.hikvision.util.ApiUtil;
import com.xjrsoft.module.hikvision.util.FaceImportUtil;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.personnel.dto.AddFaceManagementDto;
import com.xjrsoft.module.personnel.entity.FaceManagement;
import com.xjrsoft.module.personnel.entity.StundentFaceProcess;
import com.xjrsoft.module.personnel.mapper.StundentFaceProcessMapper;
import com.xjrsoft.module.personnel.service.IFaceManagementService;
import com.xjrsoft.module.personnel.service.IStundentFaceProcessService;
import com.xjrsoft.module.student.dto.BaseStudentSimpleInfoDto;
import com.xjrsoft.module.student.service.IBaseStudentSchoolRollService;
import com.xjrsoft.module.student.vo.BaseStudentSompleInfoVo;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
* @title: 学生人脸信息审核
* @Author dzx
* @Date: 2024-05-10
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class StundentFaceProcessServiceImpl extends MPJBaseServiceImpl<StundentFaceProcessMapper, StundentFaceProcess> implements IStundentFaceProcessService {

    private final HikvisionDataMapper hikvisionDataMapper;

    private final IFaceManagementService faceManagementService;
    private final IUserService userService;
    private final IBaseStudentSchoolRollService rollService;
    private final IFileService fileService;

    //删除人脸后，移除海康那边的人脸
    @Override
    public Boolean removeByIds(List<Long> ids) {
        List<StundentFaceProcess> list = this.baseMapper.selectBatchIds(ids);
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/resource/v1/face/single/delete";
        JsonParser parser = new JsonParser();
        for (StundentFaceProcess process : list) {
            String studentHikvisionId = hikvisionDataMapper.getStudentHikvisionId(process.getUserId());

            String apiUrl = "/api/resource/v1/person/condition/personInfo";
            JsonObject paramsJson = new JsonObject();
            paramsJson.addProperty("paramName", "personId");
            JsonArray array = new JsonArray();
            array.add(studentHikvisionId);
            paramsJson.add("paramValue", array);
            String personInfoRes = apiUtil.doPost(apiUrl, paramsJson.toString(), null);
            String faceId = null;
            JsonObject personInfoData = parser.parse(personInfoRes).getAsJsonObject();
            if("0".equals(personInfoData.get("code").getAsString()) && "success".equals(personInfoData.get("msg").getAsString())){
                JsonObject dataJson = personInfoData.get("data").getAsJsonObject();
                if(dataJson.get("total").getAsInt() > 0){
                    JsonArray personPhoto = dataJson.get("list").getAsJsonArray().get(0)
                            .getAsJsonObject().get("personPhoto").getAsJsonArray();
                    if(personPhoto.size() > 0){
                        faceId = personPhoto.get(0).getAsJsonObject().get("personPhotoIndexCode").getAsString();
                    }

                }
            }

            JsonObject paramJson = new JsonObject();
            paramJson.addProperty("faceId", faceId);

            String result = apiUtil.doPost(apiPath, paramJson.toString(), null);
            process.setExamStatus(2);
            process.setHikvisionResult(result);
            process.setDeleteMark(DeleteMark.DELETED.getCode());
            process.setModifyUserId(StpUtil.getLoginIdAsLong());
            process.setModifyDate(new Date());
            this.baseMapper.updateById(process);

            FaceManagement faceManagement = faceManagementService.getOne(
                    new QueryWrapper<FaceManagement>().lambda()
                            .eq(FaceManagement::getUserId, process.getUserId())
                            .eq(FaceManagement::getFileId, process.getFacePhoto())
            );

            faceManagement.setRegisterBase64(null);
            faceManagementService.update(faceManagement);
        }
        return true;
    }

    @Override
    public Boolean nsUploadFace(AddFaceManagementDto dto, MultipartFile file) {
        //新增人脸管理数据
        FaceManagement faceManagement = BeanUtil.toBean(dto, FaceManagement.class);
        try {
            faceManagement.setRegisterBase64(ImageUtil.ImageHandler(file));
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        boolean isSuccess = faceManagementService.add(faceManagement);

        User user = userService.getById(dto.getUserId());

        List<BaseStudentSompleInfoVo> infosByParam = rollService.getInfosByParam(new BaseStudentSimpleInfoDto() {{
            setUserId(user.getId());
        }});
        BaseStudentSompleInfoVo infoVo = new BaseStudentSompleInfoVo();
        if(!infosByParam.isEmpty()){
            infoVo = infosByParam.get(0);
        }
        //新生学生人俩流程数据
        StundentFaceProcess studentFace = new StundentFaceProcess();
        studentFace.setFacePhoto(dto.getFileId());
        studentFace.setName(dto.getName());
        studentFace.setStatus(1);
        studentFace.setExamStatus(1);
        studentFace.setUserId(dto.getUserId());
        studentFace.setIdentityCard(user.getCredentialNumber());
        studentFace.setGender(user.getGender());
        studentFace.setClassId(infoVo.getClassId());
        studentFace.setTeacherId(infoVo.getTeahcerId());

        File xjrFile = fileService.getOne(
                new QueryWrapper<File>().lambda().eq(File::getFolderId, dto.getFileId())
        );


        String result = FaceImportUtil.ImportStudentFace(hikvisionDataMapper.getStudentHikvisionId(user.getId()), xjrFile.getFileUrl());
        studentFace.setHikvisionResult(result);

        this.save(studentFace);
        return true;
    }

    @Override
    public Boolean clearHistory(StundentFaceProcess process) {
        return this.baseMapper.clearHistory(process);
    }
}
