package com.pusong.business.service.approver.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pusong.business.domain.PsApproverRecord;
import com.pusong.business.domain.PsCompanyInfo;
import com.pusong.business.domain.PsContractPay;
import com.pusong.business.domain.PsCustomInfo;
import com.pusong.business.domain.bo.PsApproverRecordBo;
import com.pusong.business.domain.vo.PsApproverRecordVo;
import com.pusong.business.domain.vo.PsCompanyInfoVo;
import com.pusong.business.domain.vo.PsContractPayVo;
import com.pusong.business.enums.ApproverTypeEnum;
import com.pusong.business.enums.CustomerStatusEnum;
import com.pusong.business.enums.PayStatusEnum;
import com.pusong.business.mapper.PsApproverRecordMapper;
import com.pusong.business.mapper.PsCompanyInfoMapper;
import com.pusong.business.mapper.PsContractPayMapper;
import com.pusong.business.mapper.PsCustomInfoMapper;
import com.pusong.common.core.service.UserService;
import com.pusong.common.core.utils.DateUtils;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.common.mybatis.core.page.PageQuery;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 公海认领审批
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class PublicApproverServiceImpl extends ApproverAbstractServiceImpl {
    @Override
    public String approverType() {
        return ApproverTypeEnum.PUBLIC.getCode();
    }
    private final PsCustomInfoMapper customInfoMapper;
    @Resource
    private PsApproverRecordMapper recordMapper;
    @Resource
    private final PsCompanyInfoMapper companyInfoMapper;
    private final UserService userService;
    /**
     * 1 审批成功 退款审批成功
     * @param psApproverRecord 神瀑类
     */
    @Override
    public void success(PsApproverRecord psApproverRecord) {
        PsCustomInfo info = customInfoMapper.selectById(Long.valueOf(psApproverRecord.getBusinessId()));
        info.setCustomStatus(CustomerStatusEnum.INIT.getCode());
        info.setCustomManager(Long.valueOf(psApproverRecord.getUpdateData()));
        info.setAcceptDate(new Date());
        customInfoMapper.updateById(info);
    }

    /**
     * 审批拒绝 退款审批失败
     * @param psApproverRecord
     */
    @Override
    public void fail(PsApproverRecord psApproverRecord) {
        PsCustomInfo info = customInfoMapper.selectById(Long.valueOf(psApproverRecord.getBusinessId()));
        info.setCustomStatus(CustomerStatusEnum.PUBLIC.getCode());
        info.setCustomManager(Long.valueOf(psApproverRecord.getUpdateData()));
        customInfoMapper.updateById(info);
    }

    /**
     * 查询列表
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public Page<PsApproverRecordVo> queryList(PsApproverRecordBo bo, PageQuery pageQuery){
        QueryWrapper<PsApproverRecord> lqw = Wrappers.<PsApproverRecord>query().eq("app.business_type",approverType())
                .eq(bo.getId()!=null,"app.id",bo.getId())
                .like(StringUtils.isNotBlank(bo.getCustomerName()),"cus.custom_name",bo.getCustomerName())
                .exists(StringUtils.isNotBlank(bo.getCustomManagerName()),"select 1 from sys_user su where su.user_id = app.update_data and su.nick_name like '%" + bo.getCustomManagerName() + "%'")
                .exists(StringUtils.isNotBlank(bo.getCompanyName()),"select 1 from ps_company_info com where cus.id = com.custom_id and com.company_name like '%" + bo.getCompanyName() + "%'")
                .eq(StringUtils.isNotBlank(bo.getApproverStatus()),"app.approver_status",bo.getApproverStatus())
                .orderByAsc("app.approver_status").orderByAsc("app.approver_date");;
        Page<PsApproverRecordVo> res = recordMapper.selectPagePublicList(pageQuery.build(), lqw);
        if(CollectionUtils.isEmpty(res.getRecords())){
            return res;
        }
        //装填公司信息
        List<Long> ids = res.getRecords().stream().map(PsApproverRecordVo::getCustomId).collect(Collectors.toList());
        List<PsCompanyInfoVo> companyInfoVos = companyInfoMapper.selectVoList(Wrappers.<PsCompanyInfo>lambdaQuery()
                .in(PsCompanyInfo::getCustomId, ids)
                .eq(PsCompanyInfo::getDelFlag, 0));
        Map<Long, List<PsCompanyInfoVo>> id_companyMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(companyInfoVos)){
            //分组
            id_companyMap = companyInfoVos.stream().collect((Collectors.groupingBy(PsCompanyInfoVo::getCustomId)));
            //排序
            id_companyMap.entrySet().forEach(entry->{
                entry.setValue(entry.getValue().stream().sorted(Comparator.comparingLong(PsCompanyInfoVo::getId)).collect(Collectors.toList()));
            });
        }
        for (PsApproverRecordVo info : res.getRecords()) {
            info.setCompanyInfoList(id_companyMap.get(info.getCustomId()));
            //最早的公司名称
            if(CollectionUtils.isNotEmpty(info.getCompanyInfoList())){
                //找到最近修改的公司名称
                info.setCompanyName(info.getCompanyInfoList().stream().max(Comparator.comparingLong(item -> item.getUpdateTime().getTime()))
                        .orElse(new PsCompanyInfoVo()).getCompanyName());
                info.setCompanyNum(info.getCompanyInfoList().size());
            }else{
                info.setCompanyNum(0);
            }
            //认领人id转姓名
            info.setUpdateData(userService.selectNicknameById(Long.valueOf(info.getUpdateData())));
        }
        return res;
    }
}
