package com.fjhx.iot.service.tda.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.iot.entity.tda.dto.TdaApplicationDto;
import com.fjhx.iot.entity.tda.dto.TdaApplicationSelectDto;
import com.fjhx.iot.entity.tda.po.TdaApplication;
import com.fjhx.iot.entity.tda.vo.TdaApplicationVo;
import com.fjhx.iot.mapper.tda.TdaApplicationMapper;
import com.fjhx.iot.service.tda.TdaApplicationService;
import com.fjhx.iot.utils.IoTDAUtil;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 行业管理 服务实现类
 * </p>
 *
 * @author zlj
 * @since 2023-03-21
 */
@Service
public class TdaApplicationServiceImpl extends ServiceImpl<TdaApplicationMapper, TdaApplication> implements TdaApplicationService {

    @Override
    public Page<TdaApplicationVo> getPage(TdaApplicationSelectDto dto) {
        IWrapper<TdaApplication> wrapper = getWrapper();
        wrapper.keyword(dto,
                new SqlField("tc.name"),
                new SqlField("ta.app_name")
        );

        wrapper.orderByDesc("ta", TdaApplication::getId);
        Page<TdaApplicationVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

    @Override
    public TdaApplicationVo detail(Long id) {
        TdaApplication TdaApplication = this.getById(id);
        TdaApplicationVo result = BeanUtil.toBean(TdaApplication, TdaApplicationVo.class);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TdaApplicationDto tdaApplicationDto) {
        // 华为ioDta添加资源空间
        String appId = IoTDAUtil.addApplication(tdaApplicationDto.getTdaConfigId(), tdaApplicationDto.getAppName());
        tdaApplicationDto.setAppId(appId);
        this.save(tdaApplicationDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        // 华为ioDta删除资源空间
        TdaApplication tdaApplication = getById(id);
        IoTDAUtil.deleteApplication(tdaApplication.getTdaConfigId(), tdaApplication.getAppId());
        this.removeById(id);
    }

}
