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

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.web.qo.PageQo;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.target.NewDataTargetConfigDTO;
import com.gic.enterprise.api.qdto.target.QueryNewDataTargetConfigQDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.enterprise.api.service.target.NewDataTargetConfigApiService;
import com.gic.haoban.manage.web.qo.target.QueryDataStatisticsCommonQO;
import com.gic.haoban.manage.web.utils.StoreAuthUtils;
import com.gic.haoban.manage.web.utils.target.DataTargetHttpUtils;
import com.gic.haoban.manage.web.utils.target.TargetAnalysisUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 好办小程序-目标跟进
 * @Author guojx
 * @Date 2023/1/17 9:51
 */
@Controller
public class TargetController {
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private StoreService storeService;
    @Autowired
    private NewDataTargetConfigApiService newDataTargetConfigApiService;

    /**
     * 是否有配置的发布门店
     * @param qo
     * @return
     */
    @RequestMapping(value = "valid-target-store")
    @ResponseBody
    public RestResponse<Integer> validTargetStore(QueryDataStatisticsCommonQO qo) {
        List<String> storeIdList = getStoreIdList(qo, false);
        QueryNewDataTargetConfigQDTO param = new QueryNewDataTargetConfigQDTO();
        param.setStoreIdList(storeIdList);
        param.setEnterpriseId(qo.getEnterpriseId());
        param.setReleaseFlag(1);
        param.setTargetYear(qo.getTime().substring(0,4));
        ServiceResponse<Page<NewDataTargetConfigDTO>> res = newDataTargetConfigApiService.queryNewDataTargetConfig(param, new BasePageInfo());
        if (res.isSuccess()) {
            if (res.getResult().getTotalCount() > 0) {
                return RestResponse.successResult(1);
            }
        }
        return RestResponse.successResult(0);
    }

