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.QpTransportUser;
import com.zd.airbottle.domain.QpTransportUserCredentials;
import com.zd.airbottle.domain.dto.QpTransportUserCredentialsDto;
import com.zd.airbottle.domain.dto.QpTransportUserDto;
import com.zd.airbottle.domain.vo.QpTransportUserCredentialsVo;
import com.zd.airbottle.domain.vo.QpTransportUserVo;
import com.zd.airbottle.mapper.QpTransportUserMapper;
import com.zd.airbottle.service.IQpSupplierService;
import com.zd.airbottle.service.IQpSupplierSyntheticalAuditService;
import com.zd.airbottle.service.IQpTransportUserCredentialsService;
import com.zd.airbottle.service.IQpTransportUserService;
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 QpTransportUserServiceImpl implements IQpTransportUserService {
    @Autowired
    private QpTransportUserMapper qpTransportUserMapper;
    @Autowired
    private IQpSupplierService supplierService;
    @Autowired
    private IQpTransportUserCredentialsService userCredentialsService;
    @Autowired
    private IQpSupplierSyntheticalAuditService auditService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询运输人员
     *
     * @param id 运输人员主键
     * @return 运输人员
     */
    @Override
    public QpTransportUserVo selectQpTransportUserById(Long id) {
        QpTransportUser transportUser = qpTransportUserMapper.selectQpTransportUserById(id);
        QpTransportUserVo transportUserVo = new QpTransportUserVo();
        BeanUtils.copyProperties(transportUser, transportUserVo);

        setUserCredentials(transportUserVo);
        QpSupplier qpSupplier = supplierService.selectQpSupplierById(transportUser.getSupplierId());
        if (qpSupplier!=null){
            transportUserVo.setCompanyName(qpSupplier.getCompanyName());
        }
        if (transportUser.getIsAudit() == Constants.SUPPLIER_NO_AUDIT) {
            QpSupplierSyntheticalAudit syntheticalAudit = auditService.getQpSupplierSyntheticalAuditBySyntheticalId(transportUser.getId(), AuditType.SUPPLIER_USER_AUDIT);
            transportUserVo.setSyntheticalAudit(syntheticalAudit);
        }
        return transportUserVo;
    }

    @Override
    public void setUserCredentials( QpTransportUserVo transportUserVo) {
        QpTransportUserCredentials userCredentials = new QpTransportUserCredentials().setTransportUserId(transportUserVo.getId());
        List<QpTransportUserCredentials> transportUserCredentials = userCredentialsService.selectQpTransportUserCredentialsList(userCredentials);
        List<QpTransportUserCredentialsVo> userCredentialsVos = new ArrayList<>();
        transportUserCredentials.forEach(qsc -> {
            QpTransportUserCredentialsVo userCredentialsVo = new QpTransportUserCredentialsVo();
            BeanUtils.copyProperties(qsc, userCredentialsVo);
            userCredentialsVos.add(userCredentialsVo);
        });
        transportUserVo.setUserCredentialsVos(userCredentialsVos);
    }

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

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

    /**
     * 根据供应商查询注册用户
     * @param qpTransportUserVo 查询参数
     * @return  运输人员集合
     */
    @Override
    public List<QpTransportUser> selectUserList(QpTransportUserVo qpTransportUserVo) {
        return qpTransportUserMapper.selectUserList(qpTransportUserVo);
    }

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

    @Override
    public List<QpTransportUserVo> getSupplierUserList(QpTransportUser qpTransportUser) {
        QpSupplier supplier = SupplierUtil.getSupplier(tokenService, supplierService);
        qpTransportUser.setSupplierId(supplier.getId());
        return getTransportUserList(qpTransportUser);
    }

    /**
     * 查询运输人员列表
     *
     * @param qpTransportUser 运输人员
     * @return 运输人员
     */
    @Override
    public List<QpTransportUser> selectQpTransportUserList(QpTransportUser qpTransportUser) {
        Long supplierId = qpTransportUser.getSupplierId();
        if (supplierId==null){
            QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
            if (qpSupplier == null) throw new ServiceException("供应商查询失败");
            qpTransportUser.setSupplierId(qpSupplier.getId());
        }
        return qpTransportUserMapper.selectQpTransportUserList(qpTransportUser);
    }

    @Override
    public List<QpTransportUserVo> getTransportUserList(QpTransportUser transportUser) {
        Long supplierId = transportUser.getSupplierId();
        if (supplierId==null){
            QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
            if (qpSupplier == null) throw new ServiceException("供应商查询失败");
            transportUser.setSupplierId(qpSupplier.getId());
        }
        List<QpTransportUser> transportUsers = qpTransportUserMapper.selectQpTransportUserList(transportUser);
        List<Long> userIds = transportUsers.stream().map(QpTransportUser::getId).collect(Collectors.toList());
        List<QpTransportUserCredentials> userCredentials=userCredentialsService.getUserCredentialsByUserIds(userIds);
        Map<Long, List<QpTransportUserCredentials>> credentialsMap = userCredentials.stream().collect(Collectors.groupingBy(QpTransportUserCredentials::getTransportUserId));
        List<QpTransportUserVo> userVos=new ArrayList<>();
        transportUsers.forEach(u->{
            QpTransportUserVo userVo=new QpTransportUserVo();
            BeanUtils.copyProperties(u,userVo);
            Long id = u.getId();
            if (credentialsMap.containsKey(id)){
                List<QpTransportUserCredentials> credentials = credentialsMap.get(id);
                credentials.forEach(c->{
                    Date endTime = c.getEndTime();
                    if (endTime!=null && endTime.getTime()<Calendar.getInstance().getTimeInMillis()){
                        userVo.setPastDue(1);
                    }
                });
            }
            userVos.add(userVo);
        });
        return userVos;
    }

    /**
     * 新增运输人员
     *
     * @param transportUserDto 运输人员数据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQpTransportUser(QpTransportUserDto transportUserDto) {
        QpSupplier qpSupplier = supplierService.selectQpSupplierByAccountId(tokenService.getLoginUser().getSysUser().getUserId());
        if (qpSupplier == null) throw new ServiceException("未找到供应商信息");
        QpTransportUser transportUser = new QpTransportUser()
                .setIsAudit(Constants.SUPPLIER_NOT_AUDIT)
                .setSupplierId(qpSupplier.getId());
        BeanUtils.copyProperties(transportUserDto, transportUser);
        //设置其他公共字段
        SaveUtil.setCommonAttr(transportUser);
        if (qpTransportUserMapper.insertQpTransportUser(transportUser) > 0) {
            Long id = transportUser.getId();
            //新增待审核数据
            auditService.addSyntheticalAudit(id, AuditType.SUPPLIER_USER_AUDIT, qpSupplier.getCompanyName());
            //保存车辆证件
            List<QpTransportUserCredentialsDto> userCredentialsDtos = transportUserDto.getUserCredentialsDtos();
            if (CollUtil.isNotEmpty(userCredentialsDtos)) {
                userCredentialsDtos.forEach(userCredentialsDto -> {
                    QpTransportUserCredentials userCredentials = new QpTransportUserCredentials()
                            .setTransportUserId(id);
                    BeanUtils.copyProperties(userCredentialsDto, userCredentials);
                    if (userCredentialsService.insertQpTransportUserCredentials(userCredentials)<=0)
                        throw new ServiceException("人员证件添加失败");
                });
            }
            return 1;
        }
        throw new ServiceException("新增车辆错误");
    }

    /**
     * 修改运输人员
     *
     * @param qpTransportUser 运输人员
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateQpTransportUser(QpTransportUser qpTransportUser) {
        qpTransportUser.setUpdateTime(DateUtils.getNowDate());
        qpTransportUser.setUpdateBy(SecurityUtils.getUsername());
        return qpTransportUserMapper.updateQpTransportUser(qpTransportUser);
    }

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

    /**
     * 删除运输人员信息
     *
     * @param id 运输人员主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQpTransportUserById(Long id) {
        return qpTransportUserMapper.deleteQpTransportUserById(id);
    }

    /**
     * 批量查询人员
     *
     * @param userIds ID集合
     * @return 结果集
     */
    @Override
    public List<QpTransportUser> selectQpTransportUserListByIds(Long[] userIds) {
        if (userIds.length==0){
            return Collections.emptyList();
        }
        return qpTransportUserMapper.selectQpTransportUserListByIds(userIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int edit(QpTransportUserDto transportUserDto) {
        QpTransportUser transportUser = new QpTransportUser();
        BeanUtils.copyProperties(transportUserDto, transportUser);
        transportUser.setUpdateTime(DateUtils.getNowDate());
        transportUser.setUpdateBy(SecurityUtils.getUsername());
        transportUser.setIsAudit(Constants.SUPPLIER_NOT_AUDIT);

        auditService.addSyntheticalAudit(transportUser.getId(), AuditType.SUPPLIER_USER_AUDIT, SecurityUtils.getUsername());
        List<QpTransportUserCredentialsDto> userCredentialsDtos = transportUserDto.getUserCredentialsDtos();
        List<QpTransportUserCredentials> credentials = userCredentialsService.selectQpTransportUserCredentialsList(new QpTransportUserCredentials().setTransportUserId(transportUser.getId()));
        List<Long> cIds = Collections.synchronizedList(credentials.stream().map(QpTransportUserCredentials::getId).collect(Collectors.toList()));
        if (CollUtil.isNotEmpty(userCredentialsDtos)) {
            userCredentialsDtos.forEach(qsc -> {
                QpTransportUserCredentials userCredentials = new QpTransportUserCredentials();
                BeanUtils.copyProperties(qsc, userCredentials);
                if (userCredentials.getId() == null) {
                    userCredentials.setTransportUserId(transportUser.getId());
                    if (userCredentialsService.insertQpTransportUserCredentials(userCredentials)<=0)
                        throw new ServiceException("人员证件添加失败");
                } else {
                    cIds.remove(qsc.getId());
                    if (userCredentialsService.updateQpTransportUserCredentials(userCredentials)<=0)
                        throw new ServiceException("人员证件修改失败");
                }
            });
        }
        if (CollUtil.isNotEmpty(cIds)){
            userCredentialsService.deleteQpTransportUserCredentialsByIds(cIds.toArray(cIds.toArray(new Long[0])));
        }
        return qpTransportUserMapper.updateQpTransportUser(transportUser);
    }
}
