package com.gic.haoban.manage.web.controller.data;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.DataApiUtils;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.data.DataIndexEvaluateLogDTO;
import com.gic.enterprise.api.dto.data.DataIndexExplainDTO;
import com.gic.enterprise.api.service.data.DataIndexApiService;
import com.gic.enterprise.service.CustomSettingApiService;
import com.gic.haoban.manage.web.qo.data.DataIndexExplainVO;
import com.gic.haoban.manage.web.qo.data.DataIndexQO;
import com.gic.haoban.manage.web.qo.data.HandleQO;
import com.gic.haoban.manage.web.utils.StoreAuthUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据调用通用接口
 * @Author guojx
 * @Date 2023/11/14 10:56
 */
@Controller
@RequestMapping("data")
public class DataController {
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private DataIndexApiService dataIndexApiService;
    @Autowired
    private CustomSettingApiService customSettingApiService;

    /**
     * 数据统一调用接口
     * 参数与返回字段查询数据组的yapi的对应文档
     * @param qo
     * @return
     */
    @RequestMapping(value = "handle")
    @ResponseBody
    public RestResponse handle(@RequestBody HandleQO qo) {
        String params = qo.getParams();
        JSONObject jsonObject = JSONObject.parseObject(params);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        if (StringUtils.isNotBlank(qo.getEnterpriseId())) {
            jsonObject.put("enterpriseId", qo.getWxEnterpriseId());
        }
        List<String> storeIdList = new ArrayList<>();
        String storeId = qo.getStoreId();
        if (StringUtils.isBlank(storeId)) {
            storeIdList = storeAuthUtils.queryClerkStoreIds(qo.getClerkId(), qo.getWxEnterpriseId());
        } else {
            storeIdList.add(storeId);
        }
        if (CollectionUtils.isNotEmpty(storeIdList)) {
            //区经有全部门店权限
            jsonObject.put("storeId", storeIdList.stream().collect(Collectors.joining(",")));
        }
        Map<String, Object> res = DataApiUtils.http(params, qo.getApolloKey());
        return RestResponse.successResult(res.get("data"));
    }

    /**
     * 指标字典列表
     * @param indexCode 可以多个，英文逗号隔开
     * @return
     */
    @RequestMapping("list-data-index-explain")
    @ResponseBody
    public RestResponse<List<DataIndexExplainVO>> listDataIndexExplain(String indexCode) {
        List<DataIndexExplainDTO> list = dataIndexApiService.listDataIndexExplain();
        if (StringUtils.isNotBlank(indexCode)) {
            List<String> indexCodeList = Arrays.stream(indexCode.split(",")).collect(Collectors.toList());
            list = list.stream().filter(e -> indexCodeList.contains(e.getIndexCode())).collect(Collectors.toList());
        }
        return RestResponse.successResult(EntityUtil.changeEntityListNew(DataIndexExplainVO.class, list));
    }

    /**
     * 评价指标
     * @param qo
     * @return
     */
    @RequestMapping("evaluate-data-index")
    @ResponseBody
    public RestResponse saveDataIndexEvaluate(@RequestBody DataIndexQO qo) {
        DataIndexEvaluateLogDTO log = EntityUtil.changeEntityNew(DataIndexEvaluateLogDTO.class, qo);
        log.setAccountId(qo.getClerkId());
        log.setSourceType(1);
        dataIndexApiService.saveDataIndexEvaluateLog(log);
        return RestResponse.successResult();
    }

    /**
     * 渠道字典数据
     * 说明：channelCode （渠道code，数据接口需要传的）
     * channelNameIntegral 会员类型的名称
     * channelNameOrder 订单业绩的名称
     * @param enterpriseId
     * @return
     */
    @RequestMapping("list-channel-data")
    @ResponseBody
    public RestResponse listChannelData(String enterpriseId) {
        Page<JSONObject> page = customSettingApiService
                .page("tab_gic_channel_platform_dict", "", 1, 1000).getResult();
        if (page != null) {
            return RestResponse.successResult(page.getResult());
        }
        return RestResponse.successResult(new ArrayList<>());
    }


    private JSONObject getTotalJson(JSONObject param, String apolloKey) {
        Map<String, Object> totalRes = DataApiUtils.http(param.toJSONString(), apolloKey);
        List<JSONObject> totalList = DataApiUtils.getPageList(totalRes);
        if (CollectionUtils.isEmpty(totalList)) {
            return null;
        }
        JSONObject total = totalList.get(0);
        return total;
    }
}
