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.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.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

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


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) {
        if(StringUtils.isAnyBlank(""+planId,clerkId)) {
            return  RestResponse.failure("9999","必传参数为空") ;
        }
        ServiceResponse<ClerkTaskPlanDTO> resp = this.clerkTaskApiService.getDetail(enterpriseId, planId,0) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        TaskPlanDetailVO vo = null ;
        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()));
        ClerkAwardInfoDTO awardInfoDTO = this.clerkTaskApiService.getClerkFinishInfo(planId,clerkId) ;
        ClerkAwardInfoVO  awardInfoVO = new ClerkAwardInfoVO();
        if(null != awardInfoVO) {
            awardInfoVO = EntityUtil.changeEntityByJSON(ClerkAwardInfoVO.class,awardInfoDTO) ;
        }
        vo.setClerkAwardInfo(awardInfoVO);
        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) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        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(@RequestBody SaveContentQO qo) {
        return this.save(qo) ;
    }


    private  RestResponse<String> save(SaveContentQO qo) {
        ClerkTaskContentLogDTO dto = EntityUtil.changeEntityByJSON(ClerkTaskContentLogDTO.class,qo) ;
        dto.setContentPublishType(2);
        if(qo.getUpType()==2) {
            String content = qo.getContent() ;
            if(!qo.getContent().startsWith("http")) {
                Pattern p = Pattern.compile("http.*xhslink.com/a/\\w+") ;
                Matcher m = p.matcher(content) ;
                while (m.find()) {
                  content = m.group();
                }
                if(!content.startsWith("http")) {
                    return RestResponse.failure("9999", "请输入小红书的链接,如：http://xhslink.com/a/uIZodbunsEaY");
                }
                dto.setContent(content);
            }
        }
        ServiceResponse<Long> resp = this.clerkTaskApiService.saveContent(dto) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        return RestResponse.successResult(resp.getResult()+"") ;
    }

    /**
     *  公域-内容创作上报-更新
     */
    @RequestMapping("update-content")
    @ResponseBody
    public RestResponse<String> updateContent( @RequestBody SaveContentQO qo) {
       return this.save(qo) ;
    }

    /**
     * 公域-素材列表查询
     * @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) ;
    }
}
