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.util.EntityUtil;
import com.gic.commons.web.qo.PageQo;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreGroupDTO;
import com.gic.enterprise.api.dto.target.DataTargetConfigNewVersionsDTO;
import com.gic.enterprise.api.qdto.target.QueryNewDataTargetConfigQDTO;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.enterprise.api.service.target.DataTargetConfigNewVersionsApiService;
import com.gic.haoban.manage.web.exception.TargetException;
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.StoreTargetConfigHttpUtils;
import com.gic.haoban.manage.web.vo.target.StoreTargetDisassemblyDetailVO;
import com.gic.haoban.manage.web.vo.target.StoreTargetReachDetailVO;
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.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 好办小程序-门店目标跟进正式版
 * @Author guojx
 * @Date 2023/6/12 9:09
 */
@Controller
@RequestMapping("/store-target-config")
public class StoreTargetConfigController {
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private StoreService storeService;
    @Autowired
    private DataTargetConfigNewVersionsApiService dataTargetConfigNewVersionsApiService;
    @Autowired
    private StoreGroupService storeGroupService;

    /**
     * 是否有配置的发布门店
     * @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<DataTargetConfigNewVersionsDTO>> res = dataTargetConfigNewVersionsApiService.queryNewDataTargetConfig(param, new BasePageInfo());
        if (res.isSuccess()) {
            if (res.getResult().getTotalCount() > 0) {
                return RestResponse.successResult(1);
            }
        }
        return RestResponse.successResult(0);
    }

    /**
     * 目标跟进核心目标达成概况
     * @return
     */
    @RequestMapping(value = "get-target-reach-overview")
    @ResponseBody
    public RestResponse getTargetReachOverview(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo);
        queryStoreGroupType(jsonObject, 8);
        Map<String, Object> res = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                qo.isYearQuery() ? "data_target_mgt_group_year_stat" : "data_target_mgt_group_month_stat");
        return StoreTargetConfigHttpUtils.responsePageOne(res);
    }

    /**
     * 目标跟进核心指标趋势分月/累计
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-target-chart")
    @ResponseBody
    public RestResponse getTargetChart(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = getCommon(qo);
        queryStoreGroupType(jsonObject, 8);
        //不传月参数，返回12条月数据。否则返回一条合计
        Map<String, Object> res = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                "data_target_mgt_group_month_stat");
        return StoreTargetConfigHttpUtils.responsePageList(res);
    }

    /**
     * 目标跟进达成分析门店明细数据
     * @param qo
     * @param pageQo
     * @param orderByType 排序类型 1 正序asc  2倒序desc
     * @param orderByFields 数字。具体看数据组的文档，备注里会有文档链接
     * @return
     */
    @RequestMapping(value = "get-target-analysis-store-detail")
    @ResponseBody
    public RestResponse<Page<StoreTargetReachDetailVO>> getTargetAnalysisStoreDetail(QueryDataStatisticsCommonQO qo, PageQo pageQo,
                                                                                     Integer orderByType, Integer orderByFields) {

        JSONObject jsonObject = getCommon(qo);
        queryStoreGroupType(jsonObject, 8);
        //不传月参数，返回12条月数据。否则返回一条合计
        Map<String, Object> totalRes = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                qo.isYearQuery() ? "data_target_mgt_group_year_stat" : "data_target_mgt_group_month_stat");
        if (!StoreTargetConfigHttpUtils.isSuccess(totalRes)) {
            throw new TargetException(totalRes.get("errMsg").toString());
        }
        JSONObject totalData = StoreTargetConfigHttpUtils.getPageOne(totalRes);
        //查询列表数据
        jsonObject.put("pageSize", pageQo.getPageSize());
        jsonObject.put("pageNum", pageQo.getPageNum());
        //滚动达成率(总销售额)  排序33
        jsonObject.put("orderByFields", orderByType == null ? 1 : orderByType);
        jsonObject.put("orderByType", orderByFields == null ? 33 : orderByFields);
        queryStoreGroupType(jsonObject, 7);

        Map<String, Object> res = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                qo.isYearQuery() ? "data_target_mgt_group_year_stat" : "data_target_mgt_group_month_stat");
        Page page = StoreTargetConfigHttpUtils.getPageData(res);

        Page<StoreTargetReachDetailVO> resultPage = EntityUtil.changeEntityNew(Page.class, page);
        List<JSONObject> list = StoreTargetConfigHttpUtils.getPageList(res);
        List<StoreTargetReachDetailVO> voList = JSONObject.parseArray(JSONObject.toJSONString(list), StoreTargetReachDetailVO.class);
        if (pageQo.getPageNum() == 1) {
            StoreTargetReachDetailVO vo = JSONObject.parseObject(totalData.toJSONString(), StoreTargetReachDetailVO.class);
            vo.setStoreId("-1");
            vo.setStoreName("合计");
            vo.setStoreCode("-1");
            voList.add(0, vo);
        }
        resultPage.setResult(voList);
        return RestResponse.successResult(page);
    }

    /**
     * 树跳转-目标跟进达成分析门店明细数据
     * @param qo
     * @param pageQo
     * @param orderByType 排序类型 1 正序asc  2倒序desc
     * @param orderByFields 数字。具体看数据组的文档，备注里会有文档链接
     * @return
     */
    @RequestMapping(value = "get-target-analysis-store-detail-of-tree")
    @ResponseBody
    public RestResponse<Page<StoreTargetDisassemblyDetailVO>> getTargetAnalysisStoreDetailOfTree(QueryDataStatisticsCommonQO qo, PageQo pageQo,
                                                                                           Integer orderByType, Integer orderByFields) {

        JSONObject jsonObject = getCommon(qo);
        queryStoreGroupType(jsonObject, 8);
        //不传月参数，返回12条月数据。否则返回一条合计
        Map<String, Object> totalRes = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                qo.isYearQuery() ? "data_target_mgt_group_year_stat" : "data_target_mgt_group_month_stat");
        if (!StoreTargetConfigHttpUtils.isSuccess(totalRes)) {
            throw new TargetException(totalRes.get("errMsg").toString());
        }
        JSONObject totalData = StoreTargetConfigHttpUtils.getPageOne(totalRes);
        //查询列表数据
        jsonObject.put("pageSize", pageQo.getPageSize());
        jsonObject.put("pageNum", pageQo.getPageNum());
        //会员消费次数滚动达成率 排序11
        jsonObject.put("orderByFields", orderByType == null ? 1 : orderByType);
        jsonObject.put("orderByType", orderByFields == null ? 11 : orderByFields);
        queryStoreGroupType(jsonObject, 7);

        Map<String, Object> res = StoreTargetConfigHttpUtils.http(jsonObject.toJSONString(),
                qo.isYearQuery() ? "data_target_mgt_mbr_pay_amt_dismbl_year" : "data_target_mgt_mbr_pay_amt_dismbl_month");
        Page page = StoreTargetConfigHttpUtils.getPageData(res);

        Page<StoreTargetDisassemblyDetailVO> resultPage = EntityUtil.changeEntityNew(Page.class, page);
        List<JSONObject> list = StoreTargetConfigHttpUtils.getPageList(res);
        List<StoreTargetDisassemblyDetailVO> voList = JSONObject.parseArray(JSONObject.toJSONString(list), StoreTargetDisassemblyDetailVO.class);
        if (pageQo.getPageNum() == 1) {
            StoreTargetDisassemblyDetailVO vo = JSONObject.parseObject(totalData.toJSONString(), StoreTargetDisassemblyDetailVO.class);
            vo.setStoreId("-1");
            vo.setStoreName("合计");
            vo.setStoreCode("-1");
            voList.add(0, vo);
        }
        resultPage.setResult(voList);
        return RestResponse.successResult(page);
    }

    private int getStoreGroupType(Integer showAllStoreFlag, String nextStoreGroupId) {
        //1：分组1,2：分组2,3：分组3,4：分组4,5：分组5,6：分组6,7：门店,8：区经)
        if (showAllStoreFlag != null && showAllStoreFlag == 1) {
            return 7;
        }
        if (StringUtils.isNotBlank(nextStoreGroupId)) {
            StoreGroupDTO storeGroupDTO = storeGroupService.getStoreGroupById(nextStoreGroupId);
            return storeGroupDTO.getGroupLevel() + 1;
        }
        return 1;
    }

    private void dealNextStoreIdParam(JSONObject jsonObject, String nextStoreGroupId) {
        QueryNewDataTargetConfigQDTO qdto = new QueryNewDataTargetConfigQDTO();
        qdto.setStoreGroupId(nextStoreGroupId);
        qdto.setEnterpriseId(jsonObject.getString("enterpriseId"));
        List<String> nextStoreIdList = dataTargetConfigNewVersionsApiService.getQueryStoreParam(qdto).getResult();
        if (CollectionUtils.isNotEmpty(nextStoreIdList)) {
            if (jsonObject.containsKey("storeId")) {
                String authStoreId = jsonObject.get("storeId").toString();
                List<String> authStoreIdList = Arrays.stream(authStoreId.split(",")).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(authStoreIdList)) {
                    //交集
                    nextStoreIdList.retainAll(authStoreIdList);
                }
                jsonObject.put("storeId", nextStoreIdList.stream().collect(Collectors.joining(",")));
            }
        }
    }

    private static void queryStoreGroupType(JSONObject jsonObject, int type) {
        jsonObject.put("storeGroup", type);
    }

    private JSONObject getCommon(QueryDataStatisticsCommonQO qo) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("enterpriseId", qo.getEnterpriseId());
        if (StringUtils.isBlank(qo.getTime())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy");
            qo.setTime(df.format(new Date()));
        }
        if (qo.isYearQuery()) {
            jsonObject.put("targetYear", qo.getTime());
        } else {
            jsonObject.put("targetMonth", 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<DataTargetConfigNewVersionsDTO>> res = dataTargetConfigNewVersionsApiService.queryNewDataTargetConfig(qdto, basePageInfo);
        Page<DataTargetConfigNewVersionsDTO> page = res.getResult();
        Integer total = page.getTotalCount();
        if (total <= 0) {
            return null;
        }
        List<DataTargetConfigNewVersionsDTO> list = page.getResult();
        for (DataTargetConfigNewVersionsDTO 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 = dataTargetConfigNewVersionsApiService.queryNewDataTargetConfig(qdto, basePageInfo);
                List<DataTargetConfigNewVersionsDTO> temp = res.getResult().getResult();
                for (DataTargetConfigNewVersionsDTO dto : temp) {
                    storeIdList.add(dto.getStoreId());
                }
            }
        }
        return storeIdList;
    }
}
