package com.mortals.xhx.module.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.DeviceStatusEnum;
import com.mortals.xhx.common.code.EnabledEnum;
import com.mortals.xhx.common.pdu.LoginForm;
import com.mortals.xhx.common.pdu.device.DeviceReq;
import com.mortals.xhx.feign.device.IDeviceFeign;
import com.mortals.xhx.module.device.model.DeviceQuery;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.device.dao.DeviceDao;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

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

/**
 * DeviceService
 * 设备管理 service实现
 *
 * @author zxfei
 * @date 2023-05-22
 */
@Service("deviceService")
@Slf4j
public class DeviceServiceImpl extends AbstractCRUDServiceImpl<DeviceDao, DeviceEntity, Long> implements DeviceService {

    @Autowired
    private IDeviceFeign deviceFeign;
    @Value("${token.loginName:'admin'}")
    private String loginName;
    @Value("${token.password:'admin'}")
    private String password;

    @Override
    protected void validData(DeviceEntity entity, Context context) throws AppException {
        super.validData(entity, context);
        entity.setDeviceCode(entity.getDeviceMac());
    }

    @Override
    protected void saveAfter(DeviceEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);
        //todo 通知设备管理系统
        String token = getToken();
        DeviceReq deviceReq = new DeviceReq();
        deviceReq.setReceiveMethod(1);
        deviceReq.setDeviceName(entity.getDeviceName());
        deviceReq.setDeviceCode(entity.getDeviceCode());
        deviceReq.setProductCode(entity.getProductCode());
        deviceReq.setIp(entity.getIp());
        deviceReq.setPort(entity.getPort());
        deviceReq.setSiteId(1L);
        deviceReq.setSiteCode("511500000000-0001");
        deviceReq.setSiteName("宜宾市民中心");
        deviceReq.setLeadingOfficial(entity.getLeadingOfficial());
        deviceReq.setLeadingOfficialTelephone(entity.getLeadingOfficialTelephone());
        deviceReq.setSource(1);
        deviceReq.setDeviceStatus(entity.getDeviceStatus());
        Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
        log.info("添加结果：{}", JSON.toJSONString(rest));
    }


    @Override
    protected void updateAfter(DeviceEntity entity, Context context) throws AppException {
        super.updateAfter(entity, context);
        //todo 通知设备管理系统
        String token = getToken();
        DeviceReq deviceReq = new DeviceReq();
        deviceReq.setReceiveMethod(2);
        deviceReq.setDeviceName(entity.getDeviceName());
        deviceReq.setDeviceCode(entity.getDeviceCode());
        deviceReq.setProductCode(entity.getProductCode());
        deviceReq.setIp(entity.getIp());
        deviceReq.setPort(entity.getPort());
        deviceReq.setSiteId(1L);
        deviceReq.setSiteCode("511500000000-0001");
        deviceReq.setSiteName("宜宾市民中心");
        deviceReq.setLeadingOfficial(entity.getLeadingOfficial());
        deviceReq.setLeadingOfficialTelephone(entity.getLeadingOfficialTelephone());
        deviceReq.setSource(1);
        deviceReq.setDeviceStatus(entity.getDeviceStatus());
        Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
        log.info("更新结果：{}", JSON.toJSONString(rest));
    }

    @Override
    public void active(String deviceCode, Context context) {
        DeviceEntity deviceEntity = this.selectOne(new DeviceQuery().deviceCode(deviceCode));
        if (ObjectUtils.isEmpty(deviceEntity)) throw new AppException("当前设备不存在！");
        if (deviceEntity.getDeviceStatus() > DeviceStatusEnum.未激活.getValue())
            throw new AppException("当前设备已激活！");
        deviceEntity.setDeviceStatus(DeviceStatusEnum.离线.getValue());
        deviceEntity.setEnabled(EnabledEnum.启用.getValue());
        this.getDao().update(deviceEntity);

        String token = getToken();
        DeviceReq deviceReq = new DeviceReq();
        deviceReq.setReceiveMethod(4);
        deviceReq.setDeviceCode(deviceCode);
        Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
        log.info("激活结果：{}", JSON.toJSONString(rest));
    }

    @Override
    public void deviceEnabled(Long id, Integer enabled, Context context) {
        DeviceEntity deviceEntity = this.get(id, context);
        if (ObjectUtils.isEmpty(deviceEntity)) throw new AppException("当前设备不存在！");
        deviceEntity.setEnabled(enabled);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(getContextUserId(context));
        this.getDao().update(deviceEntity);
        String token = getToken();
        DeviceReq deviceReq = new DeviceReq();
        deviceReq.setReceiveMethod(5);
        deviceReq.setDeviceCode(deviceEntity.getDeviceCode());
        Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
        log.info("激活结果：{}", JSON.toJSONString(rest));
    }

    @Override
    protected void removeBefore(Long[] ids, Context context) throws AppException {
        super.removeBefore(ids, context);
        String token = getToken();
        List<DeviceEntity> deviceEntities = this.get(ids, context);
        for (DeviceEntity entity : deviceEntities) {
            DeviceReq deviceReq = new DeviceReq();
            deviceReq.setReceiveMethod(3);
            deviceReq.setDeviceCode(entity.getDeviceCode());
            Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
            log.info("删除结果：{}", JSON.toJSONString(rest));
        }

    }

    private String getToken() {
        LoginForm loginForm = new LoginForm();
        loginForm.setLoginName(loginName);
        loginForm.setPassword(password);
        Rest<String> rest = deviceFeign.getToken(loginForm);
        String token = rest.getData();
        return token;
    }
}