package com.foreverwin.mesnac.anomaly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.anomaly.dto.AbnormalBillDisposeDto;
import com.foreverwin.mesnac.anomaly.dto.AbnormalPlanDto;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalBillDisposeMapper;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalBillMapper;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalPlanMapper;
import com.foreverwin.mesnac.anomaly.model.AbnormalBill;
import com.foreverwin.mesnac.anomaly.model.AbnormalBillDispose;
import com.foreverwin.mesnac.anomaly.model.AbnormalPlan;
import com.foreverwin.mesnac.anomaly.service.AbnormalBillService;
import com.foreverwin.mesnac.anomaly.service.AbnormalPlanService;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.mapper.MessageMapper;
import com.foreverwin.mesnac.common.model.Message;
import com.foreverwin.mesnac.common.service.MessageService;
import com.foreverwin.mesnac.common.util.ActiveMQUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.listener.mapper.UsrMapper;
import com.foreverwin.mesnac.meapi.mapper.MessageTypeMapper;
import com.foreverwin.mesnac.meapi.mapper.UserGroupMapper;
import com.foreverwin.mesnac.meapi.model.MessageType;
import com.foreverwin.mesnac.meapi.model.NwaUser;
import com.foreverwin.mesnac.meapi.model.UserGroup;
import com.foreverwin.mesnac.meapi.service.NwaUserService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 计划异常待办事项 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-08-07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AbnormalPlanServiceImpl extends ServiceImpl<AbnormalPlanMapper, AbnormalPlan> implements AbnormalPlanService {


    @Autowired
    private AbnormalPlanMapper abnormalPlanMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private NwaUserService nwaUserService;

    @Autowired
    private ActiveMQUtil activeMQUtil;

    @Autowired
    private AbnormalBillService abnormalBillService;

    @Autowired
    private AbnormalBillMapper abnormalBillMapper;

    @Autowired
    private AbnormalBillDisposeMapper abnormalBillDisposeMapper;

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private MessageTypeMapper messageTypeMapper;

    @Autowired
    private UsrMapper usrMapper;


    @Override
    public IPage<AbnormalPlan> selectPage(FrontPage<AbnormalPlan> frontPage, AbnormalPlan abnormalPlan) {
        QueryWrapper<AbnormalPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(abnormalPlan);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<AbnormalPlan> selectList(AbnormalPlan abnormalPlan) {
        QueryWrapper<AbnormalPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(abnormalPlan);
        return super.list(queryWrapper);
    }


    @Override
    public void saveAbnormalPlan(AbnormalBillDisposeDto abnormalBillDisposeDto, LocalDateTime now) {
        String site = CommonMethods.getSite();
        AbnormalPlan abnormalPlan = new AbnormalPlan();
        String user = CommonMethods.getUser();
        //设置主键
        abnormalPlan.setHandle(HandleEnum.ABNORMAL_PLAN.getHandle(site,abnormalBillDisposeDto.getAbnormalNo()));
        abnormalPlan.setSite(site);
        abnormalPlan.setAbnormalNo(abnormalBillDisposeDto.getAbnormalNo());
        //未处理
        abnormalPlan.setStatus(Constants.UNTREATED);
        abnormalPlan.setWorkCenter(abnormalBillDisposeDto.getWorkCenter());
        abnormalPlan.setAbnormalMethod(abnormalBillDisposeDto.getAbnormalMethod());
        abnormalPlan.setShopOrder(abnormalBillDisposeDto.getShopOrder());
        abnormalPlan.setResrce(abnormalBillDisposeDto.getResrce());
        abnormalPlan.setItemBo(abnormalBillDisposeDto.getItemBo());
        if(!StringUtil.isBlank(abnormalBillDisposeDto.getNcQty())){
            abnormalPlan.setQty(Long.parseLong(abnormalBillDisposeDto.getNcQty()));
        }
        //没有处理人和处理时间
        abnormalPlan.setClosedUser(user);
        abnormalPlan.setClosedDateTime(now);
        abnormalPlan.setCreatedUser(user);
        abnormalPlan.setCreatedDateTime(now);
        abnormalPlan.setModifiedUser(user);
        abnormalPlan.setModifiedDateTime(now);
        this.saveOrUpdate(abnormalPlan);
    }

    @Override
    public void saveAbnormalPlan(AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose, LocalDateTime now) {
        AbnormalBillDisposeDto abnormalBillDisposeDto = new AbnormalBillDisposeDto();
        abnormalBillDisposeDto.setHandle(abnormalBill.getHandle());
        abnormalBillDisposeDto.setAbnormalNo(abnormalBill.getAbnormalNo());
        abnormalBillDisposeDto.setStatus(abnormalBill.getStatus());
        abnormalBillDisposeDto.setWorkCenter(abnormalBill.getWorkCenter());
        abnormalBillDisposeDto.setAbnormalMethod(abnormalBillDispose.getAbnormalMethod());
        abnormalBillDisposeDto.setShopOrder(abnormalBill.getShopOrder());
        abnormalBillDisposeDto.setResrce(abnormalBill.getResrce());
        abnormalBillDisposeDto.setItemBo(abnormalBill.getItemBo());
        abnormalBillDisposeDto.setNcQty(abnormalBill.getNcQty());
        this.saveAbnormalPlan(abnormalBillDisposeDto,now);
    }

    @Override
    public List<AbnormalPlanDto> findAbnormalPlan(AbnormalPlanDto abnormalPlanDto) {
        String site = CommonMethods.getSite();
        String locale = LocaleContextHolder.getLocale().getLanguage();
        abnormalPlanDto.setSite(site);
        return abnormalPlanMapper.findAbnormalPlan(locale,abnormalPlanDto);
    }

    @Override
    public void processes(List<AbnormalPlan> abnormalPlanList) {
        String site = CommonMethods.getSite();
        LocalDateTime now = LocalDateTime.now();
        String user = CommonMethods.getUser();

        List<AbnormalPlan> abnormalPlans = new ArrayList<>();
        List<AbnormalBill> abnormalBills = new ArrayList<>();
        for (AbnormalPlan abnormalPlan : abnormalPlanList){
            AbnormalBill abnormalBill = abnormalBillMapper.selectById(HandleEnum.ABNORMAL_BILL.getHandle(site, abnormalPlan.getAbnormalNo()));
            //设置handle
            abnormalPlan.setHandle(HandleEnum.ABNORMAL_PLAN.getHandle(site,abnormalPlan.getAbnormalNo()));

            if(Constants.PROCESSED.equals(abnormalPlan.getStatus())){
                throw new BaseException("异常单："+abnormalPlan.getAbnormalNo()+"已经处理，不能再次处理");
            }
            //设置状态为已处理
            abnormalPlan.setStatus(Constants.PROCESSED);
            //设置处理人
            abnormalPlan.setProcessor(user);
            //设置发送时间
            abnormalPlan.setSendDateTime(now);
            abnormalPlans.add(abnormalPlan);
            abnormalBills.add(abnormalBill);

        }

        //发送消息
        for(int i = 0; i < abnormalBills.size() && i < abnormalPlans.size(); i++) {
            this.sendMessage(abnormalBills.get(i),abnormalPlans.get(i));
        }
        //更新
        this.saveOrUpdateBatch(abnormalPlans);
    }

    @Override
    public void sendMessage(AbnormalBill abnormalBill, AbnormalPlan abnormalPlan) {
        //创建一个消息记录表
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        Message message = new Message();
        message.setHandle(UUID.randomUUID().toString());
        message.setSite(site);
        message.setObjectBo(abnormalPlan.getHandle());
        message.setType(Constants.ABNORMAL_MESSAGE_PLAN);
        //设置消息的类型，消息的唯一id
        MessageType messageType = messageTypeMapper.findMessageTypeByUserGroup(site, abnormalPlan.getSendUserGroup());
        if(messageType == null){
            throw new BaseException("根据发送的用户组找不到对应的消息类型，请维护。");
        }
        message.setMessageType(messageType.getMessageType());
        message.setSendUserGroup(abnormalPlan.getSendUserGroup());
        //格式化消息内容
        String messageContent = abnormalBillService.formatMessage(abnormalBill, message.getMessageType(), site);
        message.setContent(messageContent);
        message.setResponseDateTime(now);
        UserGroup customFieldByGroup = userGroupMapper.getCustomFieldByGroup(site, message.getSendUserGroup());
       //设置节点（计划异常待办事项不需要设置节点）


        if(customFieldByGroup != null && !StringUtil.isBlank(customFieldByGroup.getMessageNoticeLevel())) {
            message.setGrade(Double.parseDouble(customFieldByGroup.getMessageNoticeLevel()));
        }
        message.setStatus("Y");
        message.setCreatedUser(user);
        message.setCreatedDateTime(now);
        message.setModifiedUser(user);
        message.setModifiedDateTime(now);


        //发送消息
        List<NwaUser> nwaUsers  = nwaUserService.checkUserGroup(site,message.getSendUserGroup());
        if(nwaUsers != null && nwaUsers.size() <= 0){
            throw new BaseException("消息发送失败，发送的用户组下面没有用户");
        }
        List<String> customFieldByUserId = usrMapper.findCustomFieldByUserId(site, nwaUsers);
        if(customFieldByUserId != null && customFieldByUserId.size() <= 0){
            throw new BaseException("消息发送失败，发送的用户组下面的自定义数据没有维护");
        }
        StringBuilder sendUsers = new StringBuilder();
        for (int i = 0; i < Objects.requireNonNull(customFieldByUserId).size(); i++) {
            if(i == (customFieldByUserId.size() - 1)){
                sendUsers.append(customFieldByUserId.get(i));
            }else{
                sendUsers.append(customFieldByUserId.get(i)).append("|");
            }
        }
        activeMQUtil.wechatSendMessage(sendUsers.toString(),message.getContent());
        messageService.saveOrUpdate(message);
    }

}