package com.mvc.service.wx;

import com.mvc.dao.WxUserDevicesMapper;
import com.mvc.entity.WxUserDevices;
import com.mvc.entity.WxUserDevicesExample;
import com.mvc.model.DeviceAccModel;
import com.mvc.model.wx.WxUserDevicesModel;
import com.mvc.service.taizhang.DeviceAccService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class WxUserDevicesService {
    @Resource
    private WxUserDevicesMapper wxUserDevicesMapper;

    @Resource
    private DeviceAccService deviceAccService;

    public WxUserDevicesModel saveWxUserDevices(WxUserDevicesModel model) {
        model.setBindTime(new Date());
        WxUserDevices wxUserDevices = new WxUserDevices();
        BeanUtils.copyProperties(model, wxUserDevices);
        wxUserDevicesMapper.insert(wxUserDevices);
        model.setId(wxUserDevices.getId());
        return model;
    }

    public WxUserDevicesModel updateWxUserDevices(WxUserDevicesModel model) {
        WxUserDevices cell = wxUserDevicesMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, cell);
        wxUserDevicesMapper.updateByPrimaryKey(cell);
        return model;
    }

    public int deleteWxUserDevices(int id) {
        int i = wxUserDevicesMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 根据userProfileId获取列表
     * @param userProfileId
     * @return
     */
    public List<WxUserDevicesModel> findWxUserDevicesModelsByUserProfileId(Integer userProfileId) {
        List<WxUserDevicesModel> resList = new ArrayList<>();
        WxUserDevicesExample example = new WxUserDevicesExample();
        WxUserDevicesExample.Criteria criteria = example.createCriteria();
        criteria.andUserProfileIdEqualTo(userProfileId);
        List<WxUserDevices> wxUserDevicess = wxUserDevicesMapper.selectByExample(example);
        for(WxUserDevices devices : wxUserDevicess){
            WxUserDevicesModel model = new WxUserDevicesModel();
            BeanUtils.copyProperties(devices,model);
            resList.add(model);
        }
        return resList;
    }

    public String checkValid(WxUserDevicesModel model){
        DeviceAccModel accModel = deviceAccService.findDeviceAccBysn(model.getDeviceCode());
        if(accModel==null){
            return String.format("[%s]设备台账不存在",model.getDeviceCode());
        }
        List<WxUserDevicesModel> devicesModels = findWxUserDevicesModelsByUserProfileId(model.getUserProfileId());
        Optional<WxUserDevicesModel> optional = devicesModels.stream().filter(s->s.getDeviceCode().equals(model.getDeviceCode())).findFirst();
        if(optional.isPresent()){
            return String.format("[%s]设备已经绑定,请勿重复绑定",model.getDeviceCode());
        }
        return null;
    }
}
