package com.bonus.app.service.impl;

import com.bonus.app.mapper.AppEquipmentReqMapper;
import com.bonus.app.service.IAppEquipmentReqService;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.app.AppParamsDto;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.entity.bracelet.vo.EquipmentReqDataVo;
import com.bonus.common.entity.bracelet.vo.EquipmentReqVo;
import com.bonus.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.*;

/**
 * @className:AppEquipmentReqServiceImpl
 * @author:cwchen
 * @date:2024-08-06-15:51
 * @version:1.0
 * @description:APP-设备领用-impl
 */
@Service(value = "IAppEquipmentReqService")
@Slf4j
public class AppEquipmentReqServiceImpl implements IAppEquipmentReqService {

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

    @Override
    public List<EquipmentReqVo> getEquipmentReqLists(AppParamsDto dto) {
        List<EquipmentReqVo> list = new ArrayList<>();
        try {
            list = mapper.getEquipmentReqLists(dto);
            for (EquipmentReqVo vo : list) {
                vo.setLeaderPhone(Sm4Utils.decode(vo.getLeaderPhone()));
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addData(EquipmentReqDataVo vo) {
        try {
            boolean isDepartRoleCode = SecurityUtils.isDepartRoleCode();
            if(!isDepartRoleCode){
                return AjaxResult.error("非项目部角色，无领用设备权限");
            }
            if (CollectionUtils.isEmpty(vo.getList())) {
                return AjaxResult.error("领用设备不能为空");
            }
            // 判断是否添加重复设备
            Set<EquipmentReqDataVo.Equipment> setList = new HashSet<>(vo.getList());
            if (setList.size() != vo.getList().size()) {
                return AjaxResult.error("领用设备中有重复设备，请仔细检查");
            }
            for (EquipmentReqDataVo.Equipment equipment : vo.getList()) {
                // 判断设备是否已经归还
                Integer result = result = mapper.isHasUseDevice(equipment);
                if (result > 0) {
                    return AjaxResult.error("领用设备中包含未归还设备，请先归还后，方可再次领用");
                }
            }
            // 添加设备领用数据、设备领用详情数据
            mapper.addDevUseData(vo);
            mapper.addDevUseDetailData(vo);
            // 获取绑定班组的班组长
            Long teamLeaderId = mapper.getTeamLeader(vo);
            vo.setTeamLeaderId(teamLeaderId);
            for (EquipmentReqDataVo.Equipment equipment : vo.getList()) {
                if(Objects.equals(equipment.getDevType(), BusinessConstants.SHX)){
                    // 绑定手环箱
                    mapper.updateDeviceData(vo,equipment,1);
                }else if(Objects.equals(equipment.getDevType(), BusinessConstants.AQM)){
                    // 绑定安全帽
                    mapper.updateDeviceData(vo,equipment,3);
                }else{
                    // 绑定除安全帽和手环箱以外的设备（绑定人为班组长）
                    mapper.updateDeviceData(vo,equipment,2);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getUseDevices(AppParamsDto dto) {
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            if(StringUtils.isNotBlank(dto.getDevType())){
                list = mapper.getUseDevices(dto);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult returnDevice(AppParamsDto dto) {
        try {
            boolean isDepartRoleCode = SecurityUtils.isDepartRoleCode();
            if(!isDepartRoleCode){
                return AjaxResult.error("非项目部角色，无归还设备权限");
            }
            if(Objects.equals(dto.getDevType(), BusinessConstants.SHX)){
                // 设备类型为手环箱时，判断手环设备是否全部归还
                int result = mapper.isAllDeviceReturn(dto,1);
                if(result > 0){
                    return AjaxResult.error("该手环箱中包含的手环设备未全部归还");
                }
                // 解绑手环箱
                mapper.updateReturnDeviceData(dto,1);
            }else if(Objects.equals(dto.getDevType(), BusinessConstants.AQM)){
                // 设备类型为安全帽时，判断是否全部归还
                int result = mapper.isAllDeviceReturn(dto,1);
                if(result > 0){
                    return AjaxResult.error("班组人员未归还安全帽设备");
                }
                mapper.updateReturnDeviceData(dto,2);
            }else{
                // 解绑除手环箱以外的设备
                mapper.updateReturnDeviceData(dto,2);
            }
            mapper.returnDevice(dto);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }
}
