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.clerk.api.service.PowerService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.EnterpriseSettingDTO;
import com.gic.enterprise.api.dto.StoreSearchDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.enterprise.api.service.StoreWidgetService;
import com.gic.haoban.manage.api.dto.ContentMaterialDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanAttendDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanDTO;
import com.gic.haoban.manage.api.qdto.moment.QwMomentPlanQDTO;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
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.moment.TabQwMomentPlan;
import com.gic.haoban.manage.service.service.QywxSendService;
import com.gic.haoban.manage.service.service.moment.QwMomentPlanAttendService;
import com.gic.haoban.manage.service.service.moment.QwMomentPlanService;
import com.gic.quartz.api.dto.QuartzTaskDTO;
import com.gic.quartz.api.service.QuartzService;
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.*;
import java.util.stream.Collectors;

@Service("qwMomentPlanService")
public class QwMomentPlanServiceImpl implements QwMomentPlanService {

    private final Logger logger = LogManager.getLogger(this.getClass());
    @Autowired
    private QwMomentPlanMapper qwMomentPlanMapper ;
    @Autowired
    private QwMomentPlanAttendService qwMomentPlanAttendService ;
    @Autowired
    private QwMomentPlanAttendMapper qwMomentPlanAttendMapper ;
    @Autowired
    private QuartzService quartzService;
    @Autowired
    private ClerkService clerkService ;
    @Autowired
    private EnterpriseService enterpriseService ;
    @Autowired
    private StoreService storeService ;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private PowerService powerService ;
    @Autowired
    private StoreWidgetService storeWidgetService ;
    @Autowired
    private QywxSendService qywxSendService ;

