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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkListDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DataApiUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.web.qo.data.goodsanalysis.GoodsAnalysisClerkDetailQO;
import com.gic.haoban.manage.web.qo.data.goodsanalysis.GoodsAnalysisOverviewQO;
import com.gic.haoban.manage.web.utils.StoreAuthUtils;
import com.gic.haoban.manage.web.vo.data.ClerkDateTrendVO;
import com.gic.haoban.manage.web.vo.data.ClerkUseDetailVO;
import com.gic.haoban.manage.web.vo.data.GoodsAnalysisDateTrendVO;
import com.gic.haoban.manage.web.vo.data.GoodsAnalysisOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 看数据-商品洞察
 */
@Controller
@RequestMapping("data-goods-analysis")
@Slf4j
public class GoodsAnalysisController {
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private StoreAuthUtils storeAuthUtils;
    @Autowired
    private ClerkService clerkService;

    /**
     * 商品洞察看板（店长、区经）
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-overview-of-manager")
    @ResponseBody
    public RestResponse<GoodsAnalysisOverviewVO> getOverviewOfManager(@RequestBody GoodsAnalysisOverviewQO qo) {
//        boolean isManager = staffApiService.isManager(qo.getClerkId());
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        jsonObject.put("days", storeAuthUtils.getDays(qo.getStartDate(), qo.getEndDate()));
        return RestResponse.successResult(storeAuthUtils.getPageOverview(jsonObject, "data_pro_pref_ent_overview", GoodsAnalysisOverviewVO.class));
    }

    /**
     * 导购明细（店长、区经）
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-clerk-detail-of-manager")
    @ResponseBody
    public RestResponse<Page<ClerkUseDetailVO>> getClerkDetailOfManager(@RequestBody GoodsAnalysisClerkDetailQO qo) {
        boolean isFirstPage = qo.getPageNum() == 1;
        List<ClerkListDTO> clerkList = clerkService.getClerkByStoreIdOfAllStatus(qo.getEnterpriseId(), qo.getStoreId());
        List<String> deleteList = new ArrayList<>();
        List<String> normalList = new ArrayList<>();
        List<String> allList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(clerkList)) {
            for (ClerkListDTO dto : clerkList) {
                Integer status = dto.getStatus();
                allList.add(dto.getClerkId());
                if (status != null && status == 0) {
                    deleteList.add(dto.getClerkId());
                } else {
                    normalList.add(dto.getClerkId());
                }
            }
        }
        if (CollectionUtils.isEmpty(deleteList)) {
            deleteList.add("no_delete_clerk_id");
        }
        if (CollectionUtils.isEmpty(normalList)) {
            normalList.add("no_normal_clerk_id");
        }
        if (CollectionUtils.isEmpty(allList)) {
            allList.add("no_clerk_id");
        }

        //转化金额
        qo.setOrderByFields(qo.getOrderByFields() == null ? 12 : qo.getOrderByFields());
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        jsonObject.put("clerkId", normalList.stream().collect(Collectors.joining(",")));
        //8:合计 非8：列表
        jsonObject.put("storeGroup", "1");
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_pro_pref_clerk_use_detail");
        Page page = DataApiUtils.getPageData(res);
        List<JSONObject> pageList = page.getResult();
        if (pageList == null) {
            pageList = new ArrayList<>();
        }

        if (isFirstPage) {
            jsonObject.put("clerkId", allList.stream().collect(Collectors.joining(",")));
            JSONObject allTotal = storeAuthUtils.getTotalJson(jsonObject, "data_pro_pref_clerk_use_detail");
            if (allTotal != null) {
                allTotal.put("clerkName", "门店");
                pageList.add(0, allTotal);
            }
        }

        int totalPage = page.getTotalCount() % page.getPageSize() != 0 ? page.getTotalCount() / page.getPageSize() + 1 : page.getTotalCount() / page.getPageSize();
        boolean isLastPage = totalPage == qo.getPageNum();
        if (isLastPage) {
            // 最后一页添加离职导购数据

            jsonObject.put("clerkId", deleteList.stream().collect(Collectors.joining(",")));
            JSONObject deleteTotal = storeAuthUtils.getTotalJson(jsonObject, "data_pro_pref_clerk_use_detail");
            if (deleteTotal != null) {
                deleteTotal.put("clerkName", "离职导购（汇总）");
                pageList.add(deleteTotal);
            }
        }
        page.setResult(JSONArray.parseArray(JSON.toJSONString(pageList), ClerkUseDetailVO.class));
        return RestResponse.successResult(page);
    }


    /**
     * 时间趋势（店长）
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-date-trend-of-manager")
    @ResponseBody
    public RestResponse<Page<GoodsAnalysisDateTrendVO>> getDateTrendOfManager(@RequestBody GoodsAnalysisClerkDetailQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_pro_pref_ent_date_overview");
        Page<GoodsAnalysisDateTrendVO> page = DataApiUtils.getPageData(res, GoodsAnalysisDateTrendVO.class);
        return RestResponse.successResult(page);
    }

    /**
     * 导购商品看板
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-overview-of-clerk")
    @ResponseBody
    public RestResponse<ClerkUseDetailVO> getOverviewOfClerk(@RequestBody GoodsAnalysisOverviewQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        jsonObject.put("clerkId", qo.getClerkId());
        jsonObject.put("storeGroup", "1");
        return RestResponse.successResult(storeAuthUtils.getPageOverview(jsonObject, "data_pro_pref_clerk_use_detail", ClerkUseDetailVO.class));
    }

    /**
     * 导购趋势
     * @param qo
     * @return
     */
    @RequestMapping(value = "get-date-trend-of-clerk")
    @ResponseBody
    public RestResponse<Page<ClerkDateTrendVO>> getDateTrendOfClerk(@RequestBody GoodsAnalysisClerkDetailQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        jsonObject.put("clerkId", qo.getClerkId());
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_pro_pref_clerk_date_overview");
        Page<ClerkDateTrendVO> page = DataApiUtils.getPageData(res, ClerkDateTrendVO.class);
        return RestResponse.successResult(page);
    }



}
