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.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.modules.appuser.entity.AppUserEntity;
import tech.glinfo.enbao.modules.sh.dao.OtherShDlinkDao;
import tech.glinfo.enbao.modules.sh.dao.ShDlinkDao;
import tech.glinfo.enbao.modules.sh.entity.ShDlinkDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDlinkEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.form.ShDlinkForm;
import tech.glinfo.enbao.modules.sh.service.OtherShDlinkService;
import tech.glinfo.enbao.modules.sh.service.ShDlinkDeviceService;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lyt
 * @date 2021/8/31 16:16
 */
@Service("otherShDlinkService")
public class OtherShDlinkServiceImpl extends ServiceImpl<OtherShDlinkDao, ShDlinkEntity> implements OtherShDlinkService {

    @Autowired
    private ShDlinkDeviceService shDlinkDeviceService;

    @Autowired
    private RedisUtils redisUtils;

    private static Map<String, String> cmd = new HashMap<>();

    static {
        cmd.put("01cmd", "13");
        cmd.put("01controller1", "00");
        cmd.put("01controller2", "01");
        cmd.put("02cmd", "18");
        cmd.put("03cmd", "18");
        cmd.put("03controller1", "0100000000000001");
        cmd.put("03controller2", "0000000000000001");
        cmd.put("05cmd", "18");
        cmd.put("05controller1", "0164000000000000");
        cmd.put("05controller2", "0100000000000000");
    }

    // 保存房源介绍
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R save(ShDlinkForm form, AppUserEntity user) {
        ShDlinkEntity dlinkEntity = new ShDlinkEntity();

        try {
            BeanUtils.copyProperties(dlinkEntity, form);
            if (form.getId() != null) {
                ShDlinkEntity dlinkEntity1 = this.getById(form.getId());
                redisUtils.delete("device:dlink:" + dlinkEntity1.getStart() + "-" + dlinkEntity1.getEnd() + ":" + form.getDeviceId());
                shDlinkDeviceService.remove(new QueryWrapper<ShDlinkDeviceEntity>().eq("dlink_id", form.getId()));

            }
            if (form.getHouseId() == null) {
                dlinkEntity.setUserId(user.getId());
            }
            this.saveOrUpdate(dlinkEntity);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < form.getDevices().size(); i++) {
                ShDlinkDeviceEntity deviceEntity = new ShDlinkDeviceEntity();
                BeanUtils.copyProperties(deviceEntity, form.getDevices().get(i));
                deviceEntity.setDlinkId(dlinkEntity.getId());

                String numbering = form.getDevices().get(i).getNumbering().substring(1, 3);
                ProtocolContent protocol = new ProtocolContent();
                protocol.setReceiveId(form.getDevices().get(i).getNumbering());
                protocol.setDeviceType(numbering);
                protocol.setCmd(cmd.get(numbering + "cmd"));
                //开关的指令
                if (numbering.equals("02")) {
                    String s1 = form.getDevices().get(i).getStatus() == 1 ? "01" : "00";
                    String s2 = form.getDevices().get(i).getStatus2() == 1 ? "01" : "00";
                    protocol.setContent(s1 + s2 + "000000000003");
                } else {
                    protocol.setContent(cmd.get(numbering + "controller" + form.getDevices().get(i).getStatus()));
                }
                String json = JSON.toJSONString(protocol);
                deviceEntity.setCmd(json);
                shDlinkDeviceService.save(deviceEntity);
                sb.append(json);
                if (i != form.getDevices().size() - 1) {
                    sb.append("-");
                }

            }

            // 场景关联开启的话保存，否在删除
            if (form.getStatus() == 1) {
                redisUtils.set("device:dlink:" + form.getStart() + "-" + form.getEnd() + ":" + form.getDeviceId(), sb.toString());
            }

        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return R.error("未知异常，请联系管理员！");
        }
        return R.ok();
    }

    @Override
    public R info(Integer id) {
        ShDlinkEntity dlinkEntity = this.getById(id);
        List<ShDlinkDeviceEntity> list = shDlinkDeviceService.list(new QueryWrapper<ShDlinkDeviceEntity>().eq("dlink_id", dlinkEntity.getId()));
        return R.ok().put("dlink", dlinkEntity).put("list", list);
    }

    @Override
    public ShDlinkEntity checkTime(String time, Integer deviceId) {
        return this.baseMapper.checkTime(time, deviceId);
    }


    @Override
    public R list(Integer userId) {
        List<ShDlinkEntity> list = this.list(new QueryWrapper<ShDlinkEntity>().eq("user_id", userId).orderByDesc("id"));
        return R.ok().put("data", list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delete(Integer id) {
        ShDlinkEntity dlinkEntity = this.getById(id);
        redisUtils.delete("device:dlink:" + dlinkEntity.getStart() + "-" + dlinkEntity.getEnd() + ":" + dlinkEntity.getDeviceId());
        shDlinkDeviceService.remove(new QueryWrapper<ShDlinkDeviceEntity>().eq("dlink_id", dlinkEntity.getId()));
        this.removeById(id);
        return R.ok();
    }

    @Override
    public R updateStatus(Integer id, Integer status) {
        ShDlinkEntity dlinkEntity1 = new ShDlinkEntity();
        dlinkEntity1.setId(id);
        dlinkEntity1.setStatus(status);
        this.updateById(dlinkEntity1);
        return R.ok();
    }

    @Override
    public R dlinkDeviceList(Integer id) {
        return R.ok().put("list", this.baseMapper.dlinkDeviceList(id));
    }


}
