package com.yifu.cloud.plus.v1.business.service.system.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.business.entity.system.TBusWarning;
import com.yifu.cloud.plus.v1.business.entity.system.TBusWarningEmployee;
import com.yifu.cloud.plus.v1.business.entity.system.TBusWarningMessage;
import com.yifu.cloud.plus.v1.business.mapper.system.TBusWarningMapper;
import com.yifu.cloud.plus.v1.business.service.system.TBusWarningEmployeeService;
import com.yifu.cloud.plus.v1.business.service.system.TBusWarningMessageService;
import com.yifu.cloud.plus.v1.business.service.system.TBusWarningService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * B端预警表
 *
 * @author hgw
 * @date 2021-08-20 17:39:51
 */
@Service("tBusWarningService")
public class TBusWarningServiceImpl extends ServiceImpl<TBusWarningMapper, TBusWarning> implements TBusWarningService {

     @Autowired
     private TBusWarningEmployeeService busWarningEmployeeService;
     @Autowired
     private TBusWarningMessageService busWarningMessageService;

     /**
      * B端预警表简单分页查询
      *
      * @param tBusWarning B端预警表
      * @return
      */
     @Override
     public IPage<TBusWarning> getTBusWarningPage(Page<TBusWarning> page, TBusWarning tBusWarning) {
          return baseMapper.getTBusWarningPage(page, tBusWarning);
     }

     /**
      * 获取所有要自动发送的主表，以及人员信息进行定时任务发送短信
      *
      * @return
      * @Author:hgw
      * @Date 2021-8-23 16:47:44
      */
     @Override
     public void doBatchSendBusSms() {
          List<TBusWarning> smsInfoList = this.getTBusWarningListByAuto();
          if (Common.isNotNull(smsInfoList)) {
               List<TBusWarningEmployee> smsEmployeeList;
               for (TBusWarning smsInfo : smsInfoList) {
                    smsEmployeeList = smsInfo.getEmpList();
                    this.doSendOne(smsEmployeeList, smsInfo);
               }
          }
     }

     private void doSendOne(List<TBusWarningEmployee> smsEmployeeList, TBusWarning smsInfo) {
          if (Common.isNotNull(smsEmployeeList) && !smsEmployeeList.isEmpty()) {
               if (smsEmployeeList.size() > 100) {
                    int size = smsEmployeeList.size() / 100;
                    for (int i = 0; i <= size; i++) {
                         if ((i + 1) * 100 < smsEmployeeList.size()) {
                              this.saveBizId(smsEmployeeList.subList(i * 100, (i + 1) * 100), smsInfo);
                         } else {
                              this.saveBizId(smsEmployeeList.subList(i * 100, smsEmployeeList.size()), smsInfo);
                         }
                    }
               } else {
                    this.saveBizId(smsEmployeeList, smsInfo);
               }

          }
     }

     private void saveBizId(List<TBusWarningEmployee> smsEmployeeList, TBusWarning smsInfo) {
          List<String> phones = new ArrayList<>();
          String empName;
          ParamVo paramVo;
          List<ParamVo> params = new ArrayList<>();
          for (TBusWarningEmployee entity : smsEmployeeList) {
               phones.add(entity.getEmpPhone());
               empName = entity.getEmpName();
               if (Common.isNotNull(empName)) {
                    empName = empName.replaceAll("\\d+", "").replace("X", "");
               }
               paramVo = new ParamVo();
               paramVo.setName(empName);
               if (smsInfo.getRemindType() != 2) {
                    paramVo.setZhengjian(entity.getCertType());
               } else {
                    paramVo.setTime(entity.getNotUsedVacationDuration());
               }
               params.add(paramVo);
          }
          AliSmsResult res = YiFuSmsTookit.sendBusBatchSms(phones, params, smsInfo.getSignName(), smsInfo.getModelCode());
          if (null != res && null != res.getBizId()) {
               for (TBusWarningEmployee smsEmployee : smsEmployeeList) {
                    smsEmployee.setBizId(res.getBizId());
                    smsEmployee.setMessage(res.getMessage());
               }
          }
          busWarningEmployeeService.updateBatchById(smsEmployeeList);
     }

     /**
      * 更新当日所有发送的短信状态
      *
      * @param dateStr 格式 yyyyMMdd
      * @return
      * @Author:hgw
      * @Date 2021-8-23 16:47:52
      */
     @Override
     public void doUpdateSendBusSmsStatus(String dateStr) {
          List<TBusWarningEmployee> smsEmployeeList = busWarningEmployeeService.getTBusWarningEmployeeListToday(dateStr);
          if (Common.isNotNull(smsEmployeeList)) {
               QuerySendResult res;
               for (TBusWarningEmployee smsEmployee : smsEmployeeList) {
                    res = YiFuSmsUtil.querySendDetail(smsEmployee.getEmpPhone(), smsEmployee.getBizId(), dateStr, null, null);
                    if (null != res) {
                         smsEmployee.setMessage(res.getMessage());
                         if (null != res.getSmsSendDetailDTOs() &&
                                 Common.isNotNull(res.getSmsSendDetailDTOs().getSmsSendDetailDTO())) {
                              smsEmployee.setSendStatus(res.getSmsSendDetailDTOs().getSmsSendDetailDTO().get(0).getSendStatus().toString());
                              smsEmployee.setUpdateStatus(CommonConstants.ONE_STRING);
                         }
                    }
               }
          }
          busWarningEmployeeService.updateBatchById(smsEmployeeList);
     }

