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

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
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.canvas.*;
import com.gic.haoban.manage.web.utils.EsMemberInfoUtils;
import com.gic.haoban.manage.web.vo.canvas.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 画布数据
 */
@Slf4j
@RestController
@RequestMapping("/canvas-data")
public class CanvasDataController {
    @Autowired
    private EsMemberInfoUtils esMemberInfoUtils;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private ClerkService clerkService;

    /**
     * 活动转化数据
     * @param qo
     * @return
     */
    @RequestMapping("get-canvas-conversion-data")
    public RestResponse<CanvasConversionDataVO> getCanvasConversionData(@RequestBody CanvasConversionDataQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, null, null);
        //1画布维度2导购维度3会员维度
        jsonObject.put("dataType", 1);

        removeClerkIdParam(qo.getClerkId(), jsonObject);

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_list");
        List<CanvasConversionDataVO> list = DataApiUtils.parsePageDataList(res, CanvasConversionDataVO.class);
        return RestResponse.successResult(list.size() > 0 ? list.get(0) : new CanvasConversionDataVO());
    }

    /**
     * 画布待完成会员列表
     * @param qo
     * @return
     */
    @RequestMapping("get-canvas-to-do-complete-member")
    public RestResponse<Page<CanvasToDoCompleteMemberVO>> getCanvasToDoCompleteMember(@RequestBody CanvasToDoCompleteMemberQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, qo.getPageNum(), qo.getPageSize());

        removeClerkIdParam(qo.getClerkId(), jsonObject);

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_mbr");

        Page<CanvasToDoCompleteMemberVO> page = DataApiUtils.getPageData(res, CanvasToDoCompleteMemberVO.class);
        List<CanvasToDoCompleteMemberVO> list = page.getResult();
        esMemberInfoUtils.setMemberInfo(qo.getEnterpriseId(), list, Stream.of("memberName","memberNick","photoUrl","clerkCode", "clerkName")
                .collect(Collectors.toSet()));
        return RestResponse.successResult(page);
    }

    private void removeClerkIdParam(String clerkId, JSONObject jsonObject) {
        if (StringUtils.isNotBlank(clerkId) && staffApiService.isManager(clerkId)) {
            //店长不需要传参
            jsonObject.remove("clerkId");
        }
    }

    /**
     * 活动已完成的会员
     * @param qo
     * @return
     */
    @RequestMapping("get-canvas-conversion-member")
    public RestResponse<Page<CanvasConversionMemberVO>> getCanvasConversionMember(@RequestBody CanvasConversionMemberQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, qo.getPageNum(), qo.getPageSize());
        //1导购2会员
        jsonObject.put("dataType", 2);

        removeClerkIdParam(qo.getClerkId(), jsonObject);

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_clerk");

        Page<CanvasConversionMemberVO> page = DataApiUtils.getPageData(res, CanvasConversionMemberVO.class);
        List<CanvasConversionMemberVO> list = page.getResult();
        esMemberInfoUtils.setMemberInfo(qo.getEnterpriseId(), list, Stream.of("memberName","memberNick","photoUrl","clerkCode", "clerkName")
                .collect(Collectors.toSet()));
        return RestResponse.successResult(page);
    }

    /**
     * 活动导购详情
     * @param qo
     * @return
     */
    @RequestMapping("get-canvas-conversion-clerk")
    public RestResponse<Page<CanvasConversionMemberVO>> getCanvasConversionClerk(@RequestBody CanvasConversionClerkQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, qo.getPageNum(), qo.getPageSize());
        //1导购2会员
        jsonObject.put("dataType", 1);
        removeClerkIdParam(qo.getClerkId(), jsonObject);
        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_clerk");

        Page<CanvasConversionMemberVO> page = DataApiUtils.getPageData(res, CanvasConversionMemberVO.class);
        List<CanvasConversionMemberVO> list = page.getResult();
        esMemberInfoUtils.setMemberInfo(qo.getEnterpriseId(), list, Stream.of("clerkCode", "clerkName")
                .collect(Collectors.toSet()));
        return RestResponse.successResult(page);
    }


    /**
     * 区经的话务/群发 门店和活动数据
     * @param qo
     * @return
     */
    @RequestMapping("get-tel-or-mass-task-data")
    public RestResponse<Page<CanvasTaskVO>> getTelOrMassTaskData(@RequestBody CanvasTaskQO qo) {
        boolean isStore = qo.getDataType() == 1;
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, qo.getPageNum(), qo.getPageSize());

        if (StringUtils.isBlank(qo.getStoreId())) {
            List<String> authStoreIdList = staffApiService
                    .getHaobanStoreIdsRolesByClerkIdAndStoreStatus(qo.getClerkId(), qo.getWxEnterpriseId(), null, null);
            if (CollectionUtils.isNotEmpty(authStoreIdList)) {
                jsonObject.put("storeId", authStoreIdList.stream().collect(Collectors.joining(",")));
            }
        }


        //区经，设置了门店ID参数后，取出clerkId
        jsonObject.remove("clerkId");

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_mkt_task");
        Page<CanvasTaskVO> page = DataApiUtils.getPageData(res, CanvasTaskVO.class);
        List<CanvasTaskVO> list = page.getResult();
        if (qo.getPageNum() == 1) {
            //合计
            jsonObject.put("dataType", 4);
            res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_mkt_task");
           JSONObject total = DataApiUtils.getPageOne(res);
            total.put(isStore ? "storeName" : "canvasName", "合计");
            if (CollectionUtils.isEmpty(list)) {
                list = new ArrayList<>();
            }
            list.add(0, JSONObject.parseObject(total.toJSONString(), CanvasTaskVO.class));
            page.setResult(list);
        }
        return RestResponse.successResult(page);
    }

    /**
     * 店长/店员 任务列表
     * @param qo
     * @return
     */
    @RequestMapping("get-tel-and-mass-task-data")
    public RestResponse<Page<CanvasStoreTaskVO>> getTelAndMassTaskData(@RequestBody CanvasStoreTaskQO qo) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(qo);
        setPageParam(jsonObject, qo.getPageNum(), qo.getPageSize());
        jsonObject.put("subType", "all");