    /**
     * 目标跟进达成分析数据概览
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-target-attainment-analysis-overview")
    @ResponseBody
    public RestResponse getTargetAttainmentAnalysisOverview(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo, false);
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject).toJSONString(),
                "data_mbr_target_store_total");
        JSONObject result1 = DataTargetHttpUtils.getData(res);
        if (result1 == null) {
            result1 = new JSONObject();
        }
        //合并
        JSONObject jsonObject2 = getCommon(qo, true);
        Map<String, Object> res2 = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject2).toJSONString(),
                qo.getTimeType() == 1 ? "data_mbr_target_attainment_analysis_year_overview" : "data_mbr_target_attainment_analysis_month_overview");
        JSONObject result2 = DataTargetHttpUtils.getData(res2);
        if (result2 == null) {
            result2 = new JSONObject();
        }
        result1.putAll(result2);

        List<String> keyList = new ArrayList<>();
        keyList.addAll(TargetAnalysisUtils.map.get("0"));
        keyList.addAll(TargetAnalysisUtils.map.get("1"));
        keyList.addAll(TargetAnalysisUtils.map.get("2"));
        keyList.addAll(TargetAnalysisUtils.map.get("3"));
        keyList.addAll(TargetAnalysisUtils.map.get("4"));
        keyList.addAll(TargetAnalysisUtils.map.get("5"));
        JSONObject result = new JSONObject();
        for (String key : keyList) {
            result.put(key, result1.get(key));
        }
        return RestResponse.successResult(result);
    }

    /**
     * 目标跟进核心目标达成概况
     * @return
     */
    @RequestMapping(value = "get-target-reach-overview")
    @ResponseBody
    public RestResponse getTargetReachOverview(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo, false);
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject).toJSONString(),
                "data_mbr_target_reach_overview");
        return DataTargetHttpUtils.responseOfOne(res, null);
    }

    /**
     * 目标跟进核心指标趋势分月/累计
     * @param qo
     * @param chartType 1:分月 2：累计
     * @return
     */
    @RequestMapping(value = "get-target-chart")
    @ResponseBody
    public RestResponse getTargetChart(QueryDataStatisticsCommonQO qo, Integer chartType) {
        if (chartType == null) {
            chartType = 1;
        }
        if (StringUtils.isBlank(qo.getTime())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy");
            qo.setTime(df.format(new Date()));
        }
        JSONObject jsonObject = getCommon(qo, false);
        jsonObject.put("targetYear", qo.getTime().substring(0, 4));
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject).toJSONString(),
                chartType == 1 ? "data_mbr_target_chart" : "data_mbr_target_cumulate_chart");
        return DataTargetHttpUtils.response(res);
    }

    /**
     * 目标跟进达成分析门店明细数据
     * @param qo
     * @param pageQo
     * @param sortField 排序字段
     * @param sortType asc desc
     * @param type 0:实际新增会员数 1:实际会员销售额 2：实际会员消费总次数 3：客单价 4：存量会员消费总次数 5：新增会员消费总次数 6：存量会员仅消费一次总次数 7：存量会员消费多次总次数
     *             8：新增会员仅消费一次总次数 9：新增会员消费多次总次数 10：存量会员仅消费一次总人数 11：存量会员消费多次总人数 12 ：量会员消费多次人均消费次数
     *             13 ：新增会员仅消费一次总人数 14：新增会员消费多次总人数 15：新增会员消费多次人均消费次数
     * @return
     */
    @RequestMapping(value = "get-target-analysis-store-detail")
    @ResponseBody
    public RestResponse getTargetAnalysisStoreDetail(QueryDataStatisticsCommonQO qo, PageQo pageQo,
                                                     String sortField, String sortType, @RequestParam(defaultValue = "1") Integer type) {
        List<String> keyList = TargetAnalysisUtils.map.get(type.toString());
        JSONObject jsonObject = getCommon(qo, type <= 3 ? false : true);
        if (StringUtils.isNotBlank(sortField)) {
            jsonObject.put("orderByField", sortField + " " + sortType);
        } else {
            jsonObject.put("orderByField", keyList.get(3) + " asc ");
        }
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParam(pageQo, jsonObject).toJSONString(),
                type <=3 ? (qo.getTimeType() == 1 ? "data_mbr_target_store_detail_year" : "data_mbr_target_store_detail_month") :  (qo.getTimeType() == 1 ?
                        "data_mbr_target_analysis_year_store_detail" : "data_mbr_target_analysis_month_store_detail"));
        Page page = DataTargetHttpUtils.getPage(res);
        //加上总计数据
        RestResponse totalRes = getTargetAttainmentAnalysisOverview(qo);
        if (!"0".equals(totalRes.getCode())) {
            return totalRes;
        }
        JSONObject totalJson = (JSONObject) totalRes.getResult();
        JSONObject total = new JSONObject();
        for (String key : keyList) {
            total.put(key, totalJson.get(key));
        }
        total.put("storeId", "-1");
        total.put("storeName", "合计（" + page.getTotalCount() + "）");
        total.put("storeCode", "合计");
        List<JSONObject> dataList = page.getResult();
        List<JSONObject> resultList = new ArrayList<>();
        if (pageQo.getPageNum() == 1) {
            resultList.add(total);
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (JSONObject obj : dataList) {
                JSONObject temp = new JSONObject();
                String storeId = obj.getString("storeId");
                temp.put("storeId", storeId);
                if (!"-1".equals(storeId)) {
                    StoreDTO storeDTO = storeService.getStore(storeId);
                    if (storeDTO != null) {
                        temp.put("storeName", storeDTO.getStoreName());
                        temp.put("storeCode", storeDTO.getStoreCode());
                    }
                }
                for (String key : keyList) {
                    temp.put(key, obj.get(key));
                }
                resultList.add(temp);
            }
        }
        page.setResult(resultList);
        return RestResponse.successResult(page);
    }

    /**
     * 目标跟进门店会员分层明细数据
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-target-store-mbr-hierarchy-detail")
    @ResponseBody
    public RestResponse getTargetStoreMbrHierarchyDetail(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo, true);
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject).toJSONString(),
                "data_mbr_target_store_mbr_hierarchy_detail");
        return DataTargetHttpUtils.responseOfOne(res, null);
    }

    /**
     * 目标跟进门店会员631分层明细数据
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-target-store-mbr-631-detail")
    @ResponseBody
    public RestResponse getTargetStoreMbr631Detail(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo, true);
        Map<String, Object> res = DataTargetHttpUtils.http(DataTargetHttpUtils.getParamNoPage(jsonObject).toJSONString(),
                "data_mbr_target_store_mbr_631_detail");
        return DataTargetHttpUtils.responseOfOne(res, null);
    }

    private JSONObject getCommon(QueryDataStatisticsCommonQO qo, boolean app) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("entId", qo.getEnterpriseId());
        jsonObject.put("enterpriseId", qo.getEnterpriseId());
        jsonObject.put("yearDate", qo.getTime());
        if (qo.getTimeType() == 1) {
            jsonObject.put("year", qo.getTime());
        } else {
            jsonObject.put("month", qo.getTime());
        }
        jsonObject.put("monthDate", qo.getTime());
        jsonObject.put("storeId", getStoreIdList(qo, true).stream().collect(Collectors.joining(",")));
        return jsonObject;
    }

    private List<String> getStoreIdList(QueryDataStatisticsCommonQO qo, boolean isRelease) {
        List<String> storeIdList;
        if (StringUtils.isBlank(qo.getStoreId())) {
            storeIdList = storeAuthUtils.queryClerkStoreIds(qo.getClerkId(), qo.getWxEnterpriseId());
        } else {
            storeIdList = new ArrayList<>();
            String[] storeIds = qo.getStoreId().split(",");
            for (String storeIdTemp :storeIds) {
                if (StringUtils.isBlank(storeIdTemp)) {
                    continue;
                }
                storeIdList.add(storeIdTemp);
            }
        }
        if (!isRelease) {
            return storeIdList;
        }
        List<String> targetStoreIdList = getReleaseStore(qo, 1);
        //交集 (已发布的门店数据统计过滤)
        if (CollectionUtils.isEmpty(targetStoreIdList)) {
            targetStoreIdList = new ArrayList<>();
            targetStoreIdList.add("-123456789");
        }
        if (CollectionUtils.isEmpty(storeIdList)) {
            //全部权限，则给出发布门店数据
            return targetStoreIdList;
        } else {
            storeIdList.retainAll(targetStoreIdList);
            if (CollectionUtils.isEmpty(storeIdList)) {
                storeIdList.add("-1234567890");
            }
        }
        return storeIdList;
    }

    public List<String> getReleaseStore(QueryDataStatisticsCommonQO params, Integer releaseFlag) {
        List<String> storeIdList = new ArrayList<>();
        QueryNewDataTargetConfigQDTO qdto = new QueryNewDataTargetConfigQDTO();
        qdto.setEnterpriseId(params.getEnterpriseId());
        if (StringUtils.isNotBlank(params.getTime())) {
            qdto.setTargetYear(params.getTime().substring(0, 4));
        }
        qdto.setReleaseFlag(releaseFlag);
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1000);
        ServiceResponse<Page<NewDataTargetConfigDTO>> res = newDataTargetConfigApiService.queryNewDataTargetConfig(qdto, basePageInfo);
        Page<NewDataTargetConfigDTO> page = res.getResult();
        Integer total = page.getTotalCount();
        if (total <= 0) {
            return null;
        }
        List<NewDataTargetConfigDTO> list = page.getResult();
        for (NewDataTargetConfigDTO dto : list) {
            storeIdList.add(dto.getStoreId());
        }
        int pageNum = total / 1000 + 1;
        if (pageNum > 1) {
            for (int i = 2; i < pageNum; i++) {
                basePageInfo.setPageNum(i);
                res = newDataTargetConfigApiService.queryNewDataTargetConfig(qdto, basePageInfo);
                List<NewDataTargetConfigDTO> temp = res.getResult().getResult();
                for (NewDataTargetConfigDTO dto : temp) {
                    storeIdList.add(dto.getStoreId());
                }
            }
        }
        return storeIdList;
    }
}