     /**
      * @param
      * @Description: 返回需要发送的主表list
      * @Author: hgw
      * @Date: 2021-8-24 18:15:02
      * @return: java.util.List<com.yifu.cloud.v1.hrms.api.entity.TBusWarning>
      **/
     private List<TBusWarning> getTBusWarningListByAuto() {
          // 回传list
          List<TBusWarning> siList = new ArrayList<>();
          // 自动发短信的list
          List<TBusWarning> autoList = baseMapper.getListByAutoSend();
          // 系统消息的list
          List<TBusWarning> sysList = baseMapper.getListBySystem();
          Map<Integer, TBusWarning> sysMap = new HashMap<>();
          for (TBusWarning b : sysList) {
               sysMap.put(b.getRemindType(), b);
          }
          YifuUser user = SecurityUtils.getUser();
          Integer userId = 737;
          if (user != null && user.getId() != null) {
               userId = Integer.valueOf(user.getId());
          }
          String monthDay = DateUtil.dateToString(new Date(), "MM-dd");
          List<TBusWarningEmployee> empList;
          // 暂存的id
          String bizId;
          TBusWarning sysBus;
          // 主循环，获取节日人员
          // RemindType提醒类型：0复审；1到期；2年假未休；3假期结束日期
          for (TBusWarning si : autoList) {
               bizId = String.valueOf(System.currentTimeMillis());
               sysBus = sysMap.get(si.getRemindType());
               if (si.getRemindRules() != null) {
                    if (si.getRemindType() == 0) {
                         busWarningEmployeeService.insertByReviewDate(si.getId(), userId, bizId, si.getRemindRules());
                    } else if (si.getRemindType() == 1) {
                         busWarningEmployeeService.insertByTermValidityEnd(si.getId(), userId, String.valueOf(System.currentTimeMillis()), si.getRemindRules());
                    }
               }
               if (si.getRemindType() == 2 && Common.isNotNull(si.getSendDate()) && si.getSendDate().equals(monthDay)) {
                    busWarningEmployeeService.insertByYearVacation(si.getId(), userId, String.valueOf(System.currentTimeMillis()));
               }
               empList = busWarningEmployeeService.getByBizId(bizId);

               // 1添加复审、到期、年假系统消息
               this.getRemindInfo(empList, sysBus, monthDay);
               si.setEmpList(empList);
               siList.add(si);
          }
          // 2添加假期结束未销假的消息
          this.getVacationInfo(sysMap.get(3));
          return siList;
     }

     private void getRemindInfo(List<TBusWarningEmployee> empList, TBusWarning sysBus, String monthDay) {
		 TBusWarningMessage message = new TBusWarningMessage();
		 if (sysBus.getRemindType() == 2 && Common.isNotNull(sysBus.getSendDate()) && sysBus.getSendDate().equals(monthDay)) {
			 String name = busWarningEmployeeService.getVacationEmpName();
			 if (Common.isNotNull(name)) {
				 message.setRemindContent(name + sysBus.getRemindTemplate());
				 message.setRemindObject(sysBus.getRemindObject());
				 message.setRemindType(sysBus.getRemindType());
				 message.setWarningId(sysBus.getId());
				 message.setCreateDate(LocalDateTime.now());
				 busWarningMessageService.save(message);
			 }
		 } else if (empList != null && !empList.isEmpty()) {
               message.setRemindContent(empList.get(0).getEmpName() + sysBus.getRemindTemplate());
               message.setRemindObject(sysBus.getRemindObject());
               message.setRemindType(sysBus.getRemindType());
               message.setWarningId(sysBus.getId());
               message.setCreateDate(LocalDateTime.now());
               busWarningMessageService.save(message);
          }
     }

     /**
      * @Description: 获取假期结束未销假的信息
      * @Author: hgw
      * @Date: 2021/8/25 13:17
      * @return: void
      **/
     private void getVacationInfo(TBusWarning sysBus) {
          String empName = busWarningEmployeeService.getVacationInfoEmpName();
          if (Common.isNotNull(empName)) {
               TBusWarningMessage message = new TBusWarningMessage();
               message.setRemindContent(empName + sysBus.getRemindTemplate());
               message.setRemindObject(sysBus.getRemindObject());
               message.setRemindType(sysBus.getRemindType());
               message.setWarningId(sysBus.getId());
               message.setCreateDate(LocalDateTime.now());
               busWarningMessageService.save(message);
          }
     }

}
