package com.red.circle.other.app.inner.service.sys.impl;

import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateCustomizeCmd;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.inner.convertor.sys.FeedbackInnerConvertor;
import com.red.circle.other.app.inner.service.sys.FeedbackClientService;
import com.red.circle.other.infra.database.rds.entity.sys.SysFeedback;
import com.red.circle.other.infra.database.rds.enums.FeedbackApprovalStatusEnum;
import com.red.circle.other.infra.database.rds.service.sys.SysFeedbackService;
import com.red.circle.other.inner.model.cmd.sys.BatchProcessFeedbackCmd;
import com.red.circle.other.inner.model.cmd.sys.SysFeedbackQryCmd;
import com.red.circle.other.inner.model.dto.sys.SysFeedbackDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户反馈 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2019-10-28
 */
@Service
@RequiredArgsConstructor
public class FeedbackClientServiceImpl implements
    FeedbackClientService {

  private final SysFeedbackService feedbackService;
  private final OfficialNoticeClient officialNoticeClient;
  private final FeedbackInnerConvertor feedbackInnerConvertor;


  @Override
  public PageResult<SysFeedbackDTO> pageSysFeedbackVO(SysFeedbackQryCmd query) {

    PageResult<SysFeedback> sysFeedbackPage = getSysFeedbackPage(query);

    if (CollectionUtils.isEmpty(sysFeedbackPage.getRecords())) {
      return sysFeedbackPage.convert(feedbackInnerConvertor::toSysFeedbackDTO);
    }
    sysFeedbackPage.getRecords().stream().map(SysFeedback::getUpdateUser)
        .filter(Objects::nonNull).collect(Collectors.toSet());

    return sysFeedbackPage.convert(
        sysFeedback -> feedbackInnerConvertor.toSysFeedbackDTO(sysFeedback)
            .setApprovalStatusName(
                FeedbackApprovalStatusEnum.getDes(sysFeedback.getApprovalStatus()))
    );
  }

  private PageResult<SysFeedback> getSysFeedbackPage(SysFeedbackQryCmd query) {
    return feedbackService.query()
        .eq(Objects.nonNull(query.getApprovalStatus()), SysFeedback::getApprovalStatus,
            query.getApprovalStatus())
        .eq(StringUtils.isNotEmpty(query.getSysOrigin()), SysFeedback::getSysOrigin,
            query.getSysOrigin())
        .eq(Objects.nonNull(query.getUserId()), SysFeedback::getUserId, query.getUserId())
        .eq(Objects.nonNull(query.getUpdateUserId()), SysFeedback::getUpdateUser,
            query.getUpdateUserId())
        .orderByDesc(SysFeedback::getCreateTime)
        .page(query.getPageQuery());
  }

  @Override
  public void updateApprovalStatus(Long updateUserId, Long id, Integer status) {
    feedbackService.update().set(SysFeedback::getUpdateUser, updateUserId)
        .set(SysFeedback::getApprovalStatus, status)
        .eq(SysFeedback::getId, id)
        .execute();
  }

  @Override
  public void updateApprovalRemarks(Long userId, Long id, String remarks) {
    feedbackService.update().set(SysFeedback::getUpdateUser, userId)
        .set(SysFeedback::getApprovalRemarks, remarks)
        .eq(SysFeedback::getId, id)
        .execute();
  }

  @Override
  public void updateRemarksAndNotice(Long updateUserId, Long userId, Long id, String remarks) {
    feedbackService.update()
        .set(SysFeedback::getUpdateUser, updateUserId)
        .set(SysFeedback::getApprovalRemarks, remarks)
        .set(SysFeedback::getApprovalStatus, 1)
        .eq(SysFeedback::getId, id)
        .execute();
    if (StringUtils.isNotEmpty(remarks) && !Objects.equals(userId, 0L)) {

      /*officialNoticeClient.send(NoticeExtTemplateCustomizeCmd.builder().toAccount(userId)
          .noticeType(OfficialNoticeTypeEnum.FEEDBACK_PROCESS)
          .content(remarks).build());*/
    }
  }

  @Override
  public void batchUpdateRemarksAndNotice(BatchProcessFeedbackCmd cmd) {
    if (CollectionUtils.isEmpty(cmd.getProcessFeedbacks())) {
      return;
    }
    //批量修改审批状态
    feedbackService.updateBatchById(cmd.getProcessFeedbacks().stream().map(feedbackParam -> {
          var feedback = feedbackInnerConvertor.toSysFeedback(feedbackParam);
          feedback.setUpdateUser(cmd.getReqUserId());
          return feedback;
        })

        .collect(Collectors.toList()));
    //批量发送通知
    Set<Long> userIds = new HashSet<>();
    cmd.getProcessFeedbacks().forEach(feedbackParam -> {
      if (!Objects.equals(feedbackParam.getUserId(), 0L)) {
        userIds.add(feedbackParam.getUserId());
      }
    });
    if (CollectionUtils.isNotEmpty(userIds)) {
      /*officialNoticeClient.send(
          NoticeExtTemplateTypeCmd.builder().toAccounts(new ArrayList<>(userIds))
              .noticeType(OfficialNoticeTypeEnum.FEEDBACK_PROCESS).build());*/
    }
  }
}
