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.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.qdto.moment.QwMomentPlanQDTO;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
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.moment.QwMomentPlanAttendService;
import com.gic.haoban.manage.service.service.moment.QwMomentPlanService;
import org.apache.commons.collections.CollectionUtils;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 ;

    @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 ;
        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 {
            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(CollectionUtils.isNotEmpty(addList)) {
                    for(String clerkId : addList) {
                        this.sendTaskToClerk(plan.getEnterpriseId(),clerkId,plan.getPlanId());
                    }
                }
            }
        }
        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);
    }

    @Override
    public ServiceResponse<Page<QwMomentPlanDTO>> planList(QwMomentPlanQDTO qdto) {
        return null;
    }


}
