package tech.glinfo.enbao.modules.sh.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.modules.appuser.entity.AppUserEntity;
import tech.glinfo.enbao.modules.service.BaiduApiService;
import tech.glinfo.enbao.modules.sh.dao.OtherShDeviceDao;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceDataEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShInstructionParsingEntity;
import tech.glinfo.enbao.modules.sh.entity.ShProductEntity;
import tech.glinfo.enbao.modules.sh.form.ShDeviceForm;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.ShDeviceDataService;
import tech.glinfo.enbao.modules.sh.service.ShInstructionParsingService;
import tech.glinfo.enbao.modules.sh.service.ShProductService;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Service("otherShDeviceService")
public class OtherShDeviceServiceImpl extends ServiceImpl<OtherShDeviceDao, ShDeviceEntity> implements OtherShDeviceService {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ShDeviceDataService shDeviceDataService;

    @Autowired
    private ShInstructionParsingService shInstructionParsingService;

    @Autowired
    private BaiduApiService baiduApiService;


    private static final String GROUPID = "facelock";//

    //发布
    @Override
    public R save(Map<String, Object> params, AppUserEntity user) {
        String mac = (String) params.get("mac");
        Integer familyId = (Integer) params.get("familyId");
        if (StringUtils.isBlank(mac, familyId)) {
            return R.error();
        }
        int count = this.count(new QueryWrapper<ShDeviceEntity>().eq("mac", mac));
        if (count > 0) {
            return R.error();
        }
        //保存MAC地址
        redisUtils.set("device:save:" + mac, user.getId() + "-" + familyId);
        return R.ok();
    }

    @Override
    public R list(Map<String, Object> params, AppUserEntity user) {
        String familyId = (String)params.get("familyId");
        String roomId = (String)params.get("roomId");
        List<ShDeviceEntity> list = this.list(new QueryWrapper<ShDeviceEntity>()
                        .eq(StringUtils.isNotBlank(familyId), "family_id", familyId)
                        .eq(StringUtils.isNotBlank(roomId), "room_id", roomId)
                        .orderByDesc("id"));
       /* IPage<ShDeviceEntity> page = this.page(
                new Query<ShDeviceEntity>().getPage(params),
                new QueryWrapper<ShDeviceEntity>()
                        .eq(StringUtils.isNotBlank(familyId), "family_id", familyId)
                        .eq(StringUtils.isNotBlank(roomId), "room_id", roomId)
                        .orderByDesc("id")
        );
        Map<String, Object> map = new HashMap<>();
        map.put("page", new PageUtils(page));*/
        return R.ok().put("data", list);
    }

    @Override
    public R delete(Map<String, Object> params, AppUserEntity user) {
        Integer id = (Integer) params.get("id");
        if (id == null) {
            return R.error("缺少参数");
        }
        ShDeviceEntity entity = this.getById(id);
        if (!user.getId().equals(entity.getUserId())) {
            return R.error("不能删除别人的设备");
        }
        if (entity.getNumbering().substring(0, 3).equals("011")) {
            if (entity.getSpareTwo() != null) {
                String[] faceParam1 = entity.getSpareTwo().split(",");
                baiduApiService.delUser(faceParam1[0], faceParam1[1], faceParam1[2]);
            }
        }

        return this.removeById(id) ? R.ok() : R.error("操作失败");
    }

    @Override
    public R getDeviceId(String numbering) {
        ShDeviceEntity entity = this.getOne(new QueryWrapper<ShDeviceEntity>().eq("numbering", numbering).last("LIMIT 1"));
        if (entity == null) {
            return R.error("设备不存在！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("deviceId", entity.getId());
        return R.ok().put("data", map);
    }

    @Override
    public R updateDeviceData(String value, Integer deviceId) {
        ShDeviceDataEntity entity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", deviceId));
        ShDeviceDataEntity dataEntity = new ShDeviceDataEntity();
        dataEntity.setDeviceId(deviceId);
        dataEntity.setValue(value);
//        dataEntity.setUpdateTime(new Date());
        if (entity == null) {
            shDeviceDataService.save(dataEntity);
        }else {
            dataEntity.setId(entity.getId());
            shDeviceDataService.updateById(dataEntity);
        }
        return R.ok();
    }

    @Override
    public R updateFilterDeviceData(Map<String, Object> map, Integer deviceId) {
        ShDeviceDataEntity entity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", deviceId));
        ShDeviceDataEntity dataEntity = new ShDeviceDataEntity();
        dataEntity.setDeviceId(deviceId);
        if (entity == null) {
            map.put("light", "0");
            dataEntity.setValue(JSON.toJSONString(map));
            shDeviceDataService.save(dataEntity);
        }else {
            dataEntity.setId(entity.getId());
            JSONObject jsonObj = new JSONObject(entity.getValue());
            map.put("light", jsonObj.has("light")?jsonObj.getString("light"):"0");
            dataEntity.setValue(JSON.toJSONString(map));
            shDeviceDataService.updateById(dataEntity);
        }
        return R.ok();
    }

    @Override
    public R info(String id) {
        ShDeviceEntity entity = this.getById(id);
        if (entity == null) {
            return R.error("设备不存在");
        }
        ShDeviceDataEntity dataEntity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id",  entity.getId()));
        return R.ok().put("device", entity).put("datas", dataEntity);
    }

    @Override
    public ShDeviceEntity deviceInfo(Map<String, Object> params) {
        String id = (String) params.get("id");
        String numbering = (String) params.get("numbering");
        ShDeviceEntity entity = null;
        if (StringUtils.isNotEmpty(id)) {
            entity = this.getById(id);
        } else if (StringUtils.isNotEmpty(numbering)) {
            entity = this.getOne(new QueryWrapper<ShDeviceEntity>().eq("numbering", numbering));
        }

        return entity;
    }

    @Override
    public List<ShInstructionParsingEntity> getDeviceInstructionList(Integer productId, String cmd) {
        return shInstructionParsingService.list(new QueryWrapper<ShInstructionParsingEntity>().eq("product_id", productId).eq("cmd", cmd).orderByAsc("sort"));
    }

    @Override
    public ShDeviceDataEntity getDeviceDataByNumbering(String numbering) {
        return this.baseMapper.getDeviceDataByNumbering(numbering);
    }

    @Override
    public List<ShDeviceEntity> getDeviceByFlag(Integer userId) {
        return this.baseMapper.getDeviceByFlag(userId);
    }

}