    @Override
    public ServiceResponse<Page<QwMomentPlanDTO>> planList(QwMomentPlanQDTO qdto) {
        PageHelper.startPage(qdto);
        if(StringUtils.isNotEmpty(qdto.getNameParams())) {
            qdto.setNameParamsLike("%"+qdto.getNameParams()+"%");
        }
        if(StringUtils.isBlank(qdto.getSortColumn())) {
            qdto.setSortColumn("create_time");
        }
        if(StringUtils.isBlank(qdto.getSortType())) {
            qdto.setSortType("desc");
        }
        List<TabQwMomentPlan> list = this.qwMomentPlanMapper.list(qdto);
        Page<QwMomentPlanDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, QwMomentPlanDTO.class);
        return ServiceResponse.success(retPage);
    }

    @Override
    public ServiceResponse<QwMomentPlanDTO> save(QwMomentPlanDTO dto) {
        logger.info("保存朋友圈活动={}", JSONObject.toJSONString(dto));
        String enterpriseId = dto.getEnterpriseId() ;
        Long planId = dto.getPlanId() ;
        TabQwMomentPlan plan = EntityUtil.changeEntity(TabQwMomentPlan.class,dto) ;
        Date now = new Date() ;
        plan.setUpdateTime(now);
        // 1立即发布2定时发布
        if(plan.getPublishType()==1) {
            plan.setPublishTime(now);
        }
        boolean createFlag = false ;
        boolean publishFlag = false ;
        plan.setBeginDate(plan.getPublishTime());
        Date endTime = DateUtil.addDay(plan.getBeginDate(), plan.getExpireDays());
        plan.setEndDate(endTime);
        if(null == planId) {
            createFlag = true ;
            planId = UniqueIdUtils.uniqueLong();
            dto.setPlanId(planId);
            plan.setPlanId(planId);
            plan.setCreateTime(now);
            plan.setStatusFlag(1);
            this.qwMomentPlanMapper.insert(plan);
        }else {
            TabQwMomentPlan oldPlan = this.qwMomentPlanMapper.getById(planId) ;
            // 更新为立即发布
            if(oldPlan.getPublishType()==2 && plan.getPublishType()==1) {
                publishFlag = true ;
            }
            this.qwMomentPlanMapper.update(plan);
        }
        // 参与导购
        if(dto.getPlanClerkType()==1) {
            if (createFlag) {
                this.qwMomentPlanAttendService.saveClerk(enterpriseId, planId,dto.getSelectClerkIdList());
            } else {
                List<String> oldList = this.qwMomentPlanAttendMapper.listClerk(planId).stream().map(o -> o.getClerkId()).collect(Collectors.toList());
                List<String> newList = dto.getSelectClerkIdList();
                List<String> addList = newList.stream().filter(o -> !oldList.contains(o)).distinct().collect(Collectors.toList());
                List<String> delList = oldList.stream().filter(o -> !newList.contains(o)).distinct().collect(Collectors.toList());
                this.qwMomentPlanAttendService.saveClerk(enterpriseId, planId , addList);
                if (CollectionUtils.isNotEmpty(delList)) {
                    this.qwMomentPlanAttendMapper.delClerks(planId, delList);
                }
            }
        }

        if(plan.getPublishType()==2) {
            this.addOrDelTimer(planId, plan.getPublishTime(), 1);
        }else {
            this.addOrDelTimer(planId, new Date(), 0);
            if(createFlag || publishFlag) {
               JSONObject jsonObject = new JSONObject() ;
                jsonObject.put("planId",planId) ;
                this.initTaskClerk(jsonObject.toJSONString());
                try {
                  //  clientInstance.sendMessage("clerkTaskInitClerkMQ", jsonObject.toJSONString(),10);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return ServiceResponse.success(dto);
    }

    private void sendTaskToClerk(String enterpriseId,String clerkId ,  Long planId) {
        logger.info("发送任务通知,clerkId={}",clerkId);
        //  发送通知
        Map<String, String> map = new HashMap<String, String>();
        int messageType = 0 ; // NoticeMessageTypeEnum.CLERK_TASK_SEND_NOTICE.getType();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("planId",planId) ;
        // NoticeMessageUtil.sendNoticeMessage(enterpriseId,clerkId,messageType,null,map,jsonObject);
    }


    @Override
    public ServiceResponse<Void> del(Long planId) {
        this.qwMomentPlanMapper.del(planId);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> stop(Long planId) {
        this.qwMomentPlanMapper.stop(planId);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<QwMomentPlanDTO> detail(Long planId) {
        TabQwMomentPlan plan = this.qwMomentPlanMapper.getById(planId);
        QwMomentPlanDTO dto = EntityUtil.changeEntityByJSON(QwMomentPlanDTO.class,plan) ;
        return ServiceResponse.success(dto);
    }

    private void addOrDelTimer(Long planId, Date sendTime, int status) {
        logger.info("添加1/删除0定时,{},{}", status, planId);
        QuartzTaskDTO quartzTask = new QuartzTaskDTO();
        quartzTask.setTaskStatus(status);
        String taskTimeInfo = this.getTaskTime(sendTime);
        quartzTask.setTaskTimeInfo(taskTimeInfo);
        quartzTask.setTaskService("com.gic.haoban.manage.api.service.moment.QwMomentApiService");
        quartzTask.setTaskMethod("sendPlanNoticeTimer");
        quartzTask.setTaskParam(planId + "");
        quartzTask.setReferId(planId + "");
        try {
            quartzService.addOrUpdateQuartzTask(quartzTask);
        } catch (Exception e) {
            logger.warn("提交定时任务异常", e);
        }
    }

    private String getTaskTime(Date date) {
        String timeInfo = DateUtil.dateToStr(date, "yyyyMMddHHmmss");
        String year = timeInfo.substring(0, 4);
        int month = Integer.parseInt(timeInfo.substring(4, 6));
        int day = Integer.parseInt(timeInfo.substring(6, 8));
        int hour = Integer.parseInt(timeInfo.substring(8, 10));
        int minute = Integer.parseInt(timeInfo.substring(10, 12));
        int second = Integer.parseInt(timeInfo.substring(12, 14));
        String time = new StringBuilder().append(second).append(" ").append(minute).append(" ").append(hour).append(" ")
                .append(day).append(" ").append(month).append(" ").append(year).toString();
        return time;
    }


    private void saveAttendClerkForTask(Long planId) {
        TabQwMomentPlan plan = this.qwMomentPlanMapper.getById(planId) ;
        String creatorId = plan.getCreatorId() ;
        String enterpriseId = plan.getEnterpriseId() ;
        ClerkDTO clerkDTO = this.clerkService.getclerkById(creatorId) ;
        EnterpriseSettingDTO enterpriseSetting = enterpriseService.getEnterpriseSettingByEnterpriseId(enterpriseId);
        List<String> storeIdList = null ;
        if(clerkDTO.getClerkType()==3 || !(enterpriseSetting.getEnableAccessControl() != null && enterpriseSetting.getEnableAccessControl() == 1)) {
            logger.info("超管");
            StoreSearchDTO searchDTO = new StoreSearchDTO() ;
            searchDTO.setEnterpriseId(plan.getEnterpriseId());
            searchDTO.setStatus("2");
            storeIdList = this.storeService.listStoreIds(searchDTO) ;
        }else {
            storeIdList = this.getStoreIdList(clerkDTO) ;
        }
        List<StaffClerkRelationDTO> list = this.staffClerkRelationApiService.listByStoreIds(null , storeIdList) ;
        List<String> clerkIdList = list.stream().map(o->o.getClerkId()).collect(Collectors.toList()) ;
        Page<ClerkDTO> userPage = this.clerkService.pageUserBySearchName(plan.getEnterpriseId(),null,1,1000) ;
        List<String> userIdList = userPage.getResult().stream().map(o->o.getClerkId()).collect(Collectors.toList());
        logger.info("管理员列表={}",userIdList);
        clerkIdList.stream().filter(o->!userIdList.contains(o)).collect(Collectors.toList()) ;
        logger.info("导购数量={}",clerkIdList.size());
        this.qwMomentPlanAttendService.saveClerk(plan.getEnterpriseId(),planId, clerkIdList);
        this.qwMomentPlanMapper.updateClerkNum(planId,clerkIdList.size(),-1,-1);
    }

    private List<String> getStoreIdList(ClerkDTO clerkDTO) {
        String clerkId = clerkDTO.getClerkId();
        String enterpriseId = clerkDTO.getEnterpriseId();
        String storeWidgetId = this.powerService.getStoreWidgetId(null, clerkId);
        // 门店id列表
        List<String> storeIdList = storeWidgetService.getStoreWidgetStore(storeWidgetId, enterpriseId, null, null, 2);
        logger.info("组件id={},上线数量:{}", storeWidgetId,storeIdList.size());
        if (CollectionUtils.isEmpty(storeIdList)) {
            return Collections.emptyList();
        }
        return storeIdList;
    }

    @Override
    public void initTaskClerk(String params) {
        JSONObject json = JSONObject.parseObject(params) ;
        Long planId = json.getLong("planId") ;
        TabQwMomentPlan plan = this.qwMomentPlanMapper.getById(planId) ;
        // 0全部导购 1部分导购
        if(plan.getPlanClerkType()==0) {
            this.saveAttendClerkForTask(planId) ;
        }
        this.sendPlanNotice(plan);
    }

    // 发送活动通知
    private void sendPlanNotice(TabQwMomentPlan plan) {
        if(plan.getPublishType()==1 || plan.getPublishTime().getTime() <= System.currentTimeMillis()) {
            long planId = plan.getPlanId();
            if(plan.getExecType()==1) {
                // 好办小程序
                List<QwMomentPlanAttendDTO> list = this.qwMomentPlanAttendMapper.listClerk(planId);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (QwMomentPlanAttendDTO dto : list) {
                        this.sendTaskToClerk(plan.getEnterpriseId(), dto.getClerkId(), plan.getPlanId());
                    }
                }
            }else {
                // 企微下发任务
                this.sendToQiwei(plan);
            }
        }
    }

    private void sendToQiwei(TabQwMomentPlan plan) {
        List<ContentMaterialDTO> imageList = new ArrayList<>() ;
        ContentMaterialDTO d1 = new ContentMaterialDTO();
        d1.setMaterialType(2);
        d1.setImgUrl("https://platform-1251519181.cos.ap-shanghai.myqcloud.com/image/jhdm/common-8ed0204b143c4cc0803ec153cd51f481.png?imageView2/format/jpg/q/50");
        imageList.add(d1) ;
        ServiceResponse<String> resp = this.qywxSendService.share(plan.getWxEnterpriseId(),Arrays.asList("b2ef17cce11f476b996d0b27ebadf7fb"),"朋友圈",imageList) ;
        logger.info("发企微朋友={}",JSONObject.toJSONString(resp));
    }

    @Override
    public void sendPlanNoticeTimer(String params) {
        logger.info("定时发布任务发送通知={}",params);
        Long planId = Long.valueOf(params) ;
        TabQwMomentPlan plan = this.qwMomentPlanMapper.getById(planId) ;
        // 0全部导购 1部分导购
        if(plan.getPlanClerkType()==0) {
            this.saveAttendClerkForTask(planId) ;
        }
        this.sendPlanNotice(plan);
    }
}
