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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.controller.req.ReportReq;
import com.ruoyi.enums.process.ProcessResultEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.report.entity.Report;
import com.ruoyi.frequency.report.mapper.ReportMapper;
import com.ruoyi.frequency.report.service.ReportService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 举报用户Service业务层处理
 *
 * @author liwenlong
 * @date 2023-11-17
 */
@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report>  implements ReportService
{
    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private UserService userService;
    /**
     * 查询举报用户
     *
     * @param id 举报用户主键
     * @return 举报用户
     */
    @Override
    public Report selectReportById(Long id)
    {
        Report report = reportMapper.selectReportById(id);
        if (report != null){
            Set<UserVo> userVoSet = CollectionUtil.newHashSet(new UserVo(report.getUserType(), report.getUserId()),new UserVo(report.getReportUserType(), report.getReportUserId()));

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

            report.setUserInfo(userMap.get(new UserVo(report.getUserType(), report.getUserId())));
            report.setReportUserInfo(userMap.get(new UserVo(report.getReportUserType(), report.getReportUserId())));
        }

        return report;
    }

    /**
     * 查询举报用户列表
     *
     * @param report 举报用户
     * @return 举报用户
     */
    @Override
    public List<Report> selectReportList(Report report)
    {
        List<Report> reports = reportMapper.selectReportList(report);

        if (reports.size() > 0){
            Set<UserVo> userVoSet = CollectionUtil.newHashSet();
            reports.stream().forEach(s->{
                userVoSet.add(new UserVo(s.getUserType(), s.getUserId()));
                userVoSet.add(new UserVo(s.getReportUserType(), s.getReportUserId()));
            });

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

            reports.stream().forEach(s ->{
                s.setUserInfo(userMap.get(new UserVo(s.getUserType(), s.getUserId())));
                s.setReportUserInfo(userMap.get(new UserVo(s.getReportUserType(), s.getReportUserId())));
            });
        }
        return reports;
    }

    /**
     * 新增举报用户
     *
     * @param report 举报用户
     * @return 结果
     */
    @Override
    public int insertReport(Report report)
    {
        report.setCreateData();
        return reportMapper.insert(report);
    }

    /**
     * 修改举报用户
     *
     * @param report 举报用户
     * @return 结果
     */
    @Override
    public int updateReport(Report report)
    {
        report.setUpdateData();
        return reportMapper.updateReport(report);
    }

    /**
     * 批量删除举报用户
     *
     * @param ids 需要删除的举报用户主键
     * @return 结果
     */
    @Override
    public int deleteReportByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(Report::getDelFlag,delFlag).in(Report::getId,ids).update();
        return ids.length;
    }


    @Override
    public AjaxResult handle(Report report) {

        boolean update = this.lambdaUpdate().set(Report::getResult, report.getResult())
                .eq(Report::getResult, ProcessResultEnums.PENDING.getCode())
                .eq(Report::getId, report.getId()).update();
        //处理（审核通过）
        if (update && ObjectUtil.equal(ProcessResultEnums.APPROVED.getCode(), report.getResult())) {
//            Report byId = this.getById(report.getId());
        }
        return AjaxResult.success();
    }

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StoreService storeService;


    @Override
    public ResponseData report(ReportReq req, UserVo userVo) {

        userService.storeByEnterprise(userVo);

        Long userId = null;

        if (req.getUserId().startsWith("SJS")){
            //判断设计师是否存在
            Customer customer = customerService.getOne(new QueryWrapper<Customer>().lambda().ne(Customer::getDelFlag, PublicCommon.删除)
                    .eq(Customer::getNickname, req.getUserId())
            );
            if (ObjectUtil.isNull(customer)){
                return ResponseData.error("设计师不存在");
            } else if (customer.getDelFlag().equals(PublicCommon.禁用)) {
                return ResponseData.error("设计师已被禁用");
            }

            userId = customer.getId();
            req.setUserType(UserEnums.customer.getCode());

        }else if (req.getUserId().startsWith("BXS")){
            //判断设计师是否存在
            Store store = storeService.getOne(new QueryWrapper<Store>().lambda().ne(Store::getDelFlag, PublicCommon.删除)
                    .eq(Store::getNickname, req.getUserId())
            );
            if (ObjectUtil.isNull(store)){
                return ResponseData.error("表现师不存在");
            } else if (store.getDelFlag().equals(PublicCommon.禁用)) {
                return ResponseData.error("表现师已被禁用");
            }

            userId = store.getId();
            req.setUserType(UserEnums.store.getCode());
        }else {
            return ResponseData.error("用户不存在");
        }

        Report report = new Report()
                .setReportUserType(req.getUserType())
                .setReportUserId(userId)
                .setUserType(userVo.getUserType())
                .setUserId(userVo.getUserId())
                .setReason(req.getReason())
                .setContent(req.getContent())
                .setImages(req.getImages());
        this.save(report);

        return ResponseData.success();
    }
}
