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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.enums.FlowStatusEnum1;
import com.fjhx.customer.entity.customer.po.Customer;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.file.entity.FileInfoVo;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.contract.vo.ContractProductVo;
import com.fjhx.sale.entity.sample.dto.SampleDto;
import com.fjhx.sale.entity.sample.dto.SampleSelectDto;
import com.fjhx.sale.entity.sample.po.Sample;
import com.fjhx.sale.entity.sample.vo.SampleVo;
import com.fjhx.sale.mapper.sample.SampleMapper;
import com.fjhx.sale.service.sample.SampleService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import org.apache.commons.collections4.MapUtils;
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-05-05
 */
@Service
public class SampleServiceImpl extends ServiceImpl<SampleMapper, Sample> implements SampleService {


    @Autowired
    private CustomerService customerService;

    @Autowired
    private ProductInfoService productInfoService;


    /**
     * 分页
     *
     * @param dto
     * @return
     */
    @Override
    public Page<SampleVo> getPage(SampleSelectDto dto) {
        IWrapper<Sample> wrapper = getWrapper();
        wrapper.orderByDesc("s", Sample::getCreateTime);
        wrapper.between("s", Sample::getStatus, FlowStatusEnum1.DRAFT.getKey(), FlowStatusEnum1.CANCELLATION.getKey() - 1);
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            wrapper.eq("s", Sample::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getUserId())) {
            wrapper.eq("s", Sample::getCreateUser, dto.getUserId());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            wrapper.keyword(dto.getKeyword(), new SqlField("s", Sample::getCode));
        }
        Page<SampleVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<SampleVo> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> customerIds = list.stream().map(Sample::getBuyCorporationId).collect(Collectors.toList());
            List<Customer> customerList = customerService.list(Wrappers.<Customer>query().lambda().in(Customer::getId, customerIds));
            Map<Long, List<Customer>> cusMap = customerList.stream().distinct().collect(Collectors.groupingBy(Customer::getId));

            List<Long> ids = list.stream().map(sampleVo -> sampleVo.getId()).collect(Collectors.toList());
            //获取交接单附件
            Map<Long, List<FileInfoVo>> fileMap = ObsFileUtil.getFileMap(ids, 1);

            //获取包装附件
            Map<Long, List<FileInfoVo>> packageFileMap = ObsFileUtil.getFileMap(ids, 2);

            for (SampleVo p : list) {
                if (MapUtils.isNotEmpty(cusMap)) {//客户
                    List<Customer> customers = cusMap.getOrDefault(p.getBuyCorporationId(), null);
                    p.setBuyCorporationName(customers == null ? null : customers.get(0).getName());
                    //赋值客户标签
                    p.setTag(customers == null ? null : customers.get(0).getTag());
                }

                //赋值交接单附件
                if (MapUtils.isNotEmpty(fileMap)){
                    List<FileInfoVo> fileInfoVos = fileMap.get(p.getId());
                    p.setFileInfoVos(fileInfoVos);
                }

                //赋值包装附件信息
                if (MapUtils.isNotEmpty(packageFileMap)){
                    List<FileInfoVo>  packageFileInfoVOList= packageFileMap.get(p.getId());
                    p.setPackageFileInfoVOList(packageFileInfoVOList);
                }

            }


        }


        return page;
    }

    @Override
    public SampleVo detail(Long id) {
        Sample Sample = this.getById(id);
        SampleVo result = BeanUtil.toBean(Sample, SampleVo.class);
        return result;
    }

    @Override
    public void add(SampleDto sampleDto) {
        this.save(sampleDto);
    }

    @Override
    public void edit(SampleDto sampleDto) {
        this.updateById(sampleDto);
    }

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

    /**
     * 样品交接单(类型1 为交接单，2为包装指示)
     */
    @Override
    public void sampleHandover(SampleDto dto) {
        ObsFileUtil.editFile(dto.getFileList(),dto.getId(),1);
        ObsFileUtil.editFile(dto.getPackageFileList(),dto.getId(),2);
    }

    /**
     * 样品交接单列表
     */
    @Override
    public Page<ContractProductVo> sampleHandoverList(SampleSelectDto dto) {
        IWrapper<Sample> wrapper = getWrapper();
        wrapper.orderByDesc("t1.create_time");
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t1.`contractCode`"),new SqlField("t1.`userName`"));
        }
        wrapper.ge("t2.`status`",30);
        wrapper.lt("t2.`status`",88);
        wrapper.gt("t1.expend_quantity",0);
        //查询样品交接单列表（只查询有交接单的数据）
        Page<ContractProductVo> page = this.baseMapper.sampleHandoverList(dto.getPage(), wrapper);

        List<ContractProductVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });
            // 赋值客户名称
            customerService.attributeAssign(list, ContractProductVo::getBuyCorporationId, (item, corporation) -> {
                item.setBuyCorporationName(corporation.getName());
            });
        }
        return page;
    }

}
