package com.ruoyi.frequency.appealdetail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.controller.req.AppealMessagePageReq;
import com.ruoyi.controller.req.SendMessageReq;
import com.ruoyi.controller.resp.AppealMessagePageResp;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.appeal.entity.Appeal;
import com.ruoyi.frequency.appeal.mapper.AppealMapper;
import com.ruoyi.frequency.appealdetail.entity.AppealDetail;
import com.ruoyi.frequency.appealdetail.mapper.AppealDetailMapper;
import com.ruoyi.frequency.appealdetail.service.AppealDetailService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.ordermessage.service.OrderMessageService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 申诉详情Service业务层处理
 *
 * @author zj
 * @date 2023-10-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AppealDetailServiceImpl extends ServiceImpl<AppealDetailMapper, AppealDetail> implements AppealDetailService {
    @Autowired
    private AppealDetailMapper appealDetailMapper;

    /**
     * 查询申诉详情
     *
     * @param id 申诉详情主键
     * @return 申诉详情
     */
    @Override
    public AppealDetail selectAppealDetailById(Long id) {
        return appealDetailMapper.selectAppealDetailById(id);
    }

    /**
     * 查询申诉详情列表
     *
     * @param appealDetail 申诉详情
     * @return 申诉详情
     */
    @Override
    public List<AppealDetail> selectAppealDetailList(AppealDetail appealDetail) {

        List<AppealDetail> appealDetails = appealDetailMapper.selectAppealDetailList(appealDetail);

        if (!appealDetails.isEmpty()) {
            Set<UserVo> userVoSet = appealDetails.stream().map(s -> new UserVo(s.getSendUserType(), s.getSendUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            appealDetails.stream().forEach(s -> {
                s.setUserInfo(userMap.get(new UserVo(s.getSendUserType(), s.getSendUserId())));
            });
        }

        return appealDetails;
    }

    /**
     * 新增申诉详情
     *
     * @param appealDetail 申诉详情
     * @return 结果
     */
    @Override
    public int insertAppealDetail(AppealDetail appealDetail) {
        return appealDetailMapper.insertAppealDetail(appealDetail);
    }

    /**
     * 修改申诉详情
     *
     * @param appealDetail 申诉详情
     * @return 结果
     */
    @Override
    public int updateAppealDetail(AppealDetail appealDetail) {
        appealDetail.setUpdateTime(DateUtils.getNowDate());
        return appealDetailMapper.updateAppealDetail(appealDetail);
    }

    /**
     * 批量删除申诉详情
     *
     * @param ids 需要删除的申诉详情主键
     * @return 结果
     */
    @Override
    public int deleteAppealDetailByIds(Long[] ids) {
        this.lambdaUpdate().set(AppealDetail::getDelFlag, PublicCommon.删除).in(AppealDetail::getId, ids).update();
        return ids.length;
    }

    /**
     * 删除申诉详情信息
     *
     * @param id 申诉详情主键
     * @return 结果
     */
    @Override
    public int deleteAppealDetailById(Long id) {
        this.lambdaUpdate().set(AppealDetail::getDelFlag, PublicCommon.删除).eq(AppealDetail::getId, id).update();
        return 1;
    }

    @Autowired
    private UserService userService;

    @Override
    public ResponseData<PageResult<Page<AppealMessagePageResp>>> appealMessagePage(AppealMessagePageReq req, UserVo userVo) {

        Page<AppealMessagePageResp> page = appealDetailMapper.appealMessagePage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);
//        page.getRecords().sort(Comparator.comparing(AppealMessagePageResp::getCreateTime));

        if (!page.getRecords().isEmpty()) {

            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getSendUserType(), resp.getSendUserId())).collect(Collectors.toSet());

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, userVo);

            page.getRecords().stream().forEach(resp -> {
                resp.setSendUserInfo(userMap.get(new UserVo(resp.getSendUserType(), resp.getSendUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Autowired
    private OrderMessageService orderMessageService;

    @Autowired
    private AppealMapper appealMapper;

    @Autowired
    private BusinessUtil businessUtil;

    @Override
    public ResponseData sendMessage(SendMessageReq req, UserVo userVo) {
        AppealDetail appealDetail = new AppealDetail();
        BeanUtil.copyProperties(req, appealDetail);
        appealDetail.setSendUserId(userVo.getUserId())
                .setSendUserType(userVo.getUserType());
        boolean save = this.save(appealDetail);

        if (save) {
            Appeal appeal = appealMapper.selectById(req.getAppealId());

            UserVo sendMessageUserVo = new UserVo();
            if (appeal != null) {
                if (appeal.getAppealUserId().equals(userVo.getUserId()) && appeal.getAppealUserType().equals(userVo.getUserType())) {
                    sendMessageUserVo.setUserId(appeal.getPassiveAppealUserId());
                    sendMessageUserVo.setUserType(appeal.getPassiveAppealUserType());
                } else {
                    sendMessageUserVo.setUserId(appeal.getAppealUserId());
                    sendMessageUserVo.setUserType(appeal.getAppealUserType());
                }
            }


            String nickname = (String) businessUtil.getUserFieldValue(userVo, "nickname");

            //发送消息提醒用户
            orderMessageService.addOrderMessage(sendMessageUserVo, appeal.getOrderId(), "", PublicCommon.Order.订单, OrderMessageEnums.APPEAL_MESSAGE,
                    ObjectUtil.equal(UserEnums.store.getCode(), userVo.getUserType()) ? "表现师" : "设计师" + nickname);
        }

        return ResponseData.success();
    }
}
