package com.fuyuanshen.app.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareDetailVo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.exception.user.CaptchaExpireException;
import com.fuyuanshen.common.core.utils.MessageUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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


@RequiredArgsConstructor
@Slf4j
@Service
public class AppDeviceShareService {

    private final AppDeviceShareMapper appDeviceShareMapper;
    
    private final DeviceMapper deviceMapper;

    private final DeviceTypeMapper deviceTypeMapper;

    private final AppPersonnelInfoMapper appPersonnelInfoMapper;

    public AppDeviceShareDetailVo getInfo(Long id) {

        LambdaQueryWrapper<AppDeviceShare> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppDeviceShare::getDeviceId, id);
        List<AppDeviceShareVo> appDeviceShareVos = appDeviceShareMapper.selectVoList(queryWrapper);
        if(appDeviceShareVos==null || appDeviceShareVos.isEmpty()){
            return null;
        }

        AppDeviceShareVo shareVo = appDeviceShareVos.get(0);
        AppDeviceShareDetailVo shareDetailVo = new AppDeviceShareDetailVo();
        shareDetailVo.setId(shareVo.getId());
        shareDetailVo.setDeviceId(shareVo.getDeviceId());
        shareDetailVo.setPhonenumber(shareVo.getPhonenumber());
        shareDetailVo.setPermission(shareVo.getPermission());

        Device device = deviceMapper.selectById(shareVo.getDeviceId());
        shareDetailVo.setDeviceName(device.getDeviceName());
        shareDetailVo.setDeviceImei(device.getDeviceImei());
        shareDetailVo.setDeviceMac(device.getDeviceMac());

        DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
        if(deviceType!=null){
            shareDetailVo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
        }
        shareDetailVo.setDevicePic(device.getDevicePic());
        shareDetailVo.setTypeName(deviceType.getTypeName());
        shareDetailVo.setBluetoothName(device.getBluetoothName());
        shareDetailVo.setDeviceStatus(device.getDeviceStatus());
        shareDetailVo.setSendMsg(device.getSendMsg());

        LambdaQueryWrapper<AppPersonnelInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(AppPersonnelInfo::getDeviceId, device.getId());
        List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
        if(appPersonnelInfoVos!=null && !appPersonnelInfoVos.isEmpty()){
            shareDetailVo.setPersonnelInfo(appPersonnelInfoVos.get(0));
        }

        return shareDetailVo;
    }
    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String tenantId, String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.DEVICE_SHARE_CODES_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("验证码失效");
        }
        return code.equals(smsCode);
    }
    public int deviceShare(AppDeviceShareBo bo) {
        boolean flag = validateSmsCode(AppLoginHelper.getTenantId(), bo.getPhonenumber(), bo.getSmsCode());
        if(!flag){
            throw new ServiceException("验证码错误");
        }

        Device device = deviceMapper.selectById(bo.getDeviceId());
        if(device==null){
            throw new ServiceException("设备不存在");
        }
        Long userId = AppLoginHelper.getUserId();
        LambdaQueryWrapper<AppDeviceShare> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AppDeviceShare::getDeviceId, bo.getDeviceId());
        lqw.eq(AppDeviceShare::getPhonenumber, bo.getPhonenumber());
        Long count = appDeviceShareMapper.selectCount(lqw);
        if(count>0){

            UpdateWrapper<AppDeviceShare> uw = new UpdateWrapper<>();
            uw.eq("device_id", bo.getDeviceId());
            uw.eq("phonenumber", bo.getPhonenumber());
            uw.set("permission", bo.getPermission());
            uw.set("update_by", userId);
            uw.set("update_time", new Date());

            return appDeviceShareMapper.update(uw);
        }else {
            AppDeviceShare appDeviceShare = new AppDeviceShare();
            appDeviceShare.setDeviceId(bo.getDeviceId());
            appDeviceShare.setPhonenumber(bo.getPhonenumber());
            appDeviceShare.setPermission(bo.getPermission());
            appDeviceShare.setCreateBy(userId);
            return appDeviceShareMapper.insert(appDeviceShare);
        }
    }

    public int remove(Long[] ids) {
        return appDeviceShareMapper.deleteByIds(Arrays.asList(ids));
    }
}
