package com.cpop.api.cloudDb.handler;

import com.alibaba.fastjson.JSONObject;
import com.cpop.api.cloudDb.core.constant.CloudDbUrl;
import com.cpop.api.cloudDb.core.dto.CloudStoreActiveDto;
import com.cpop.api.cloudDb.core.dto.CloudStoreDto;
import com.cpop.common.utils.StringUtils;
import com.cpop.core.base.exception.UtilException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 云校区工具类
 * @author DB
 * @version 1.0.0
 * @since 2024-01-15 11:16
 */
@Component
public class CloudStoreHandler {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 更新校区
     * @author DB
     * @since 2024/1/15
     * @param dto 入参
     */
    public void updateStore(CloudStoreDto dto) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("_type", "storeEdit");
        //云校区id
        jsonBody.put("storeId", dto.getStoreCloudId());
        if (StringUtils.isNotBlank(dto.getBrandCloudId())) {
            jsonBody.put("brandId", dto.getBrandCloudId());
        }
        if (StringUtils.isNotBlank(dto.getStoreName())) {
            jsonBody.put("name", dto.getStoreName());
        }
        if (StringUtils.isNotBlank(dto.getPersonCharge())) {
            jsonBody.put("principalName", dto.getPersonCharge());
        }
        if (StringUtils.isNotBlank(dto.getPhone())) {
            jsonBody.put("phone", dto.getPhone());
        }
        if (StringUtils.isNotBlank(dto.getStoreAddr())) {
            jsonBody.put("address", dto.getStoreAddr());
        }
        JSONObject jsonObject = restTemplate.postForObject(CloudDbUrl.COMMON_USE_URL, jsonBody, JSONObject.class);
        if (jsonObject != null) {
            if (!jsonObject.getBoolean("success")) {
                throw new UtilException(jsonObject.getString("error"));
            }
        }
    }

    /**
     * 获取校区活跃数据
     *
     * @param date 查询日期
     * @return List<Object>
     * @author DB
     * @since 2024/4/12
     */
    public List<CloudStoreActiveDto> getStoreActiveData(String date) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("_type", "storeLogNum");
        jsonBody.put("logDate", date);
        JSONObject jsonObject = restTemplate.postForObject(CloudDbUrl.COMMON_USE_URL, jsonBody, JSONObject.class);
        if (jsonObject != null) {
            if (!jsonObject.getBoolean("success")) {
                throw new UtilException(jsonObject.getString("error"));
            }
            return jsonObject.getJSONArray("data").toJavaList(CloudStoreActiveDto.class);
        } else {
            throw new UtilException("获取云校区活跃数据失败");
        }
    }
}
