package com.fjhx.account.service.account.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.account.entity.account.dto.AccountRequestFundsDto;
import com.fjhx.account.entity.account.dto.AccountRequestFundsSelectDto;
import com.fjhx.account.entity.account.po.AccountRequestFunds;
import com.fjhx.account.entity.account.po.AccountRequestFundsDetail;
import com.fjhx.account.entity.account.vo.AccountRequestFundsVo;
import com.fjhx.account.mapper.account.AccountRequestFundsMapper;
import com.fjhx.account.service.account.AccountRequestFundsDetailService;
import com.fjhx.account.service.account.AccountRequestFundsService;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.entity.corporation.po.Corporation;
import com.fjhx.common.service.corporation.CorporationService;
import com.fjhx.flow.entity.flow.po.FlowExample;
import com.fjhx.flow.entity.flow.po.FlowInfo;
import com.fjhx.flow.service.flow.FlowExampleService;
import com.fjhx.flow.service.flow.FlowInfoService;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 * 请款表 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-10
 */
@Service
public class AccountRequestFundsServiceImpl extends ServiceImpl<AccountRequestFundsMapper, AccountRequestFunds> implements AccountRequestFundsService {
    @Autowired
    private CorporationService corporationService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private AccountRequestFundsDetailService accountRequestFundsDetailService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private FlowExampleService flowExampleService;

    /**
     * 查询请款列表
     * @param dto
     * @return
     */
    @Override
    public Page<AccountRequestFundsVo> getPage(AccountRequestFundsSelectDto dto) {
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getType()),"arf.type",dto.getType());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getStatus()),"arf.status",dto.getStatus());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getPaymentStatus()),"ap.status",dto.getPaymentStatus());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getKeyword()),"arf.payment_remarks",dto.getKeyword());
        wrapper.orderByDesc("ap.status","arf.payment_time","arf.create_time");
        Page<AccountRequestFundsVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        //赋值部门名称、归属公司名称
        List<AccountRequestFundsVo> records = page.getRecords();
        if(ObjectUtil.isEmpty(records)){
            return page;
        }

        //切换数据源
        DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
        //查询公司名称信息
        List<Corporation> corporationList = corporationService.list();
        Map<Long, List<Corporation>> corporationMap = corporationList.stream().collect(Collectors.groupingBy(Corporation::getId));
        DynamicDataSourceContextHolder.poll();


        //切换数据源
        DynamicDataSourceContextHolder.push(SourceConstant.BASE);
        //查询部门信息
        List<SysDept> sysDeptList = sysDeptService.list();
        Map<Long, List<SysDept>> sysDeptMap = sysDeptList.stream().collect(Collectors.groupingBy(SysDept::getDeptId));

        //根据业务ID列表获取流程实例Id列表
        List<Long> ids = records.stream().map(AccountRequestFundsVo::getId).collect(Collectors.toList());
        List<FlowExample> flowExamples = flowExampleService.list(Wrappers.<FlowExample>lambdaQuery().in(FlowExample::getBusinessId, ids));
        Map<Long, List<FlowExample>> flowInfoMap = flowExamples.stream().collect(Collectors.groupingBy(FlowExample::getBusinessId));


        for (AccountRequestFundsVo record : records) {
            //赋值部门信息
            List<SysDept> sysDepts = sysDeptMap.get(record.getDepartmentId());
            if (ObjectUtil.isNotEmpty(sysDepts)){
                record.setDeptName(sysDepts.get(0).getDeptName());
            }

            //赋值公司信息
            List<Corporation> corporations = corporationMap.get(record.getCorporationId());
            if (ObjectUtil.isNotEmpty(corporations)){
                record.setCorporationName(corporations.get(0).getName());
            }

            //赋值流程ID
            List<FlowExample> flowInfoList = flowInfoMap.get(record.getId());
            if (ObjectUtil.isEmpty(flowInfoList)){
                throw new ServiceException("数据有误：该请款没有找到流程详情信息信息");
            }
            record.setFlowInfoId(flowInfoList.get(0).getId());
        }

        // 赋值用户名称
        UserUtil.assignmentNickName(records, BasePo::getCreateUser,AccountRequestFundsVo::setUserName);
        DynamicDataSourceContextHolder.poll();
        return page;
    }

    /**
     * 查询请款详情
     * @param id
     * @return
     */
    @Override
    public AccountRequestFundsVo detail(Long id){
        AccountRequestFunds accountRequestFunds = this.getById(id);
        AccountRequestFundsVo accountRequestFundsVo = BeanUtil.toBean(accountRequestFunds, AccountRequestFundsVo.class);

        //获取到请款明细信息
        List<AccountRequestFundsDetail> accountRequestFundsDetailList = accountRequestFundsDetailService
                .list(Wrappers.<AccountRequestFundsDetail>lambdaQuery()
                        .eq(AccountRequestFundsDetail::getAccountRequestFundsId, accountRequestFunds.getId()));
        accountRequestFundsVo.setAccountRequestFundsDetailList(accountRequestFundsDetailList);

        //切换数据源
        DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
        //查询归属公司的名称
        Corporation corporation = corporationService.getById(accountRequestFundsVo.getCorporationId());
        if (ObjectUtil.isEmpty(corporation)){
            throw new ServiceException("没有找到归属公司信息");
        }
        accountRequestFundsVo.setCorporationName(corporation.getName());

        //切换数据源
        DynamicDataSourceContextHolder.push(SourceConstant.BASE);
        //查询部门名称信息
        SysDept sysDept = sysDeptService.getById(accountRequestFundsVo.getDepartmentId());
        if (ObjectUtil.isEmpty(sysDept)){
            throw new ServiceException("没有找到归属部门信息");
        }
        accountRequestFundsVo.setDeptName(sysDept.getDeptName());
        return accountRequestFundsVo;
    }

    @Override
    public void add(AccountRequestFundsDto accountRequestFundsDto) {
        this.save(accountRequestFundsDto);
    }

    @Override
    public void edit(AccountRequestFundsDto accountRequestFundsDto) {
        this.updateById(accountRequestFundsDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
