package com.zcxk.service;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcxk.common.HttpRequest;
import com.zcxk.common.JacksonUtil;
import com.zcxk.dao.DeviceSetupMethodMapper;
import com.zcxk.dto.SetupMethod;
import com.zcxk.entity.*;
import com.zcxk.model.LoginUser;
import com.zcxk.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

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

/**
 * 参数设置指令Service接口
 *
 * @author: WYY
 * @date 2021-05-10 14:39
 */
@Service
public class DeviceSetupMethodService extends ServiceImpl<DeviceSetupMethodMapper, DeviceSetupMethodEntity> {

    @Resource
    private DeviceSetupMethodMapper deviceSetupMethodMapper;
    @Autowired
    private DeviceSetupRecordService deviceSetupRecordService;
    @Autowired
    private DeviceService deviceService;
    @Value("${send.setsetup.url}")
    private  String setSetupUrl;
    @Autowired
    private ParmSettingService parmSettingService;
    @Autowired
    private DeviceTypeService deviceTypeService;

    /**
     * 查列表
     */
    public List<DeviceSetupMethodEntity> findList(DeviceSetupMethodEntity deviceSetupMethodEntity) {
        return deviceSetupMethodMapper.findList(deviceSetupMethodEntity);
    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delDeviceSetupMethodByIds(Long[] ids) {

        return this.removeByIds(Arrays.asList(ids));

    }

    /**
     * 单个删除
     */
    public boolean delDeviceSetupMethodById(Long id) {


        return this.removeById(id);

    }

    /**
     * 保存
     */
    public boolean addDeviceSetupMethod(DeviceSetupMethodEntity deviceSetupMethod) {

        if (this.save(deviceSetupMethod)) {
            return true;
        }
        return false;
    }

    /**
     * 修改根居ID
     */
    public boolean updateDeviceSetupMethodById(DeviceSetupMethodEntity deviceSetupMethod) {

        if (this.updateById(deviceSetupMethod)) {
            return true;
        }
        return false;
    }

    /**
     * 根居ID获取对象
     */
    public DeviceSetupMethodEntity findDeviceSetupMethodById(Long id) {
        return deviceSetupMethodMapper.findDeviceSetupMethodById(id);
    }

    /**
     * 添加设备指令
     *
     * @param type
     * @param deviceId
     * @param attributeId
     * @param parms
     * @return
     */
    public boolean setSetupForDevice(Integer type, Long  sceneId,Long deviceId, Long attributeId, String parms) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        String methodParms = "";
        //查询设备
        DeviceEntity deviceEntity = deviceService.selectById(deviceId);
        if (deviceEntity == null) {
            return false;
        }
        //查询操作方法
        DeviceSetupMethodEntity info = new DeviceSetupMethodEntity();
        info.setType(type);
        info.setDeviceId(deviceId);
        info.setAttributeId(attributeId);
        List<DeviceSetupMethodEntity> deviceSetupMethodEntities = deviceSetupMethodMapper.findList(info);
        //查询到操作方法后执行操作
        if (deviceSetupMethodEntities.size() > 0) {
            //查询设备型号
            DeviceTypeEntity deviceTypeEntity = deviceTypeService.findDeviceTypeById(Long.valueOf(deviceEntity.getDeviceTypeId()));
            String method = deviceSetupMethodEntities.get(0).getMethod();
            methodParms = deviceSetupMethodEntities.get(0).getParams();
            SetupMethod setupMethod = new SetupMethod();
            setupMethod.setMethod(method);
            //setupMethod.setDeviceId("912cf9e7-8557-4792-a2f9-27ba72bbcb89");
            setupMethod.setUnitIdentifier(deviceEntity.getDeviceCode());
            setupMethod.setDeviceMode(deviceTypeEntity.getDeviceMode());
            setupMethod.setDeviceType(deviceTypeEntity.getDeviceType());
            setupMethod.setManufacturer(deviceTypeEntity.getManufacturerId());
            setupMethod.setReceiveTime(new Date());
            //封装指令
            String[] parm = parms.split(",");
            ObjectMapper mapper = new ObjectMapper();
            for (String item : parm) {
                methodParms = methodParms.replaceFirst("%", item);
            }
            JsonNode node = null;
            try {
                node = mapper.readTree(methodParms);
            } catch (IOException e) {
                return false;
            }
            setupMethod.setParams(node);
            String result = "";
            try {
                result = HttpRequest.doPost(setSetupUrl, JacksonUtil.obj2String(setupMethod));
            } catch (IOException e) {
                return false;
            }

            //添加操作记录
            DeviceSetupRecordEntity deviceSetupRecordEntity = new DeviceSetupRecordEntity();
            deviceSetupRecordEntity.setType(type);
            deviceSetupRecordEntity.setAttributeId(attributeId);
            deviceSetupRecordEntity.setDeviceId(deviceId);
            deviceSetupRecordEntity.setCreateBy(currentUser.getUsername());
            deviceSetupRecordEntity.setUpdateBy(currentUser.getUsername());

            try {
                JsonNode resultNode = mapper.readTree(result);
                if (resultNode.get("status").toString().equals("0")) {
                    deviceSetupRecordEntity.setState(1);
                } else {
                    deviceSetupRecordEntity.setState(2);
                }
            } catch (IOException e) {
                return false;
            }
            deviceSetupRecordEntity.setStatus(1);
            deviceSetupRecordEntity.setDateCreate(new Date());
            deviceSetupRecordEntity.setDateUpdate(new Date());
            deviceSetupRecordEntity.setSceneId(sceneId);
            deviceSetupRecordEntity.setParams(methodParms);
            deviceSetupRecordEntity.setTenantId(currentUser.getTenantId());
            deviceSetupRecordEntity.setSetupMethodId(deviceSetupMethodEntities.get(0).getId());

            deviceSetupRecordService.addDeviceSetupRecord(deviceSetupRecordEntity);
        }
        return true;
    }
    /**
     * 校验密码
     * @param password
     * @return
     */
    public Boolean checkPassword(String password) {
        //校验密钥
        LoginUser currentUser = UserUtil.getCurrentUser();
        ParmSettingEntity parmSettingEntity = new ParmSettingEntity();
        parmSettingEntity.setEnableState(1);
        parmSettingEntity.setParmType(1);
        if(currentUser!=null&&currentUser.getCompanyId()!=null) {
            parmSettingEntity.setCompanyOrgId(Long.valueOf(currentUser.getCompanyId()));
        }
        parmSettingEntity.setTenantId(currentUser.getTenantId());
        List<ParmSettingEntity> parmSettingEntities = parmSettingService.findList(parmSettingEntity);
        if (parmSettingEntities.size() == 0) {
            return false;
        }
        if (password.equals(parmSettingEntities.get(0).getParmValue())) {
            return true;
        } else {
            return false;
        }
    }
}
