package com.fjhx.service.tda.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.entity.tda.TdaApplication;
import com.fjhx.entity.tda.TdaProduct;
import com.fjhx.mapper.tda.TdaApplicationMapper;
import com.fjhx.params.tda.TdaApplicationVo;
import com.fjhx.service.tda.TdaApplicationService;
import com.fjhx.service.tda.TdaProductService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.IoTDAUtil;
import com.fjhx.utils.UserClientUtil;
import com.fjhx.utils.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-07-21
 */
@Service
public class TdaApplicationServiceImpl extends ServiceImpl<TdaApplicationMapper, TdaApplication> implements TdaApplicationService {

    @Lazy
    @Autowired
    private TdaProductService tdaProductService;

    @Override
    public Page<Map<String, Object>> getPage(Map<String, String> condition) {

        QueryWrapper<TdaApplication> wrapper = Wrappers.query();

        WrapperUtil.init(condition, wrapper)
                .keyword("app_name", "app_id")
                .createTimeDesc();

        Page<Map<String, Object>> mapPage = pageMaps(condition, wrapper);
        List<Map<String, Object>> records = mapPage.getRecords();

        // 赋值用户名称
        UserClientUtil.setUserName(records, "createUser", "createUserName");
        return mapPage;
    }

    @Override
    public void add(TdaApplicationVo tdaApplicationVo) {
        String appName = tdaApplicationVo.getAppName();
        Assert.notEmpty(appName, "行业名称不能为空");

        // 华为ioDta添加资源空间
        String appId = IoTDAUtil.addApplication(appName);
        tdaApplicationVo.setAppId(appId);
        save(tdaApplicationVo);
    }

    @Override
    public void delete(TdaApplicationVo tdaApplicationVo) {
        Long id = tdaApplicationVo.getId();
        Assert.notEmpty(id, "行业表id不能为空");

        // 查询行业是否已添加产品，已添加产品则不可删除
        Long count = tdaProductService.count(TdaProduct::getTdaApplicationId, id);
        Assert.eqZero(count, "行业已添加产品，无法删除");

        // 华为ioDta删除资源空间
        TdaApplication tdaApplication = getById(id);
        IoTDAUtil.deleteApplication(tdaApplication.getAppId());

        removeById(id);
    }

    @Override
    public List<Map<String, Object>> getList() {
        return listMaps(Wrappers.<TdaApplication>lambdaQuery().select(BaseEntity::getId, TdaApplication::getAppName));
    }

    @Override
    public Map<String, Object> details(TdaApplicationVo tdaApplicationVo) {
        return baseMapper.getDetails(tdaApplicationVo.getId());
    }

}
