package cn.superdesk.uniorder.service.thirdpart.qchjc.invoice.impl;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcStorageStatusEnum;
import cn.superdesk.uniorder.common.exception.OpenApiException;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.accounting.*;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplySupplierEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplySupplierEntityExample;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcAccountingUnifiedSupplierEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcOrderGoodsEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcUserEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.invoice.QchjcInvoiceApplySupplierEntityMapper;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcOrderGoodsParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.accounting.QchjcOrderParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.invoice.QchjcInvoiceApplySupplierParam;
import cn.superdesk.uniorder.service.sys.SysUserService;
import cn.superdesk.uniorder.service.thirdpart.qchjc.invoice.QchjcSupplierInvoiceService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author xc
 * @description
 * @date 2022/4/1 20:20
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QchjcSupplierInvoiceServiceImpl implements QchjcSupplierInvoiceService {

    private final QchjcInvoiceApplySupplierEntityMapper      qchInvoiceApplySupplierEntityMapper;
    private final QchjcUserEntityMapper                      qchjcUserEntityMapper;
    private final SysUserService                             sysUserService;
    private final QchjcAccountingUnifiedSupplierEntityMapper qchjcAccountingUnifiedSupplierEntityMapper;

    private final QchjcOrderGoodsEntityMapper qchjcOrderGoodsEntityMapper;


    @Override
    public void receive(String data) throws OpenApiException {
        QchjcInvoiceApplySupplierParam param         = AnJsonUtils.toObject(data, QchjcInvoiceApplySupplierParam.class);
        List<QchjcOrderParam>          orderSelected = param.getOrderSelected();
        if (CollectionUtils.isEmpty(orderSelected)) {
            throw new OpenApiException(500, "供应商发票单明细不能为空");
        }
        //参数校验
        QchjcAccountingUnifiedSupplierEntityExample example = new QchjcAccountingUnifiedSupplierEntityExample();
        example.createCriteria()
                .andAccountingOrderSnEqualTo(param.getAccountingOrderSn());
        List<QchjcAccountingUnifiedSupplierEntity> entities = qchjcAccountingUnifiedSupplierEntityMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(entities)) {
            throw new OpenApiException(500, "该发票单所属的对账单主体数据查询不到，请重新推送对账单");
        }
        //发票单对应的对账单主体
        QchjcAccountingUnifiedSupplierEntity qchjcAccountingUnifiedSupplierEntity = entities.get(0);
        if (!Objects.equals(qchjcAccountingUnifiedSupplierEntity.getStorageStatus(), QchjcStorageStatusEnum.FAIL.getStatus())
                && !Objects.equals(qchjcAccountingUnifiedSupplierEntity.getStorageStatus(), QchjcStorageStatusEnum.TODO.getStatus())) {
            //如果对账单主体的状态不是待入库或者入库失败，则不允许推送发票单
            throw new OpenApiException(500, "所属对账单处于入库中或入库成功,不允许推送发票单");
        }
        //保存用户信息
        handleUser(param);
        //保存发票单主体数据
        QchjcInvoiceApplySupplierEntityExample qchjcInvoiceApplySupplierEntityExample = new QchjcInvoiceApplySupplierEntityExample();
        qchjcInvoiceApplySupplierEntityExample.createCriteria()
                .andAccountingOrderSnEqualTo(param.getAccountingOrderSn())
                .andInvoiceSnEqualTo(param.getInvoiceSn());
        List<QchjcInvoiceApplySupplierEntity> qchjcInvoiceApplySupplierEntities = qchInvoiceApplySupplierEntityMapper.selectByExample(qchjcInvoiceApplySupplierEntityExample);
        //已存在则更新，否则新增
        if (CollectionUtils.isNotEmpty(qchjcInvoiceApplySupplierEntities)) {
            QchjcInvoiceApplySupplierEntity copy = AnBeanUtils.copy(param, qchjcInvoiceApplySupplierEntities.get(0));
            int                             sum  = orderSelected.stream().map(x -> x.getOrderGoodsSelected().size()).reduce(0, Integer::sum);
            copy.setJcOrderCount(sum);
            copy.setSaleId(qchjcAccountingUnifiedSupplierEntity.getSaleId());
            copy.setSaleName(qchjcAccountingUnifiedSupplierEntity.getSaleName());
            qchInvoiceApplySupplierEntityMapper.updateByPrimaryKeySelective(copy);

            //清除商品绑定的供应商发票单
            qchjcOrderGoodsEntityMapper.clearSupplierInvoiceOrderGoodsBind(copy.getId());
            //商品绑定发票申请id
            for (QchjcOrderParam qchjcOrderParam : orderSelected) {
                List<QchjcOrderGoodsParam> orderGoodsSelected = qchjcOrderParam.getOrderGoodsSelected();
                for (QchjcOrderGoodsParam qchjcOrderGoodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntityExample goodsEntityExample = new QchjcOrderGoodsEntityExample();

                    goodsEntityExample.createCriteria().
                            andOrderSnEqualTo(qchjcOrderGoodsParam.getOrderSn())
                            .andOutSnapshotOrderGoodsIdEqualTo(qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(goodsEntityExample);
                    if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                        throw new OpenApiException(500, "发票单明细商品不存在,outSnapshotOrderGoodsId:" + qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    }
                    //集采商品绑定供应商发票申请id
                    QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                    qchjcOrderGoodsEntity.setQchSupplierInvoiceApplyId(copy.getId());
                    qchjcOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                }
            }
        } else {
            QchjcInvoiceApplySupplierEntity copy = AnBeanUtils.copy(param, QchjcInvoiceApplySupplierEntity.class);
            int                             sum  = orderSelected.stream().map(x -> x.getOrderGoodsSelected().size()).reduce(0, Integer::sum);
            copy.setJcOrderCount(sum);
            copy.setSaleId(qchjcAccountingUnifiedSupplierEntity.getSaleId());
            copy.setSaleName(qchjcAccountingUnifiedSupplierEntity.getSaleName());
            qchInvoiceApplySupplierEntityMapper.insertSelective(copy);

            //清除商品绑定的供应商发票单
            qchjcOrderGoodsEntityMapper.clearSupplierInvoiceOrderGoodsBind(copy.getId());
            //商品绑定发票申请id
            for (QchjcOrderParam qchjcOrderParam : orderSelected) {
                List<QchjcOrderGoodsParam> orderGoodsSelected = qchjcOrderParam.getOrderGoodsSelected();
                for (QchjcOrderGoodsParam qchjcOrderGoodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntityExample goodsEntityExample = new QchjcOrderGoodsEntityExample();
                    goodsEntityExample.createCriteria()
                            .andOrderSnEqualTo(qchjcOrderGoodsParam.getOrderSn())
                            .andOutSnapshotOrderGoodsIdEqualTo(qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(goodsEntityExample);
                    if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                        throw new OpenApiException(500, "发票单明细商品不存在,outSnapshotOrderGoodsId:" + qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    }
                    //集采商品绑定供应商发票申请id
                    QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                    qchjcOrderGoodsEntity.setQchSupplierInvoiceApplyId(copy.getId());
                    qchjcOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                }
            }
        }


    }

    /**
     * 外部用户入库统一订单，保存映射关系
     *
     * @param param
     */
    private void handleUser(QchjcInvoiceApplySupplierParam param) {
        String createUserId         = param.getApplyUserId();
        String createUserName       = param.getApplyUserName();
        String updateUserId         = param.getUpdateUserId();
        String updateUserName       = param.getUpdateUserName();
        String makeInvoicesUserId   = param.getMakeInvoiceUserId();
        String makeInvoicesUserName = param.getMakeInvoiceUserName();
        handle(createUserId, createUserName);
        handle(updateUserId, updateUserName);
        handle(makeInvoicesUserId, makeInvoicesUserName);

    }

    private void handle(String userId, String userName) {
        QchjcUserEntityExample example = new QchjcUserEntityExample();
        example.createCriteria()
                .andOutIdEqualTo(userId);
        List<QchjcUserEntity> creator = qchjcUserEntityMapper.selectByExample(example);
        QchjcUserEntity       createUser;
        if (CollectionUtils.isEmpty(creator) || null == creator.get(0)) {
            createUser = QchjcUserEntity.builder()
                    .outId(userId)
                    .userName(userName).build();
            qchjcUserEntityMapper.insertSelective(createUser);
        } else {
            createUser = creator.get(0);
        }
        if (createUser.getUnifiedId() == null) {
            //用户入库统一订单
            SysUser sysUser4Qchjc = sysUserService.createSysUser4Qchjc(userId, userName);
            if (sysUser4Qchjc == null) {
                createUser.setStorageStatus(QchjcStorageStatusEnum.FAIL.getStatus());
                qchjcUserEntityMapper.updateByPrimaryKeySelective(createUser);
                throw new OpenApiException(500, "同步失败,用户入库异常");
            }
            //保存统一订单用户id
            createUser.setUnifiedId(sysUser4Qchjc.getId());
            createUser.setStorageStatus(QchjcStorageStatusEnum.SUCCESS.getStatus());
            createUser.setStorageTime(DateUtil.date());
            qchjcUserEntityMapper.updateByPrimaryKeySelective(createUser);
        }
    }

    @Override
    public int insertSelective(QchjcInvoiceApplySupplierEntity qchjcInvoiceApplySupplierEntity) {
        return qchInvoiceApplySupplierEntityMapper.insertSelective(qchjcInvoiceApplySupplierEntity);
    }

    @Override
    public int updateByPrimaryKeySelective(QchjcInvoiceApplySupplierEntity qchjcInvoiceApplySupplierEntity) {
        return qchInvoiceApplySupplierEntityMapper.updateByPrimaryKeySelective(qchjcInvoiceApplySupplierEntity);
    }

    @Override
    public void deleteObj(Long id) {
        qchInvoiceApplySupplierEntityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public QchjcInvoiceApplySupplierEntity findById(Long id) {
        return qchInvoiceApplySupplierEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<QchjcInvoiceApplySupplierEntity> findAll(Map<String, Object> queryMap) {
        return null;
    }

    @Override
    public PageInfo<QchjcInvoiceApplySupplierEntity> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        return null;
    }
}