//        if (StringUtils.isNotBlank(qo.getClerkId()) && staffApiService.isManager(qo.getClerkId())) {
//            //店长不需要传参
//            jsonObject.remove("clerkId");
//        }

        Map<String, Object> res = DataApiUtils.http(jsonObject.toJSONString(), "data_mkt_canvas_haoban_mkt_task");
        Page<CanvasStoreTaskVO> page = DataApiUtils.getPageData(res, CanvasStoreTaskVO.class);
        List<CanvasStoreTaskVO> list = page.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> clerkIdList = list.stream().filter(e -> StringUtils.isNotBlank(e.getClerkId())).map(e -> e.getClerkId()).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(clerkIdList)) {
                List<ClerkDTO> clerkList = clerkService.getClerkByClerkIds(clerkIdList);
                if (CollectionUtils.isNotEmpty(clerkList)) {
                    Map<String, String> clerkIdMapHeadImage = clerkList.stream()
                            .filter(e -> StringUtils.isNotBlank(e.getHeadImgUrl()))
                            .collect(Collectors.toMap(e -> e.getClerkId(), e -> e.getHeadImgUrl()));
                    for (CanvasStoreTaskVO vo : list) {
                        vo.setClerkImageUrl(clerkIdMapHeadImage.get(vo.getClerkId()));
                    }
                }
            }
        }
        return RestResponse.successResult(page);
    }

    private void setPageParam(JSONObject jsonObject, Integer pageNum, Integer pageSize) {
        jsonObject.put("pageNum", pageNum == null ? 1 : pageNum);
        jsonObject.put("pageSize", pageSize == null ? 10 : pageSize);
    }

}
