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

import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.enums.PlatformChannelEnum;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.manage.web.controller.MaterialController;
import com.gic.haoban.manage.web.qo.clerktask.*;
import com.gic.haoban.manage.web.vo.clerktask.*;
import com.gic.marketing.pro.api.dto.clerktask.*;
import com.gic.marketing.pro.api.qdto.clerktask.ClerkAwardQDTO;
import com.gic.marketing.pro.api.qdto.clerktask.ClerkRankQDTO;
import com.gic.marketing.pro.api.qdto.clerktask.ClerkTaskContentPageQDTO;
import com.gic.marketing.pro.api.qdto.clerktask.ClerkTaskPageQDTO;
import com.gic.marketing.pro.api.service.clerktask.ClerkTaskApiService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;
import java.util.stream.Collectors;

/**
 * 导购任务-好办小程序
 */

@Controller
@RequestMapping("clerk/task")
public class ClerkTaskController {
    private static Logger logger = LoggerFactory.getLogger(ClerkTaskController.class);

    @Autowired
    private ClerkTaskApiService clerkTaskApiService ;
    @Autowired
    private EnterpriseService enterpriseService ;

    /**
     * 导购进行中任务数
     */
    @RequestMapping("get-task-count")
    @ResponseBody
    public RestResponse<Object> getTaskCount(String enterpriseId , String clerkId) {
        ClerkTaskPageQDTO qdto = new ClerkTaskPageQDTO() ;
        qdto.setStatus(2);
        qdto.setClerkId(clerkId);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        ServiceResponse<Page<ClerkTaskPlanDTO>> resp =this.clerkTaskApiService.hbPage(qdto) ;
        if(null != resp.getResult()) {
            return RestResponse.successResult(resp.getResult().getTotalCount()) ;
        }
        return RestResponse.successResult(0) ;
    }

    /**
     * 导购任务列表
     * @return
     */
    @RequestMapping("task-list")
    @ResponseBody
    public RestResponse<Page<ClerkTaskListVO>> taskList(@RequestBody ClerkTaskListQO qo) {
        ClerkTaskPageQDTO qdto = EntityUtil.changeEntityByJSON(ClerkTaskPageQDTO.class,qo) ;
        ServiceResponse<Page<ClerkTaskPlanDTO>> resp =this.clerkTaskApiService.hbPage(qdto) ;
        Page<ClerkTaskPlanDTO> page = resp.getResult();
        Page<ClerkTaskListVO> retPage = PageHelperUtils.changePageToCurrentPage(page, ClerkTaskListVO.class);
        if(CollectionUtils.isNotEmpty(retPage.getResult())) {
            Map<Long,Integer> map = this.statusMap(page.getResult()) ;
            for(ClerkTaskListVO vo : retPage.getResult()) {
                vo.setStatus(map.get(vo.getPlanId()));
            }
        }
        return RestResponse.successResult(retPage) ;
    }

    // 1未开始  2进行中  3已结束  4已过期 */
    private Map<Long,Integer> statusMap(List<ClerkTaskPlanDTO> list) {
        Map<Long,Integer> map = new HashMap<>() ;
        for(ClerkTaskPlanDTO dto : list) {
            if(dto.getStatusFlag()==2) {
                map.put(dto.getPlanId(),3) ;
            }else {
                if(dto.getBeginDate().getTime()>System.currentTimeMillis()) {
                    map.put(dto.getPlanId(),1) ;
                }else if(DateUtil.getEndTimeOfDay(dto.getEndDate()).getTime()<System.currentTimeMillis()) {
                    map.put(dto.getPlanId(),3) ;
                }else {
                    map.put(dto.getPlanId(),2) ;
                }
            }
        }
        return map ;
    }

    /**
     * 任务详情
     */
    @RequestMapping("task-detail")
    @ResponseBody
    public RestResponse<TaskPlanDetailVO> taskDetail(String enterpriseId , Long planId , String clerkId) {
        ServiceResponse<ClerkTaskPlanDTO> resp = this.clerkTaskApiService.getDetail(enterpriseId, planId,0) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        TaskPlanDetailVO vo = new TaskPlanDetailVO() ;
        Map<Long,Integer> map = this.statusMap(Arrays.asList(resp.getResult())) ;
        vo = EntityUtil.changeEntityByJSON(TaskPlanDetailVO.class,resp.getResult());
        vo.setStatus(map.get(vo.getPlanId()));
        vo.setOrderChannelNames(this.channelName(enterpriseId,vo.getOrderChannels()));
        return RestResponse.successResult(vo) ;
    }

