package com.fjhx.sale.service.contract.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.customer.entity.customer.po.Customer;
import com.fjhx.customer.entity.customer.vo.CustomerFollowRecordsVo;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.purchase.entity.invoice.po.Invoice;
import com.fjhx.purchase.entity.invoice.po.InvoiceDetails;
import com.fjhx.purchase.entity.invoice.vo.InvoiceDetailsVo;
import com.fjhx.purchase.entity.invoice.vo.InvoiceVo;
import com.fjhx.sale.entity.contract.po.ContractInvoice;
import com.fjhx.sale.entity.contract.po.ContractInvoiceDetails;
import com.fjhx.sale.entity.contract.vo.ContractInvoiceDetailsVo;
import com.fjhx.sale.entity.serviceContract.vo.ServiceContractRecordVo;
import com.fjhx.sale.mapper.contract.ContractInvoiceMapper;
import com.fjhx.sale.service.contract.ContractInvoiceDetailsService;
import com.fjhx.sale.service.contract.ContractInvoiceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.LogicIgnore;
import com.ruoyi.common.annotation.TenantIgnore;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.SqlField;
import com.ruoyi.system.utils.UserUtil;
import lombok.experimental.Delegate;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjhx.sale.entity.contract.vo.ContractInvoiceVo;
import com.fjhx.sale.entity.contract.dto.ContractInvoiceSelectDto;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.fjhx.sale.entity.contract.dto.ContractInvoiceDto;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * <p>
 * 合同发票管理 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-09-08
 */
@Service
public class ContractInvoiceServiceImpl extends ServiceImpl<ContractInvoiceMapper, ContractInvoice> implements ContractInvoiceService {

    @Autowired
    private ContractInvoiceDetailsService contractInvoiceDetailsService;

    @Autowired
    private CustomerService customerService;
    /**
     * 分页
     * @param dto
     * @return
     */
    @Override
    public Page<ContractInvoiceVo> getPage(ContractInvoiceSelectDto dto) {
        IWrapper<ContractInvoice> wrapper = getWrapper();
        wrapper.orderByDesc("t1", Invoice::getCreateTime);
        if(ObjectUtils.isNotEmpty(dto.getInvoiceType())){
            wrapper.eq("t1", Invoice::getType,dto.getInvoiceType());
        }
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(), new SqlField("t1.contractCodes"));
        }
        Page<ContractInvoiceVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<ContractInvoiceVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            //赋值客户名称
            customerService.attributeAssign(list, ContractInvoiceVo::getCustomerId, (item, customer) -> {
                item.setCustomerName(customer.getName());
            });
            UserUtil.assignmentNickName(list, BasePo::getCreateUser, ContractInvoiceVo::setUserName);
        }
        return page;
    }

    /**
     * 明细
     * @param id
     * @return
     */
    @Override
    public ContractInvoiceVo detail(Long id) {
        ContractInvoice ContractInvoice = this.getById(id);
        ContractInvoiceVo result = BeanUtil.toBean(ContractInvoice, ContractInvoiceVo.class);
        if(ObjectUtils.isEmpty(result)){
            throw new ServiceException("发票不存在");
        }
        Customer customer = customerService.getById(result.getCustomerId());
        result.setCustomerName(ObjectUtils.isEmpty(customer)?"":customer.getName());
        List<ContractInvoiceDetailsVo> invoiceDetailsVos = contractInvoiceDetailsService.getDetail(id);
        List<Long> ids = invoiceDetailsVos.stream().distinct().map(ContractInvoiceDetailsVo::getContractId).collect(Collectors.toList());
        List<ContractInvoiceDetailsVo> invoiceDetailsList = contractInvoiceDetailsService.getSumMoneyByContractIds(ids);
        Map<Long, BigDecimal> invoiceMap = invoiceDetailsList.stream().collect(Collectors.toMap(ContractInvoiceDetailsVo::getContractId,ContractInvoiceDetailsVo::getSumMoney));
        for(ContractInvoiceDetailsVo p:invoiceDetailsVos){
            if(MapUtils.isNotEmpty(invoiceMap)){
                p.setSumMoney(invoiceMap.getOrDefault(p.getContractId(), BigDecimal.ZERO));
            }else{
                p.setSumMoney(BigDecimal.ZERO);
            }
        }
        result.setContractInvoiceDetailsVoList(invoiceDetailsVos);
        return result;
    }

    /**
     * 添加
     * @param contractInvoiceDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ContractInvoiceDto contractInvoiceDto) {
        this.save(contractInvoiceDto);
        List<ContractInvoiceDetails> invoiceDetailsList = contractInvoiceDto.getInvoiceDetailsList();
        if(CollectionUtils.isNotEmpty(invoiceDetailsList)){
            invoiceDetailsList = invoiceDetailsList.stream()
                    .peek(item -> item.setInvoiceId(contractInvoiceDto.getId()))
                    .filter(item -> item.getMoney() != null && item.getMoney().compareTo(BigDecimal.ZERO) > 0)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(invoiceDetailsList)) {
                contractInvoiceDetailsService.saveBatch(invoiceDetailsList);
            }
        }
    }

    /**
     * 修改
     * @param contractInvoiceDto
     */
    @Override
    @LogicIgnore
    @Transactional(rollbackFor = Exception.class)
    public void edit(ContractInvoiceDto contractInvoiceDto) {
        this.updateById(contractInvoiceDto);
        contractInvoiceDetailsService.remove(Wrappers.<ContractInvoiceDetails>query().lambda().eq(ContractInvoiceDetails::getInvoiceId,contractInvoiceDto.getId()));
        List<ContractInvoiceDetails> invoiceDetailsList = contractInvoiceDto.getInvoiceDetailsList();
        if(CollectionUtils.isNotEmpty(invoiceDetailsList)){
            for(ContractInvoiceDetails d:invoiceDetailsList){
                d.setInvoiceId(contractInvoiceDto.getId());
            }
            contractInvoiceDetailsService.saveBatch(invoiceDetailsList);
        }
    }

    /**
     * 删除
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        this.removeById(id);
        contractInvoiceDetailsService.remove(Wrappers.<ContractInvoiceDetails>query().lambda().eq(ContractInvoiceDetails::getInvoiceId,id));
    }

}
