package com.bonus.bracelet.service.impl;

import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.bonus.bracelet.mapper.BraceletMapper;
import com.bonus.bracelet.mapper.DeviceMapper;
import com.bonus.bracelet.service.IBraceletService;
import com.bonus.bracelet.service.IDeviceService;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.bracelet.vo.*;
import lombok.extern.slf4j.Slf4j;
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.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * BraceletServiceImpl 手环管理
 */
@Service(value = "IBraceletService")
@Slf4j
public class BraceletServiceImpl implements IBraceletService {

    @Resource(name = "BraceletMapper")
    private BraceletMapper braceletMapper;

    @Override
    public List<BraceletVo> getBraceletLists(BraceletVo data) {
        List<BraceletVo> list = new ArrayList<>();
        List<BraceletVo> listFilter =   new ArrayList<>();
        try {
            list = braceletMapper.getBraceletLists(data);
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getShPersonType()==0){
                    String name = braceletMapper.getBraceletPersonName(list.get(i).getShPersonId());
                    list.get(i).setShPersonName(name);
                }else if(list.get(i).getShPersonType()==1){
                    String name = braceletMapper.getDeviceLyPersonNameTemp(list.get(i).getShPersonId());
                    list.get(i).setShPersonName(name);
                }
                if(list.get(i).getShboxName()==null || list.get(i).getShboxName().equals("")){
                    list.get(i).setShboxName("未绑定");
                }
            }
                if(data.getShPersonName()!=null){
                    listFilter = list.stream().filter(bracelet -> data.getShPersonName().equals(bracelet.getShPersonName())).collect(Collectors.toList());
                }else{
                    listFilter = list;
                }

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return listFilter;
    }

    @Override
    public List<BraceletVo> getShBindLists(BraceletVo data) {
        List<BraceletVo> list = new ArrayList<>();
        List<BraceletVo> listFilter =   new ArrayList<>();
        try {
            list = braceletMapper.getShBindLists(data);
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getShPersonType()==0){
                    String name = braceletMapper.getBraceletPersonName(list.get(i).getShPersonId());
                    list.get(i).setShPersonName(name);
                }else if(list.get(i).getShPersonType()==1){
                    String name = braceletMapper.getDeviceLyPersonNameTemp(list.get(i).getShPersonId());
                    list.get(i).setShPersonName(name);
                }
            }
            if(data.getShPersonName()!=null){
                listFilter = list.stream().filter(bracelet -> data.getShPersonName().equals(bracelet.getShPersonName())).collect(Collectors.toList());
            }else{
                listFilter = list;
            }

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return listFilter;
    }

    @Override
    public List<BraceletVo> getShBindNoLists(BraceletVo data) {
        List<BraceletVo> list = new ArrayList<>();
        try {
            list = braceletMapper.getShBindNoLists(data);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    @Override
    public List<ShboxVo> getShboxLists(ShboxVo data) {
        List<ShboxVo> list = new ArrayList<>();
        try {
            list = braceletMapper.getShboxLists(data);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    @Override
    public List<ShboxVo> getShboxallLists(ShboxVo data) {
        List<ShboxVo> list = new ArrayList<>();
        List<ShboxVo> listFilter = new ArrayList<>();
        try {
            list = braceletMapper.getShboxallLists(data);
            if(data.getShboxStatus()==null){
                listFilter = list;
            }else if(data.getShboxStatus()==0){
                listFilter = list.stream().filter(bracelet -> (bracelet.getLyName()!=null && (!bracelet.getLyName().equals("")))).collect(Collectors.toList());
            }else {
                listFilter = list.stream().filter(bracelet -> (bracelet.getLyName()==null || bracelet.getLyName().equals(""))).collect(Collectors.toList());
            }
            for (int i = 0; i < listFilter.size(); i++) {
                if(listFilter.get(i).getLyName()==null || listFilter.get(i).getLyName().equals("")){
                    listFilter.get(i).setShboxStatus(1);
                }else{
                    listFilter.get(i).setShboxStatus(0);
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return listFilter;
    }

    @Override
    public List<ShboxVo> getShboxBindLists(ShboxVo data) {
        List<ShboxVo> list = new ArrayList<>();
        try {
            list = braceletMapper.getShboxBindLists(data);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    /**
     * 新增手环信息
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addSh(ShboxVo vo) {
        try {
            BraceletVo result = braceletMapper.isCodeExist(vo);
            if (result != null) {
                return AjaxResult.error("手环编号已存在");
            }
            if(vo.getShboxId()==null){
                vo.setShStatus(1);
            }else{
                vo.setShStatus(0);
            }
            int num =  braceletMapper.addSh(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环信息新增失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 新增设备属性信息
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addAttribute(AttributeVo vo) {
        try {
            AttributeVo result = braceletMapper.isDataCodeExist(vo);
            if (result != null) {
                return AjaxResult.error("该手环的级联编号已存在，请重新输入");
            }
            int num =  braceletMapper.addAttribute(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("该手环设备属性信息新增失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 新增手环箱子信息
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBox(ShboxVo vo) {
        try {
            ShboxVo result =  braceletMapper.isBoxCodeExistTemp(vo);
            if (result != null) {
                return AjaxResult.error("手环箱编号已存在");
            }
            ShboxVo result2 =  braceletMapper.isBoxNameExistTemp(vo);
            if (result2 != null) {
                return AjaxResult.error("手环箱名称已存在");
            }
            int num =  braceletMapper.addBox(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环箱信息新增失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 手环绑定选择页面绑定手环信息
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addShBind(ShboxVo vo) {
        try {
            if(vo.getShboxBindNum()>=vo.getShboxCapacity()){
                return AjaxResult.error("手环箱绑定数量已满，无法绑定");
            }
            int num =  braceletMapper.addShBind(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环绑定失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 解除绑定
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delSh(BraceletVo vo) {
        try {
            int result = braceletMapper.delSh(vo);
            if(result==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("解除绑定失败");
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editSh(ShboxVo vo) {
        try {
        if(vo.getShboxId()==null){
            vo.setShStatus(1);
        }else{
            vo.setShStatus(0);
        }
           int num =  braceletMapper.updateSh(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环信息修改失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editBox(ShboxVo vo) {
        try {
            ShboxVo result =  braceletMapper.isBoxCodeExist(vo);
            if (result != null) {
                return AjaxResult.error("手环箱编号已存在");
            }
            ShboxVo result2 =  braceletMapper.isBoxNameExist(vo);
            if (result2 != null) {
                return AjaxResult.error("手环箱名称已存在");
            }
            int num =  braceletMapper.updateShbox(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环箱信息修改失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delShById(int shId) {
        try {
            int result = braceletMapper.delShById(shId);
            if(result==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环信息删除失败");
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delShboxById(int shboxId) {
        try {
            int result = braceletMapper.delShboxById(shboxId);
            if(result==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("手环箱信息删除失败");
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 根据手环箱id获得详细信息
     * @param shboxId
     * @return
     */
    @Override
    public AjaxResult selectBoxById(Integer shboxId) {
        try {
            ShboxVo vo = braceletMapper.selectBoxById(shboxId);
            return AjaxResult.success(vo);
        } catch (Exception e) {
            log.error("手环箱详情", e);
            return AjaxResult.error();
        }
    }

    /**
     * 根据手环箱id获得刷新详细信息
     * @param shboxId
     * @return
     */
    @Override
    public AjaxResult selectBoxNewById(Integer shboxId) {
        Map<String,Integer> map= Maps.newHashMap();
        try {
            ShboxVo vo = braceletMapper.selectBoxNewById(shboxId);
            if(!Objects.isNull(vo)){
                Integer  num=vo.getShboxCapacity()-vo.getShboxBindNum();
                map.put("boxNum",num);
            }else{
                map.put("boxNum",0);
                return AjaxResult.error();
            }
            return AjaxResult.success(map);
        } catch (Exception e) {
            map.put("boxNum",0);
            log.error(e.toString(), e);
            return AjaxResult.error();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult bindSh(int shboxId,int[] shIds) {
        if(shIds.length==0){
            return AjaxResult.error("请至少选择一个要绑定的手环");
        }
        try {
            for (int i = 0; i < shIds.length; i++) {
                int shId = shIds[i];
                braceletMapper.bindSh(shboxId,shId);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("绑定失败");
        }
        return AjaxResult.success("绑定成功");
    }
}
