package com.fjhx.sale.service.serviceContract.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.LambdaQueryWrapper;
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.common.constant.SourceConstant;
import com.fjhx.common.service.corporation.CorporationService;
import com.fjhx.sale.entity.serviceContract.dto.ServiceContractDto;
import com.fjhx.sale.entity.serviceContract.dto.ServiceContractSelectDto;
import com.fjhx.sale.entity.serviceContract.po.ServiceContract;
import com.fjhx.sale.entity.serviceContract.po.ServiceContractPay;
import com.fjhx.sale.entity.serviceContract.po.ServiceContractProduct;
import com.fjhx.sale.entity.serviceContract.vo.ServiceContractVo;
import com.fjhx.sale.mapper.serviceContract.ServiceContractMapper;
import com.fjhx.sale.service.serviceContract.ServiceContractPayService;
import com.fjhx.sale.service.serviceContract.ServiceContractProductService;
import com.fjhx.sale.service.serviceContract.ServiceContractService;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务合同表 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-18
 */
@Service
public class ServiceContractServiceImpl extends ServiceImpl<ServiceContractMapper, ServiceContract> implements ServiceContractService {

    @Autowired
    private ServiceContractProductService serviceContractProductService;

    @Autowired
    private ServiceContractPayService serviceContractPayService;

    @Autowired
    private CorporationService corporationService;
    /**
     * 服务合同表分页
     */
    @Override
    public Page<ServiceContractVo> getPage(ServiceContractSelectDto dto) {
        QueryWrapper<Object> query = Wrappers.query();
        query.orderByDesc("sc.create_time");
        //审批状态
        query.eq(ObjectUtil.isNotEmpty(dto.getStatus()),"sc.status",dto.getStatus());
        //服务状态
        query.eq(ObjectUtil.isNotEmpty(dto.getServiceStatus()),"cc.status",dto.getServiceStatus());
        //归属公司查询
        query.eq(ObjectUtil.isNotEmpty(dto.getSellCorporationId()),"sc.sell_corporation_id",dto.getSellCorporationId());
        //客户查询
        query.eq(ObjectUtil.isNotEmpty(dto.getBuyCorporationId()),"sc.buy_corporation_id",dto.getBuyCorporationId());
        //合同编码查询
        query.eq(ObjectUtil.isNotEmpty(dto.getCode()),"sc.code",dto.getCode());
        //合同金额
        query.ge(ObjectUtil.isNotEmpty(dto.getBeginAmount()),"sc.amount",dto.getEndAmount());
        query.le(ObjectUtil.isNotEmpty(dto.getEndAmount()),"sc.amount",dto.getEndAmount());
        //下单时间
        query.ge(ObjectUtil.isNotEmpty(dto.getBeginTime()),"sc.create_time",dto.getBeginAmount());
        query.ge(ObjectUtil.isNotEmpty(dto.getEndTime()),"sc.create_time",dto.getEndTime());

        //查询服务合同列表
        Page<ServiceContractVo> page = this.baseMapper.getPage(dto.getPage(), query);
        List<ServiceContractVo> records = page.getRecords();
        //赋值用户名称
        UserUtil.assignmentNickName(records, BasePo::getCreateUser, ServiceContractVo::setUserName);
        return page;
    }

    /**
     * 服务合同表明细
     */
    @Override
    public ServiceContractVo detail(Long id) {
        //查询服务合同表的信息
        ServiceContract ServiceContract = this.getById(id);
        ServiceContractVo result = BeanUtil.toBean(ServiceContract, ServiceContractVo.class);

        //查询服务合同-商品表的数据
        List<ServiceContractProduct> contractProductList = serviceContractProductService.list(Wrappers.<ServiceContractProduct>lambdaQuery()
                .eq(ServiceContractProduct::getServiceContractId, result.getId()));

        //查询服务合同-收费项目
        List<ServiceContractPay> contractPayList = serviceContractPayService.list(Wrappers.<ServiceContractPay>lambdaQuery()
                .eq(ServiceContractPay::getServiceContractId, result.getId()));

        result.setServiceContractProductList(contractProductList);
        result.setServiceContractPayList(contractPayList);
        return result;
    }

    @Override
    public void add(ServiceContractDto serviceContractDto) {
        this.save(serviceContractDto);
    }

    @Override
    public void edit(ServiceContractDto serviceContractDto) {
        this.updateById(serviceContractDto);
    }

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

    /**
     * 服务合同统计（根据归属公司统计）
     */
    @Override
    public Map<String, Object> serviceContractStatistics(ServiceContractDto serviceContractDto) {
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<ServiceContract> query = Wrappers.query();
        query.select("count(*) count,ifnull(sum(amount),0) amount,sell_corporation_id sellCorporationId");
        query.groupBy("sell_corporation_id");
        query.eq("status",30);
        List<ServiceContract> serviceContractList = baseMapper.selectList(query);

        //计算合计数量
        Integer countAmount = serviceContractList.stream().map(ServiceContract::getCount).reduce(Integer::sum).orElse(0);
        //计算合计金额
        BigDecimal amount = serviceContractList.stream().map(ServiceContract::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        map.put("countAmount",countAmount);
        map.put("amount",amount);

        //赋值归属公司名称
        DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
        corporationService.attributeAssign(serviceContractList, ServiceContract::getSellCorporationId, (item, corporation) -> {
            item.setSellCorporationName(corporation.getName());
        });
        DynamicDataSourceContextHolder.poll();

        //过滤掉卖方公司为null的数据（因为如果归属公司为null说明服务合同表的是没有数据）
        serviceContractList = serviceContractList.stream().filter(serviceContract -> ObjectUtil
                .isNotEmpty(serviceContract.getSellCorporationId())).collect(Collectors.toList());

        map.put("serviceContractList",serviceContractList);
        return map;
    }

}
