package com.gic.haoban.manage.service.service.moment.impl;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanAttendDTO;
import com.gic.haoban.manage.api.dto.moment.TaskDetailDTO;
import com.gic.haoban.manage.api.dto.moment.TaskListWxaDTO;
import com.gic.haoban.manage.api.qdto.moment.PlanClerkListQDTO;
import com.gic.haoban.manage.api.qdto.moment.SendResultQDTO;
import com.gic.haoban.manage.api.qdto.moment.TaskListWxaQDTO;
import com.gic.haoban.manage.service.dao.mapper.StaffMapper;
import com.gic.haoban.manage.service.dao.mapper.moment.QwMomentPlanAttendMapper;
import com.gic.haoban.manage.service.dao.mapper.moment.QwMomentPlanMapper;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.entity.moment.TabQwMomentPlanAttend;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.moment.QwMomentPlanAttendService;
import com.gic.wechat.api.dto.qdto.group.QywxMomentInfoQDTO;
import com.gic.wechat.api.dto.qywx.group.QywxMomentRespDTO;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("qwMomentPlanAttendService")
public class QwMomentPlanAttendServiceImpl implements QwMomentPlanAttendService {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private QwMomentPlanAttendMapper qwMomentPlanAttendMapper ;
    @Autowired
    private ClerkService clerkService ;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService ;
    @Autowired
    private WxEnterpriseService wxEnterpriseService ;
    @Autowired
    private StaffMapper staffMapper ;
    @Autowired
    private QwMomentPlanMapper qwMomentPlanMapper ;

    @Override
    public ServiceResponse<Page<QwMomentPlanAttendDTO>> attendList(PlanClerkListQDTO qdto) {
        PageHelper.startPage(qdto);
        if(StringUtils.isNotEmpty(qdto.getClerkParams())) {
            qdto.setClerkParamsLike("%"+qdto.getClerkParams()+"%");
        }
        if(StringUtils.isNotBlank(qdto.getStaffName())) {
            qdto.setStaffNameLike("%"+qdto.getStaffName()+"%");
        }
        if(StringUtils.isBlank(qdto.getSortColumn())) {
            qdto.setSortColumn("create_time");
        }
        if(StringUtils.isBlank(qdto.getSortType())) {
            qdto.setSortType("desc");
        }
        List<QwMomentPlanAttendDTO> list = this.qwMomentPlanAttendMapper.list(qdto);
        Page<QwMomentPlanAttendDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, QwMomentPlanAttendDTO.class);
        return ServiceResponse.success(retPage);
    }

    @Override
    public void saveClerk(String wxEnterpriseId , String enterpriseId, Long planId , List<String> clerkIdList) {
        List<String> existClerkIdList = this.qwMomentPlanAttendMapper.listExistClerkIds(planId,clerkIdList) ;
        if(CollectionUtils.isNotEmpty(existClerkIdList)) {
            clerkIdList = clerkIdList.stream().filter(o->!existClerkIdList.contains(o)).collect(Collectors.toList());
        }
        if(CollectionUtils.isEmpty(clerkIdList)) {
            logger.info("所有导购都已添加过");
            return ;
        }
        List<TabQwMomentPlanAttend> list = new ArrayList<>() ;
        for(String clerkId :  clerkIdList) {
            ClerkDTO clerkDTO = this.clerkService.getclerkById(clerkId) ;
            if(null != clerkDTO) {
                TabQwMomentPlanAttend attend = new TabQwMomentPlanAttend() ;
                attend.setAttendId(UniqueIdUtils.uniqueLong());
                attend.setPlanId(planId);
                attend.setWxEnterpriseId(wxEnterpriseId);
                attend.setEnterpriseId(enterpriseId);
                attend.setClerkId(clerkId);
                attend.setClerkCode(clerkDTO.getClerkCode());
                attend.setClerkName(clerkDTO.getClerkName());
                attend.setStoreId(clerkDTO.getStoreId());
                attend.setTaskStatus(1);
                attend.setStatusFlag(0);
                list.add(attend) ;
            }
        }
        this.qwMomentPlanAttendMapper.batchInsert(list);
    }


    @Override
    public ServiceResponse<TaskDetailDTO> taskDetail(Long planId, String execClerkId) {
        TaskDetailDTO dto = this.qwMomentPlanAttendMapper.taskDetail(planId,execClerkId) ;
        return ServiceResponse.success(dto);
    }

    @Override
    public ServiceResponse<Page<TaskListWxaDTO>> taskListWxa(TaskListWxaQDTO qdto) {
        PageHelper.startPage(qdto);
        List<TaskListWxaDTO> list = this.qwMomentPlanAttendMapper.taskListWxa(qdto);
        Page<TaskListWxaDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, TaskListWxaDTO.class);
        return ServiceResponse.success(retPage);
    }

    @Override
    public ServiceResponse<Void> finishTask(SendResultQDTO qdto) {
        Long planId = qdto.getPlanId() ;
        String clerkId = qdto.getClerkId() ;
        TaskDetailDTO dto = this.qwMomentPlanAttendMapper.taskDetail(planId,clerkId) ;
        if(null == dto) {
            return ServiceResponse.failure("9999","任务不存在");
        }
        this.qwMomentPlanAttendMapper.finishTask(dto.getAttendId(),qdto.getSendTime()) ;
        this.qwMomentPlanMapper.updateClerkNum(planId,-1,-1,1);
        String momentId = this.getMomentId(qdto.getStaffId() , qdto.getSendTime()) ;




        return ServiceResponse.success() ;
    }

    public String getMomentId(String staffId , Date sendTime) {
        Date startTime =  DateUtil.addNumForSecond(sendTime,-10) ;
        Date endTime = DateUtil.addNumForMinute(sendTime,1) ;
        TabHaobanStaff staff =  this.staffMapper.selectByPrimaryKey(staffId) ;
        String wxEnterpriseId = staff.getWxEnterpriseId() ;
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId) ;
        String wxUserId = staff.getWxUserId() ;
        if(qwDTO.needOpenUserId3th()) {
            wxUserId = staff.getWxOpenUseId() ;
        }
        QywxMomentInfoQDTO qywxMomentInfoQDTO = new QywxMomentInfoQDTO();
        qywxMomentInfoQDTO.setCorpid(qwDTO.getThirdCorpid());
        qywxMomentInfoQDTO.setSuiteid(qwDTO.getSelf3thSecret());
        qywxMomentInfoQDTO.setStartTime(startTime.getTime() / 1000);
        qywxMomentInfoQDTO.setEndTime(endTime.getTime() / 1000);
        qywxMomentInfoQDTO.setCreatorId(wxUserId);
        qywxMomentInfoQDTO.setPageSize(1);
        ServiceResponse<QywxMomentRespDTO> serviceResponse = qywxSuiteApiService.queryQywxMomentList(qywxMomentInfoQDTO,qwDTO.isSelf(),qwDTO.getUrlHost());
        logger.info("查询朋友圈id={},{},{}",staffId,sendTime, JSONObject.toJSONString(serviceResponse));
        List<QywxMomentRespDTO.QywxMomentInfoDTO> list = serviceResponse.getResult().getQywxMomentInfos() ;
        if(CollectionUtils.isNotEmpty(list)) {
            return list.get(0).getMomentId() ;
        }
        return null  ;
    }
}
