package com.bonus.bracelet.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.bracelet.mapper.ResourceFileMapper;
import com.bonus.bracelet.mapper.TemporarilyPersonMapper;
import com.bonus.bracelet.service.TemporarilyPersonService;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.FaceCodeUtil;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.entity.bracelet.vo.PersonVo;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.SysFile;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @className:TemporarilyPersonServiceImpl
 * @author:cwchen
 * @date:2024-09-30-9:26
 * @version:1.0
 * @description:临时人员-业务逻辑层
 */
@Service(value = "TemporarilyPersonService")
@Slf4j
public class TemporarilyPersonServiceImpl implements TemporarilyPersonService {

    @Resource(name = "TemporarilyPersonMapper")
    private TemporarilyPersonMapper mapper;

    @Resource(name = "testTaskExecutor")
    private ThreadPoolTaskExecutor testTaskExecutor;

    @Resource(name = "ResourceFileMapper")
    private ResourceFileMapper resourceFileMapper;

    @Resource
    private RemoteFileService remoteFileService;

    @Autowired
    private FaceInterUtilService faceInterService;

    @Override
    public TableDataInfo getTemporarilyPersons(BraceletParamsDto dto) {
        dto.setSourceType(BusinessConstants.RESOURCE_TYPE_USERTEMP);
        List<PersonVo> list = new ArrayList<>();
        List<Future> futureList = new ArrayList<>();
        List<PersonVo> newList = new ArrayList<>();
        try {
            list = mapper.getTemporarilyPersons(dto);
            for (PersonVo vo : list) {
                Future<PersonVo> future = testTaskExecutor.submit(new Callable<PersonVo>() {
                    @Override
                    public PersonVo call() throws Exception {
                        vo.setIdCard(Sm4Utils.decode(vo.getIdCard()));
                        vo.setPhone(Sm4Utils.decode(vo.getPhone()));
                        String imageBase64 = getImageBase64(vo.getFilePath());
                        vo.setBase64Url(imageBase64);
                        return vo;
                    }
                });
                futureList.add(future);
            }
            for (Future<PersonVo> future : futureList) {
                PersonVo vo = future.get();
                newList.add(vo);
            }
        } catch (Exception e) {
            log.error("查询人员列表", e);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(newList);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delTemporarilyPerson(BraceletParamsDto dto) {
        try {
            if (dto.getId() == null) {
                return AjaxResult.error("参数不能为空");
            }
            // 删除临时人员、更新手环绑定的临时人员
            mapper.delTemporarilyPerson(dto);
            Long id = mapper.getBraceletByTemporarilyPerson(dto);
            mapper.updateBracelet(id);
            if (StringUtils.isNotBlank(dto.getFilePath())) {
                String personImgBase64 = getPersonImgBase64(dto.getFilePath());
                // 删除人脸库
                AjaxResult delAjax = delFaceToLibrary(personImgBase64, FaceCodeUtil.DEL, "ls-" + dto.getId());
                if (dto.getFileId() != null) {
                    resourceFileMapper.delResourceFile(dto.getFileId());
                    remoteFileService.delFile(String.valueOf(dto.getFileId()), SecurityConstants.INNER);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 获取图片的base64
     *
     * @param filePath
     * @return String
     * @author cwchen
     * @date 2024/8/20 9:18
     */
    public String getImageBase64(String filePath) {
        R<SysFile> result = remoteFileService.getImgBase64(filePath, SecurityConstants.INNER);
        if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
            String jsonString = JSON.toJSONString(result.getData());
            JSONObject item = JSON.parseObject(jsonString);
            String base64 = item.getString("url");
            return base64;
        }
        return null;
    }

    /**
     * 根据文件ID获取图片base64
     *
     * @param filePath
     * @return String
     * @author cwchen
     * @date 2024/8/12 14:35
     */
    public String getPersonImgBase64(String filePath) {
        R<SysFile> result = remoteFileService.getImgBase64(filePath, SecurityConstants.INNER);
        if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
            String jsonString = JSON.toJSONString(result.getData());
            JSONObject item = JSON.parseObject(jsonString);
            String base64 = item.getString("url");
            return base64;
        }
        return null;
    }

    /**
     * 删除人脸库
     *
     * @param base64
     * @param type
     * @param id
     * @return Integer
     * @author cwchen
     * @date 2024/8/12 13:27
     */
    public AjaxResult delFaceToLibrary(String base64, String type, String id) {
        if (StringUtils.isEmpty(base64)) {
            return null;
        }
        AjaxResult ajaxResult = faceInterService.addFace(base64, type, id);
        log.info("删除人脸库返回结果：{}", ajaxResult);
        return ajaxResult;
    }

}
