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

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcOrgEnum;
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.organisation.SysEnterpriseExtInvoice;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterpriseExtInvoiceExample;
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.QchjcInvoiceApplyEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.invoice.QchjcInvoiceApplyEntityExample;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcEnterpriseEntity;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseExtInvoiceMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcAccountingScoreCustomerEntityMapper;
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.QchjcInvoiceApplyEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcEnterpriseEntityMapper;
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.QchjcInvoiceApplyParam;
import cn.superdesk.uniorder.service.sys.SysUserService;
import cn.superdesk.uniorder.service.thirdpart.qchjc.invoice.QchjcCustomerInvoiceService;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * @author xc
 * @description
 * @date 2022/4/1 20:22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QchjcCustomerInvoiceServiceImpl implements QchjcCustomerInvoiceService {
    private final QchjcInvoiceApplyEntityMapper            qchInvoiceApplyEntityMapper;
    private final QchjcUserEntityMapper                    qchjcUserEntityMapper;
    private final SysUserService                           sysUserService;
    private final QchjcAccountingScoreCustomerEntityMapper qchjcAccountingScoreCustomerEntityMapper;
    private final QchjcOrderGoodsEntityMapper              qchjcOrderGoodsEntityMapper;
    private final QchjcEnterpriseEntityMapper              qchjcEnterpriseEntityMapper;
    private final SysEnterpriseExtInvoiceMapper            sysEnterpriseExtInvoiceMapper;

    @Override
    public int insertSelective(QchjcInvoiceApplyEntity qchjcInvoiceApplyEntity) {
        return qchInvoiceApplyEntityMapper.insertSelective(qchjcInvoiceApplyEntity);
    }

    @Override
    public int updateByPrimaryKeySelective(QchjcInvoiceApplyEntity qchjcInvoiceApplyEntity) {
        return qchInvoiceApplyEntityMapper.updateByPrimaryKeySelective(qchjcInvoiceApplyEntity);
    }

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

    @Override
    public QchjcInvoiceApplyEntity findById(Long id) {
        return qchInvoiceApplyEntityMapper.selectByPrimaryKey(id);
    }

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receive(String data) throws OpenApiException {
        QchjcInvoiceApplyParam param         = AnJsonUtils.toObject(data, QchjcInvoiceApplyParam.class);
        List<QchjcOrderParam>  orderSelected = param.getOrderSelected();
        if (CollectionUtils.isEmpty(orderSelected)) {
            throw new OpenApiException(500, "采购单位发票单明细不能为空");
        }
        //参数校验
        QchjcAccountingScoreCustomerEntityExample example = new QchjcAccountingScoreCustomerEntityExample();
        example.createCriteria()
                .andAccountingOrderSnEqualTo(param.getAccountingOrderSn());
        List<QchjcAccountingScoreCustomerEntity> entities = qchjcAccountingScoreCustomerEntityMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(entities)) {
            throw new OpenApiException(500, "该发票单所属的对账单主体数据查询不到，请重新推送对账单");
        }
        QchjcAccountingScoreCustomerEntity qchjcAccountingScoreCustomerEntity = entities.get(0);
        if (!Objects.equals(qchjcAccountingScoreCustomerEntity.getStorageStatus(), QchjcStorageStatusEnum.FAIL.getStatus())
                && !Objects.equals(qchjcAccountingScoreCustomerEntity.getStorageStatus(), QchjcStorageStatusEnum.TODO.getStatus())) {
            //如果对账单主体的状态不是待入库或者入库失败，则不允许推送发票单
            throw new OpenApiException(500, "所属对账单处于入库中或入库成功,不允许推送发票单");
        }
        //保存用户信息
        handleUser(param);
        //保存发票单主体数据
        QchjcInvoiceApplyEntityExample qchjcInvoiceApplyEntityExample = new QchjcInvoiceApplyEntityExample();
        qchjcInvoiceApplyEntityExample.createCriteria()
                .andAccountingOrderSnEqualTo(param.getAccountingOrderSn())
                .andInvoiceSnEqualTo(param.getInvoiceSn());
        List<QchjcInvoiceApplyEntity> qchjcInvoiceApplyEntities = qchInvoiceApplyEntityMapper.selectByExample(qchjcInvoiceApplyEntityExample);
        if (CollectionUtils.isNotEmpty(qchjcInvoiceApplyEntities)) {
            Long                    customerInvoiceApplyId = qchjcInvoiceApplyEntities.get(0).getId();
            QchjcInvoiceApplyEntity copy                   = AnBeanUtils.copy(param, qchjcInvoiceApplyEntities.get(0));
            int                     sum                    = orderSelected.stream().map(x -> x.getOrderGoodsSelected().size()).reduce(0, Integer::sum);
            copy.setJcOrderCount(sum);
            copy.setTaxPayersIDCode(param.getTaxpayersIDCode());//纳税人识别号
            //创建开票抬头信息
            SysEnterpriseExtInvoiceExample sysEnterpriseExtInvoiceExample = new SysEnterpriseExtInvoiceExample();
            sysEnterpriseExtInvoiceExample.createCriteria().
                    andTaxpayersIDCodeEqualTo(param.getTaxpayersIDCode())
                    .andCompanyNameEqualTo(param.getCompanyName());
            List<SysEnterpriseExtInvoice> sysEnterpriseExtInvoices  = sysEnterpriseExtInvoiceMapper.selectByExample(sysEnterpriseExtInvoiceExample);
            Long                          sysEnterpriseExtInvoiceId = null;
            if (CollectionUtils.isEmpty(sysEnterpriseExtInvoices)) {

                SysEnterpriseExtInvoice sysEnterpriseExtInvoice = SysEnterpriseExtInvoice.builder()
                        .sysOrgId(copy.getSysOrgId())
                        .sysVirtId(copy.getSysVirtId())
                        .outOrgId(copy.getOutOrgId())
                        .invoiceState(copy.getInvoiceState())
                        .invoiceType(copy.getInvoiceType().intValue())
                        .selectedInvoiceTitle(copy.getSelectedInvoiceTitle())
                        .companyName(copy.getCompanyName())
                        .taxpayersIDCode(copy.getTaxPayersIDCode())
                        .invoiceContent(copy.getInvoiceContent())
                        .invoiceName(copy.getInvoiceName())
                        .invoicePhone(copy.getInvoicePhone())
                        .invoiceEmail(copy.getInvoiceEmail())
                        .contactsName(copy.getContactsName())
                        .contactsEmail(copy.getContactsEmail())
                        .contactsPhone(copy.getContactsPhone())
                        .invoiceProvice(copy.getInvoiceProvice())
                        .invoiceCity(copy.getInvoiceCity())
                        .invoiceCounty(copy.getInvoiceCounty())
                        .invoiceAddress(copy.getInvoiceAddress())
                        .invoiceAddressPhone(copy.getInvoiceAddressPhone())
                        .invoiceBankAccountNumber(copy.getInvoiceBankAccountNumber())
                        .invoiceBank(copy.getInvoiceBank())
                        .invoiceAccount(copy.getInvoiceAccount()).deleted(0).enabled(1)
                        .createTime(DateUtil.date())
                        .createUserId(1L).build();
                sysEnterpriseExtInvoiceMapper.insertSelective(sysEnterpriseExtInvoice);
                sysEnterpriseExtInvoiceId = sysEnterpriseExtInvoice.getId();
            } else {
                SysEnterpriseExtInvoice exist = sysEnterpriseExtInvoices.get(0);
                SysEnterpriseExtInvoice sysEnterpriseExtInvoice = SysEnterpriseExtInvoice.builder()
                        .sysOrgId(copy.getSysOrgId())
                        .sysVirtId(copy.getSysVirtId())
                        .outOrgId(copy.getOutOrgId())
                        //.outVirtId()//集采的id是uuid
                        .invoiceState(copy.getInvoiceState())
                        .invoiceType(copy.getInvoiceType().intValue())
                        .selectedInvoiceTitle(copy.getSelectedInvoiceTitle())
                        .companyName(copy.getCompanyName())
                        .taxpayersIDCode(copy.getTaxPayersIDCode())
                        .invoiceContent(copy.getInvoiceContent())
                        .invoiceName(copy.getInvoiceName())
                        .invoicePhone(copy.getInvoicePhone())
                        .invoiceEmail(copy.getInvoiceEmail())
                        .contactsName(copy.getContactsName())
                        .contactsEmail(copy.getContactsEmail())
                        .contactsPhone(copy.getContactsPhone())
                        .invoiceProvice(copy.getInvoiceProvice())
                        .invoiceCity(copy.getInvoiceCity())
                        .invoiceCounty(copy.getInvoiceCounty())
                        .invoiceAddress(copy.getInvoiceAddress())
                        .invoiceAddressPhone(copy.getInvoiceAddressPhone())
                        .invoiceBankAccountNumber(copy.getInvoiceBankAccountNumber())
                        .invoiceBank(copy.getInvoiceBank())
                        .invoiceAccount(copy.getInvoiceAccount()).deleted(0).enabled(1)
                        .createTime(DateUtil.date())
                        .createUserId(1L).build();

                sysEnterpriseExtInvoice.setId(exist.getId());
                sysEnterpriseExtInvoiceMapper.updateByPrimaryKeySelective(sysEnterpriseExtInvoice);
                sysEnterpriseExtInvoiceId = sysEnterpriseExtInvoice.getId();
            }
            //把开票抬头id更新回中间表
            copy.setSysEnterpriseExtInvoiceId(sysEnterpriseExtInvoiceId);
            qchInvoiceApplyEntityMapper.updateByPrimaryKeySelective(copy);
            //清除商品绑定的采购单位发票单
            qchjcOrderGoodsEntityMapper.clearCustomerInvoiceOrderGoodsBind(customerInvoiceApplyId);
            //商品绑定发票申请id
            for (QchjcOrderParam qchjcOrderParam : orderSelected) {
                List<QchjcOrderGoodsParam> orderGoodsSelected = qchjcOrderParam.getOrderGoodsSelected();
                for (QchjcOrderGoodsParam qchjcOrderGoodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntityExample goodsEntityExample = new QchjcOrderGoodsEntityExample();
                    goodsEntityExample.createCriteria()
                            .andOutSnapshotOrderGoodsIdEqualTo(qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId())
                            .andOrderSnEqualTo(qchjcOrderGoodsParam.getOrderSn());
                    List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(goodsEntityExample);
                    if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                        throw new OpenApiException(500, "发票单明细商品不存在" + qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    }
                    //集采商品绑定采购单位发票申请id
                    QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                    qchjcOrderGoodsEntity.setQchCustomerInvoiceApplyId(customerInvoiceApplyId);
                    qchjcOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                }
            }
        } else {
            QchjcInvoiceApplyEntity                   copy     = AnBeanUtils.copy(param, QchjcInvoiceApplyEntity.class);
            QchjcAccountingScoreCustomerEntityExample example1 = new QchjcAccountingScoreCustomerEntityExample();
            example1.createCriteria().andAccountingOrderSnEqualTo(param.getAccountingOrderSn());
            List<QchjcAccountingScoreCustomerEntity> entities1 = qchjcAccountingScoreCustomerEntityMapper.selectByExample(example1);
            copy.setAccountingOrderId(entities1.get(0).getId());//对账单id
            copy.setAccountingOrderType(2);//对账单类型 默认积分
            copy.setDimCreateBy(2);//对账单维度 默认流水
            copy.setBackAccountModeRecord(0);//回款登记方式，默认0 初始
            copy.setTaxPayersIDCode(param.getTaxpayersIDCode());//纳税人识别号
            copy.setInvoiceEmail(param.getInvoiceSendEmail());//发票邮箱
            copy.setServiceName(CommonServiceNoEnum.企业商城_侨城汇.getServiceName());
            copy.setOutVirtId(entities1.get(0).getPurchaseVirtId());//所属第三方企业id
            copy.setOutOrgId(QchjcOrgEnum.CUSTOMER.getOrgId());
            copy.setSysOrgId(QchjcOrgEnum.CUSTOMER.getOrgId());
            int sum = orderSelected.stream().map(x -> x.getOrderGoodsSelected().size()).reduce(0, Integer::sum);
            copy.setJcOrderCount(sum);
            QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(entities1.get(0).getPurchaseVirtId());
            copy.setSysVirtId(qchjcEnterpriseEntity.getId());
            qchInvoiceApplyEntityMapper.insertSelective(copy);

            //创建开票抬头信息
            SysEnterpriseExtInvoiceExample sysEnterpriseExtInvoiceExample = new SysEnterpriseExtInvoiceExample();
            sysEnterpriseExtInvoiceExample.createCriteria().
                    andTaxpayersIDCodeEqualTo(param.getTaxpayersIDCode())
                    .andCompanyNameEqualTo(param.getCompanyName());
            List<SysEnterpriseExtInvoice> sysEnterpriseExtInvoices  = sysEnterpriseExtInvoiceMapper.selectByExample(sysEnterpriseExtInvoiceExample);
            Long                          sysEnterpriseExtInvoiceId = null;
            if (CollectionUtils.isEmpty(sysEnterpriseExtInvoices)) {

                SysEnterpriseExtInvoice sysEnterpriseExtInvoice = SysEnterpriseExtInvoice.builder()
                        .sysOrgId(copy.getSysOrgId())
                        .sysVirtId(copy.getSysVirtId())
                        .outOrgId(copy.getOutOrgId())
                        //.outVirtId()//集采的id是uuid
                        .invoiceState(copy.getInvoiceState())
                        .invoiceType(copy.getInvoiceType().intValue())
                        .selectedInvoiceTitle(copy.getSelectedInvoiceTitle())
                        .companyName(copy.getCompanyName())
                        .taxpayersIDCode(copy.getTaxPayersIDCode())
                        .invoiceContent(copy.getInvoiceContent())
                        .invoiceName(copy.getInvoiceName())
                        .invoicePhone(copy.getInvoicePhone())
                        .invoiceEmail(copy.getInvoiceEmail())
                        .contactsName(copy.getContactsName())
                        .contactsEmail(copy.getContactsEmail())
                        .contactsPhone(copy.getContactsPhone())
                        .invoiceProvice(copy.getInvoiceProvice())
                        .invoiceCity(copy.getInvoiceCity())
                        .invoiceCounty(copy.getInvoiceCounty())
                        .invoiceAddress(copy.getInvoiceAddress())
                        .invoiceAddressPhone(copy.getInvoiceAddressPhone())
                        .invoiceBankAccountNumber(copy.getInvoiceBankAccountNumber())
                        .invoiceBank(copy.getInvoiceBank())
                        .invoiceAccount(copy.getInvoiceAccount()).deleted(0).enabled(1)
                        .createTime(DateUtil.date())
                        .createUserId(1L).build();
                sysEnterpriseExtInvoiceMapper.insertSelective(sysEnterpriseExtInvoice);
                sysEnterpriseExtInvoiceId = sysEnterpriseExtInvoice.getId();
            } else {
                SysEnterpriseExtInvoice exist = sysEnterpriseExtInvoices.get(0);
                SysEnterpriseExtInvoice sysEnterpriseExtInvoice = SysEnterpriseExtInvoice.builder()
                        .sysOrgId(copy.getSysOrgId())
                        .sysVirtId(copy.getSysVirtId())
                        .outOrgId(copy.getOutOrgId())
                        //.outVirtId()//集采的id是uuid
                        .invoiceState(copy.getInvoiceState())
                        .invoiceType(copy.getInvoiceType().intValue())
                        .selectedInvoiceTitle(copy.getSelectedInvoiceTitle())
                        .companyName(copy.getCompanyName())
                        .taxpayersIDCode(copy.getTaxPayersIDCode())
                        .invoiceContent(copy.getInvoiceContent())
                        .invoiceName(copy.getInvoiceName())
                        .invoicePhone(copy.getInvoicePhone())
                        .invoiceEmail(copy.getInvoiceEmail())
                        .contactsName(copy.getContactsName())
                        .contactsEmail(copy.getContactsEmail())
                        .contactsPhone(copy.getContactsPhone())
                        .invoiceProvice(copy.getInvoiceProvice())
                        .invoiceCity(copy.getInvoiceCity())
                        .invoiceCounty(copy.getInvoiceCounty())
                        .invoiceAddress(copy.getInvoiceAddress())
                        .invoiceAddressPhone(copy.getInvoiceAddressPhone())
                        .invoiceBankAccountNumber(copy.getInvoiceBankAccountNumber())
                        .invoiceBank(copy.getInvoiceBank())
                        .invoiceAccount(copy.getInvoiceAccount()).deleted(0).enabled(1)
                        .createTime(DateUtil.date())
                        .createUserId(1L).build();

                sysEnterpriseExtInvoice.setId(exist.getId());
                sysEnterpriseExtInvoiceMapper.updateByPrimaryKeySelective(sysEnterpriseExtInvoice);
                sysEnterpriseExtInvoiceId = sysEnterpriseExtInvoice.getId();
            }
            //把开票抬头id更新回中间表
            copy.setSysEnterpriseExtInvoiceId(sysEnterpriseExtInvoiceId);
            qchInvoiceApplyEntityMapper.updateByPrimaryKeySelective(copy);
            //清除商品绑定的采购单位发票单
            qchjcOrderGoodsEntityMapper.clearCustomerInvoiceOrderGoodsBind(copy.getId());
            //商品绑定发票申请id
            for (QchjcOrderParam qchjcOrderParam : orderSelected) {
                List<QchjcOrderGoodsParam> orderGoodsSelected = qchjcOrderParam.getOrderGoodsSelected();
                for (QchjcOrderGoodsParam qchjcOrderGoodsParam : orderGoodsSelected) {
                    QchjcOrderGoodsEntityExample goodsEntityExample = new QchjcOrderGoodsEntityExample();
                    goodsEntityExample.createCriteria()
                            .andOutSnapshotOrderGoodsIdEqualTo(qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId())
                            .andOrderSnEqualTo(qchjcOrderGoodsParam.getOrderSn());
                    List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(goodsEntityExample);
                    if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                        throw new OpenApiException(500, "发票单明细商品不存在" + qchjcOrderGoodsParam.getOutSnapshotOrderGoodsId());
                    }
                    //集采商品绑定采购单位发票申请id
                    QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                    qchjcOrderGoodsEntity.setQchCustomerInvoiceApplyId(copy.getId());
                    qchjcOrderGoodsEntityMapper.updateByPrimaryKeySelective(qchjcOrderGoodsEntity);
                }
            }
        }

    }

    private void handleUser(QchjcInvoiceApplyParam param) {
        String createUserId   = param.getApplyUserId();
        String createUserName = param.getApplyUserName();
        String updateUserId   = param.getUpdateUserId();
        String updateUserName = param.getUpdateUserName();
        String applyUserId    = param.getApplyUserId();
        String applyUserName  = param.getApplyUserName();
        handle(createUserId, createUserName);
        handle(updateUserId, updateUserName);
        handle(applyUserId, applyUserName);
    }

    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);
        }
    }
}
