package com.zd.airbottle.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.zd.airbottle.constant.AuditType;
import com.zd.airbottle.constant.Constants;
import com.zd.airbottle.domain.QpSupplier;
import com.zd.airbottle.domain.QpSupplierSyntheticalAudit;
import com.zd.airbottle.domain.QpTransportCar;
import com.zd.airbottle.domain.QpTransportCarCredentials;
import com.zd.airbottle.domain.dto.QpTransportCarCredentialsDto;
import com.zd.airbottle.domain.dto.QpTransportCarDto;
import com.zd.airbottle.domain.vo.QpTransportCarCredentialsVo;
import com.zd.airbottle.domain.vo.QpTransportCarVo;
import com.zd.airbottle.mapper.QpTransportCarMapper;
import com.zd.airbottle.service.IQpSupplierService;
import com.zd.airbottle.service.IQpSupplierSyntheticalAuditService;
import com.zd.airbottle.service.IQpTransportCarCredentialsService;
import com.zd.airbottle.service.IQpTransportCarService;
import com.zd.airbottle.utils.SupplierUtil;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.bean.TransferUtils;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.SaveUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 运输车辆Service业务层处理
 */
@Service
public class QpTransportCarServiceImpl implements IQpTransportCarService {
    @Autowired
    private QpTransportCarMapper qpTransportCarMapper;
    @Autowired
    private IQpTransportCarCredentialsService carCredentialsService;
    @Autowired
    private IQpSupplierService supplierService;
    @Autowired
    private IQpSupplierSyntheticalAuditService auditService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询运输车辆
     *
     * @param id 运输车辆主键
     * @return 运输车辆
     */
    @Override
    public QpTransportCarVo selectQpTransportCarById(Long id) {
        QpTransportCar qpTransportCar = qpTransportCarMapper.selectQpTransportCarById(id);
        QpTransportCarVo transportCarVo = new QpTransportCarVo();
        BeanUtils.copyProperties(qpTransportCar, transportCarVo);

        setTransportCarCredentialsVos(transportCarVo);
        QpSupplier qpSupplier = supplierService.selectQpSupplierById(qpTransportCar.getSupplierId());
        if (qpSupplier!=null){
            transportCarVo.setCompanyName(qpSupplier.getCompanyName());
        }
        if (qpTransportCar.getIsAudit() == Constants.SUPPLIER_NO_AUDIT) {
            QpSupplierSyntheticalAudit syntheticalAudit = auditService.getQpSupplierSyntheticalAuditBySyntheticalId(qpTransportCar.getId(), AuditType.SUPPLIER_CAR_AUDIT);
            transportCarVo.setSyntheticalAudit(syntheticalAudit);
        }
        return transportCarVo;
    }

    @Override
    public void setTransportCarCredentialsVos(QpTransportCarVo transportCarVo) {
        QpTransportCarCredentials carCredentials = new QpTransportCarCredentials().setTransportCarId(transportCarVo.getId());
        List<QpTransportCarCredentials> transportCarCredentials = carCredentialsService.selectQpTransportCarCredentialsList(carCredentials);
        List<QpTransportCarCredentialsVo> carCredentialsVos = new ArrayList<>();
        transportCarCredentials.forEach(qsc -> {
            QpTransportCarCredentialsVo carCredentialsVo = new QpTransportCarCredentialsVo();
            BeanUtils.copyProperties(qsc, carCredentialsVo);
            carCredentialsVos.add(carCredentialsVo);
        });
        transportCarVo.setCarCredentialsVos(carCredentialsVos);
    }

    /**
     * 根据供应商ID集合获取运输人员数量
     * @param supplierIds 供应商ID集合
     * @return map结果集
     */
    @Override
    public Map<Long, Integer> getBySupplierIds(List<Long> supplierIds) {
        List<QpTransportCarVo> carVos = qpTransportCarMapper.getBySupplierIds(supplierIds);
        return carVos.stream().collect(Collectors.toMap(QpTransportCarVo::getSupplierId, QpTransportCarVo::getSum));
    }