    private String channelName(String enterpriseId , String channelCodes) {
        if(StringUtils.isBlank(channelCodes)) {
            return "";
        }else {
            ServiceResponse<List<PlatformChannelEnum>> resp = this.enterpriseService.getEnabledMemberChannel(enterpriseId) ;
            Map<String,String> map = new HashMap<>() ;
            map.put("c_pos","线下") ;
            if(resp.isSuccess()) {
                List<PlatformChannelEnum> channelEnumList = resp.getResult() ;
                for(PlatformChannelEnum o : channelEnumList) {
                    map.put(o.getChannelCode(),o.getChannelNameOrder()) ;
                }
            }
            logger.info("{},{}",channelCodes);
            String[] arr = channelCodes.split(",") ;
            List<String> list = new ArrayList<>() ;
            for(int i=0;i<arr.length;i++) {
                String s = arr[i] ;
                if(StringUtils.isNotBlank(s)) {
                    if(null != map.get(s)) {
                        list.add(map.get(s)) ;
                    }
                }
            }
            return list.stream().collect(Collectors.joining(","));
        }
    }

    /**
     * 排名
     */
    @RequestMapping("task-rank-list")
    @ResponseBody
    public RestResponse<Page<ClerkRankVO>> taskRankList(@RequestBody ClerkRankQO qo) {
        ClerkRankQDTO qdto = EntityUtil.changeEntityByJSON(ClerkRankQDTO.class,qo) ;
        ServiceResponse<Page<ClerkRankDTO>> resp = this.clerkTaskApiService.taskRankList(qdto) ;
        Page<ClerkRankDTO> page = resp.getResult();
        Page<ClerkRankVO> retPage = PageHelperUtils.changePageToCurrentPage(page, ClerkRankVO.class);
        return RestResponse.successResult(retPage) ;
    }

    /**
     * 奖励明细
     */
    @RequestMapping("task-award-list")
    @ResponseBody
    public RestResponse<Page<ClerkAwardVO>> taskAwardList(@RequestBody ClerkAwardQO qo) {
        ClerkAwardQDTO qdto = EntityUtil.changeEntityByJSON(ClerkAwardQDTO.class,qo) ;
        ServiceResponse<Page<ClerkTaskAwardLogDTO>> resp = this.clerkTaskApiService.taskAwardList(qdto) ;
        Page<ClerkTaskAwardLogDTO> page = resp.getResult();
        Page<ClerkAwardVO> retPage = PageHelperUtils.changePageToCurrentPage(page, ClerkAwardVO.class);
        return RestResponse.successResult(retPage) ;
    }
    /**
     *  公域-内容创作上报
     */
    @RequestMapping("save-content")
    @ResponseBody
    public RestResponse<String> saveContent(String enterpriseId , @RequestBody SaveContentQO qo) {
        ClerkTaskContentLogDTO dto = EntityUtil.changeEntityByJSON(ClerkTaskContentLogDTO.class,qo) ;
        dto.setEnterpriseId(enterpriseId);
        ServiceResponse<Long> resp = this.clerkTaskApiService.saveContent(dto) ;
        return RestResponse.successResult(resp.getResult()+"") ;
    }

    /**
     *  公域-内容创作上报-更新
     */
    @RequestMapping("update-content")
    @ResponseBody
    public RestResponse<String> updateContent(String enterpriseId , @RequestBody SaveContentQO qo) {
        ClerkTaskContentLogDTO dto = EntityUtil.changeEntityByJSON(ClerkTaskContentLogDTO.class,qo) ;
        dto.setEnterpriseId(enterpriseId);
        ServiceResponse<Long> resp = this.clerkTaskApiService.saveContent(dto) ;
        return RestResponse.successResult(resp.getResult()+"") ;
    }

    /**
     * 公域-素材列表查询
     * @param qo
     * @return
     */
    @RequestMapping("list-content")
    @ResponseBody
    public RestResponse<Page<ClerkTaskContentPageVO>> listContent(@RequestBody ContentPageQO qo) {
        ClerkTaskContentPageQDTO qdto = EntityUtil.changeEntityByJSON(ClerkTaskContentPageQDTO.class,qo) ;
        ServiceResponse<Page<ClerkTaskContentLogDTO>> resp = this.clerkTaskApiService.contentPage(qdto) ;
        Page<ClerkTaskContentLogDTO> page = resp.getResult();
        Page<ClerkTaskContentPageVO> retPage = PageHelperUtils.changePageToCurrentPage(page, ClerkTaskContentPageVO.class);
        return RestResponse.successResult(retPage) ;
    }

    /**
     *  获取召回客户数
     */
    @RequestMapping("get-consume-count")
    @ResponseBody
    public RestResponse<ConsumeMemberCountVO> getConsumeCount(String enterpriseId , String clerkId , Long planId) {
        ConsumeMemberCountDTO dto = this.clerkTaskApiService.getConsumeCount(enterpriseId,clerkId,planId) ;
        ConsumeMemberCountVO vo = EntityUtil.changeEntityByJSON(ConsumeMemberCountVO.class,dto) ;
        return RestResponse.successResult(vo) ;
    }
}
