package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.demo.RemoteTsdbProxyService;
import com.usky.demo.domain.DataTypeEnum;
import com.usky.demo.domain.Fields;
import com.usky.demo.domain.FieldsVO;
import com.usky.demo.domain.SuperTableDTO;
import com.usky.iot.domain.DmpProductAttribute;
import com.usky.iot.domain.DmpProductInfo;
import com.usky.iot.mapper.DmpProductAttributeMapper;
import com.usky.iot.service.DmpProductAttributeService;
import com.usky.iot.service.vo.DmpProductAttributeRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.Remote;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 产品属性表 服务实现类
 * </p>
 *
 * @author ya
 * @since 2022-10-08
 */
@Service
public class DmpProductAttributeServiceImpl extends AbstractCrudService<DmpProductAttributeMapper, DmpProductAttribute> implements DmpProductAttributeService {
    @Autowired
    private RemoteTsdbProxyService remoteTsdbProxyService;
    @Autowired
    private DmpProductAttributeMapper dmpProductAttributeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(DmpProductAttribute dmpProductAttribute) {
        if (checkNameUnique(dmpProductAttribute)){
            throw new BusinessException("新增产品属性信息'" + dmpProductAttribute.getAttributeName() + "'失败，产品信息已存在");
        }
        dmpProductAttribute.setDeleteFlag(0);
        dmpProductAttribute.setCreatedBy(SecurityUtils.getUsername());
        dmpProductAttribute.setCreatedTime(new Date());
        dmpProductAttribute.setTenantId(SecurityUtils.getTenantId());
        this.save(dmpProductAttribute);

        SuperTableDTO superTableDTO = new SuperTableDTO();
        String superTableName = "super_"+dmpProductAttributeMapper.getSuperTableName(dmpProductAttribute.getProductId());
        superTableDTO.setSuperTableName(superTableName);

        int data_type = dmpProductAttribute.getDataType();
        String dataType = "";
        if(data_type == 1){
            dataType = "INT";
        }else if(data_type == 2){
            dataType = "VARCHAR";
        }else if(data_type == 3){
            dataType = "BOOL";
        }else if(data_type == 4) {
            dataType = "DOUBLE";
        }
        FieldsVO fieldsVO = new FieldsVO(dmpProductAttribute.getAttributeCode(), dataType, dmpProductAttribute.getAttributeLength());
        superTableDTO.setFields(FieldsVO.toFields(fieldsVO));
        //超级表新增字段
        remoteTsdbProxyService.addSuperTableColumn(superTableDTO);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(DmpProductAttribute dmpProductAttribute) {
        dmpProductAttribute.setUpdatedTime(new Date());
        if (checkNameUnique(dmpProductAttribute)){
            throw new BusinessException("新增产品属性信息'" + dmpProductAttribute.getAttributeName() + "'失败，产品信息已存在");
        }
        this.updateById(dmpProductAttribute);

        SuperTableDTO superTableDTO = new SuperTableDTO();
        String superTableName = "super_"+dmpProductAttributeMapper.getSuperTableName(dmpProductAttribute.getProductId());
        superTableDTO.setSuperTableName(superTableName);

        int data_type = dmpProductAttribute.getDataType();
        String dataType = "";
        if(data_type == 1){
            dataType = "INT";
        }else if(data_type == 2){
            dataType = "VARCHAR";
        }else if(data_type == 3){
            dataType = "BOOL";
        }else if(data_type == 4) {
            dataType = "DOUBLE";
        }
        FieldsVO fieldsVO = new FieldsVO(dmpProductAttribute.getAttributeCode(), dataType, dmpProductAttribute.getAttributeLength());
        superTableDTO.setFields(FieldsVO.toFields(fieldsVO));
        //超级表删除字段
        remoteTsdbProxyService.dropSuperTableColumn(superTableDTO);
        //超级表新增字段
        remoteTsdbProxyService.addSuperTableColumn(superTableDTO);
    }

    @Override
    public boolean checkNameUnique(DmpProductAttribute dmpProductAttribute) {
        Integer id = null == dmpProductAttribute.getId() ? -1 : dmpProductAttribute.getId();
        LambdaQueryWrapper<DmpProductAttribute> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DmpProductAttribute::getAttributeName,dmpProductAttribute.getAttributeName())
                .eq(DmpProductAttribute::getTenantId,SecurityUtils.getTenantId())
                .eq(DmpProductAttribute::getDeleteFlag,0);
        DmpProductAttribute one = this.getOne(queryWrapper);
        return null != one && !Objects.equals(one.getId(), id);
    }

    @Override
    public CommonPage<DmpProductAttribute> page(DmpProductAttributeRequest paRequest) {
        IPage<DmpProductAttribute> page = new Page<>(paRequest.getCurrent(), paRequest.getSize());
        LambdaQueryWrapper<DmpProductAttribute> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .eq(StringUtils.isNotBlank(paRequest.getAttributeName()),DmpProductAttribute::getAttributeName,paRequest.getAttributeName())
                .eq(null != paRequest.getProductId(),DmpProductAttribute::getProductId,paRequest.getProductId())
                .eq(DmpProductAttribute::getTenantId,SecurityUtils.getTenantId())
                .eq(DmpProductAttribute::getDeleteFlag,0);
        page = this.page(page,lambdaQuery);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public boolean remove(Integer id) {
        DmpProductAttribute dmpProductAttribute = this.getById(id);
        Optional.ofNullable(dmpProductAttribute).orElseThrow(() -> new BusinessException("产品不存在"));
        dmpProductAttribute.setDeleteFlag(1);

        SuperTableDTO superTableDTO = new SuperTableDTO();
        String superTableName = "super_"+dmpProductAttributeMapper.getSuperTableName(dmpProductAttribute.getProductId());
        superTableDTO.setSuperTableName(superTableName);

        FieldsVO fieldsVO = new FieldsVO(dmpProductAttribute.getAttributeCode(), "", dmpProductAttribute.getAttributeLength());
        superTableDTO.setFields(FieldsVO.toFields(fieldsVO));
        //超级表删除字段
        remoteTsdbProxyService.dropSuperTableColumn(superTableDTO);

        return this.updateById(dmpProductAttribute);
    }

    @Override
    public void  updateBatchBind(List<Integer> ids) {
        LambdaUpdateWrapper<DmpProductAttribute> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper
                .set(DmpProductAttribute::getBindStatus,2)
                .in(DmpProductAttribute::getId,ids);
        this.update(updateWrapper);
    }
}