    @Override
    public List<QpTransportCar> checkList(QpTransportCar transportCar) {
        QpSupplier supplier=new QpSupplier();
        supplier.setCompanyName(transportCar.getSearchValue());
        List<QpSupplier> suppliers = supplierService.getList(supplier);
        List<Long> supplierIds = suppliers.stream().map(QpSupplier::getId).collect(Collectors.toList());
        transportCar.setSupplierIds(supplierIds);
        return qpTransportCarMapper.selectQpTransportCarList(transportCar);
    }

    /***
     * 查询供应商下的注册车辆
     * @param qpTransportCarVo 查询参数
     * @return 运输车辆集合
     */
    @Override
    public List<QpTransportCar> selectCarList(QpTransportCarVo qpTransportCarVo) {
        return qpTransportCarMapper.selectCarList(qpTransportCarVo);
    }

    @Override
    public List<QpTransportCarVo> getListVo(List<QpTransportCar> list) {
        List<QpSupplier> suppliers = supplierService.selectQpSupplierListByIds(list.stream().map(QpTransportCar::getSupplierId).toArray(Long[]::new));
        Map<Long, String> supplierNameMap = suppliers.stream().collect(Collectors.toMap(QpSupplier::getId, QpSupplier::getCompanyName));
        List<QpTransportCarVo> carVos = TransferUtils.transferList(list, QpTransportCarVo.class);
        carVos.forEach(c->{
            Long supplierId = c.getSupplierId();
            setTransportCarCredentialsVos(c);
            if (supplierNameMap.containsKey(supplierId)){
                c.setCompanyName(supplierNameMap.get(supplierId));
            }
        });
        return carVos;
    }

    @Override
    public List<QpTransportCarVo> getSupplierCarList(QpTransportCar qpTransportCar) {
        QpSupplier supplier = SupplierUtil.getSupplier(tokenService, supplierService);
        qpTransportCar.setSupplierId(supplier.getId());
        return getCarList(qpTransportCar);
    }

    /**
     * 查询运输车辆列表
     *
     * @param qpTransportCar 运输车辆
     * @return 运输车辆
     */
    @Override
    public List<QpTransportCar> selectQpTransportCarList(QpTransportCar qpTransportCar) {
        Long supplierId = qpTransportCar.getSupplierId();
        if (supplierId == null) {
            QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
            if (qpSupplier == null) throw new ServiceException("供应商查询失败");
            qpTransportCar.setSupplierId(qpSupplier.getId());
        }
        return qpTransportCarMapper.selectQpTransportCarList(qpTransportCar);
    }

    @Override
    public List<QpTransportCarVo> getCarList(QpTransportCar transportCar) {
        Long supplierId = transportCar.getSupplierId();
        if (supplierId == null) {
            QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
            if (qpSupplier == null) throw new ServiceException("供应商查询失败");
            transportCar.setSupplierId(qpSupplier.getId());
        }
        List<QpTransportCar> transportCars = qpTransportCarMapper.selectQpTransportCarList(transportCar);
        List<QpTransportCarCredentials> carCredentials=carCredentialsService.getByCarIds(transportCars.stream().map(QpTransportCar::getId).collect(Collectors.toList()));
        Map<Long, List<QpTransportCarCredentials>> credentialsMap = carCredentials.stream().collect(Collectors.groupingBy(QpTransportCarCredentials::getTransportCarId));
        List<QpTransportCarVo> carVos=new ArrayList<>();
        transportCars.forEach(u->{
            QpTransportCarVo carVo=new QpTransportCarVo();
            BeanUtils.copyProperties(u,carVo);
            Long id = u.getId();
            if (credentialsMap.containsKey(id)){
                List<QpTransportCarCredentials> credentials = credentialsMap.get(id);
                credentials.forEach(c->{
                    Date endTime = c.getEndTime();
                    if (endTime!=null && endTime.getTime()<Calendar.getInstance().getTimeInMillis()){
                        carVo.setPastDue(1);
                    }
                });
            }
            carVos.add(carVo);
        });
        return carVos;
    }

    @Override
    public List<QpTransportCar> selectQpTransportCarList(Long[] ids) {
        if (ids.length==0){
            return Collections.emptyList();
        }
        return qpTransportCarMapper.selectQpTransportCarListByIds(ids);
    }

    /**
     * 新增运输车辆
     *
     * @param transportCarDto 运输车辆
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQpTransportCar(QpTransportCarDto transportCarDto) {
        QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
        if (qpSupplier == null) throw new ServiceException("未找到供应商信息");
        QpTransportCar qpTransportCar = new QpTransportCar()
                .setIsAudit(Constants.SUPPLIER_NOT_AUDIT)
                .setSupplierId(qpSupplier.getId());
        BeanUtils.copyProperties(transportCarDto, qpTransportCar);
        //设置其他公共字段
        SaveUtil.setCommonAttr(qpTransportCar);
        if (qpTransportCarMapper.insertQpTransportCar(qpTransportCar) > 0) {
            Long id = qpTransportCar.getId();
            //新增待审核数据
            auditService.addSyntheticalAudit(id, AuditType.SUPPLIER_CAR_AUDIT, qpSupplier.getCompanyName());
            //保存车辆证件
            List<QpTransportCarCredentialsDto> carCredentialsDtos = transportCarDto.getCarCredentialsDtos();
            if (CollUtil.isNotEmpty(carCredentialsDtos)) {
                carCredentialsDtos.forEach(carCredentialsDto -> {
                    QpTransportCarCredentials carCredentials = new QpTransportCarCredentials()
                            .setTransportCarId(id);
                    BeanUtils.copyProperties(carCredentialsDto, carCredentials);
                    if (carCredentialsService.insertQpTransportCarCredentials(carCredentials) <= 0)
                        throw new ServiceException("新增车辆证件失败");
                });
            }
            return 1;
        }
        throw new ServiceException("新增车辆错误");
    }

    /**
     * 修改运输车辆
     *
     * @param qpTransportCar 运输车辆
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateQpTransportCar(QpTransportCar qpTransportCar) {
        qpTransportCar.setUpdateTime(DateUtils.getNowDate());
        qpTransportCar.setUpdateBy(SecurityUtils.getUsername());
        return qpTransportCarMapper.updateQpTransportCar(qpTransportCar);
    }

    /**
     * 批量删除运输车辆
     *
     * @param ids 需要删除的运输车辆主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQpTransportCarByIds(Long[] ids) {
        return qpTransportCarMapper.deleteQpTransportCarByIds(ids);
    }

    /**
     * 删除运输车辆信息
     *
     * @param id 运输车辆主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQpTransportCarById(Long id) {
        return qpTransportCarMapper.deleteQpTransportCarById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editQpTransportCar(QpTransportCarDto transportCarDto) {
        QpTransportCar transportCar = new QpTransportCar();
        BeanUtils.copyProperties(transportCarDto, transportCar);
        transportCar.setUpdateTime(DateUtils.getNowDate());
        transportCar.setUpdateBy(SecurityUtils.getUsername());
        transportCar.setIsAudit(Constants.SUPPLIER_NOT_AUDIT);

        auditService.addSyntheticalAudit(transportCar.getId(), AuditType.SUPPLIER_CAR_AUDIT, SecurityUtils.getUsername());
        List<QpTransportCarCredentialsDto> carCredentialsDtos = transportCarDto.getCarCredentialsDtos();
        List<QpTransportCarCredentials> credentials = carCredentialsService.selectQpTransportCarCredentialsList(new QpTransportCarCredentials().setTransportCarId(transportCar.getId()));
        List<Long> cIds = Collections.synchronizedList(credentials.stream().map(QpTransportCarCredentials::getId).collect(Collectors.toList()));

        if (CollUtil.isNotEmpty(carCredentialsDtos)) {
            carCredentialsDtos.forEach(carCredentialsDto -> {
                QpTransportCarCredentials carCredentials = new QpTransportCarCredentials();
                BeanUtils.copyProperties(carCredentialsDto, carCredentials);
                if (carCredentials.getId() == null) {
                    carCredentials.setTransportCarId(transportCar.getId());
                    if (carCredentialsService.insertQpTransportCarCredentials(carCredentials) <= 0)
                        throw new ServiceException("车辆证件添加失败");
                } else {
                    cIds.remove(carCredentials.getId());
                    carCredentialsService.updateQpTransportCarCredentials(carCredentials);
                }
            });
        }
        if (CollUtil.isNotEmpty(cIds)){
            carCredentialsService.deleteQpTransportCarCredentialsByIds(cIds.toArray(cIds.toArray(new Long[0])));
        }
        return qpTransportCarMapper.updateQpTransportCar(transportCar);
    }
}
