package com.jianshui.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.common.utils.SecurityUtils;
import com.jianshui.common.utils.ValidateUtils;
import com.jianshui.invoice.domain.BillInfo;
import com.jianshui.invoice.domain.Invoice;
import com.jianshui.invoice.domain.dto.HXResponse;
import com.jianshui.invoice.enums.ChannelSource;
import com.jianshui.invoice.factory.IInvoiceServiceFactory;
import com.jianshui.invoice.mapper.BillInfoMapper;
import com.jianshui.invoice.mapper.InvoiceMapper;
import com.jianshui.invoice.service.IInvoiceApiService;
import com.jianshui.platform.dto.CopyBillInfoQueryDTO;
import com.jianshui.platform.dto.InvoiceAdd.BillInfoPDTO;
import com.jianshui.platform.dto.InvoiceAdd.species.BillInfoSDGenInvoicePDTO;
import com.jianshui.platform.dto.InvoiceAdd.species.BillInfoSDSpecialInvoicePDTO;
import com.jianshui.platform.enums.InvoiceType;
import com.jianshui.platform.service.InvoiceAddPService;
import com.jianshui.platform.utils.InvoiceAllYhdjUtils;
import com.jianshui.system.domain.InvoiceAllYhdj;
import com.jianshui.system.mapper.CompanyserviceMapper;
import com.jianshui.system.service.IServiceManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
* @Author: kk
* @Description: 发票管理
* @DateTime: 2023/6/26 11:59
*/
@Service
@Slf4j
public class InvoiceAddPServiceImpl implements InvoiceAddPService {

    @Autowired
    private static BillInfoMapper billInfoMapper;

    @Autowired
    private IServiceManageService serviceManageService;

    @Autowired
    private IInvoiceServiceFactory invoiceServiceFactory;

    @Autowired
    private CompanyserviceMapper companyServiceMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;


    @Override
    public int invoiceSave(BillInfoPDTO billInfoPDTO) {
        ValidateUtils.validate(billInfoPDTO);

        BillInfo billInfo = BeanUtil.copyProperties(billInfoPDTO, BillInfo.class);
        // 手工录入
        billInfo.setSource("3");
        return billInfoMapper.insertBillInfo(billInfo);

    }

    /**
    * @Author: kk
    * @Description: 发票开具
    */
    @Override
    public HXResponse invoiceIssuance(BillInfoPDTO billInfoPDTO) {

        String invoiceType = Optional.ofNullable(billInfoPDTO.getInvoiceType()).orElse("");

        // 数电(普票、专票)校验
        BillInfo billInfo = null;
        if(InvoiceType.SHU_DIAN_ZHUAN_PIAO.getCode().equals(invoiceType)){
            BillInfoSDGenInvoicePDTO sdGenInvoicePDTO = BeanUtil.copyProperties(billInfoPDTO, BillInfoSDGenInvoicePDTO.class);
            ValidateUtils.validate(sdGenInvoicePDTO.getBillInfoDetailPDTOList());
            ValidateUtils.validate(sdGenInvoicePDTO);

            billInfo = BeanUtil.copyProperties(sdGenInvoicePDTO, BillInfo.class);

        }else if(InvoiceType.SHU_DIAN_PU_PIAO.getCode().equals(invoiceType)){
            BillInfoSDSpecialInvoicePDTO sdSpecialInvoicePDTO = BeanUtil.copyProperties(billInfoPDTO, BillInfoSDSpecialInvoicePDTO.class);
            ValidateUtils.validate(sdSpecialInvoicePDTO.getBillInfoDetailPDTOList());
            ValidateUtils.validate(sdSpecialInvoicePDTO);

            billInfo = BeanUtil.copyProperties(sdSpecialInvoicePDTO, BillInfo.class);

        }else {
            return new HXResponse("未获取到发票类别！");
        }

        billInfo = BeanUtil.copyProperties(billInfoPDTO, BillInfo.class);

        // 蓝票
        billInfo.setKptype("1");
        billInfo.setSource(ChannelSource.PLATFORM.getCode());

        // 获取用户信息
        Long companyId = Optional.ofNullable(SecurityUtils.getLoginUser())
                .map(loginUser -> loginUser.getCompanyId())
                .orElse(0L);
        if (companyId == 0L) {
            return new HXResponse("未获取到用户服务信息，请联系管理员配置！");
        }
        Companyservice companyservice = companyServiceMapper.selectCompanyserviceByCompanyid(companyId);
        if (BeanUtil.isEmpty(companyservice)) {
            return new HXResponse(("未获取到用户服务信息，请联系管理员配置！"));
        }

        InvoiceAllYhdjUtils invoiceAllYhdjUtils = new InvoiceAllYhdjUtils();
        InvoiceAllYhdj userInfo = invoiceAllYhdjUtils.getUserInfo(companyservice);

        if (BeanUtil.isEmpty(userInfo)) {
            return new HXResponse(("未查询到登记信息！"));
        }

        // 获得请求实例，并且进行扣费
        String serviceKey = null;
        try {
            serviceKey = serviceManageService.getCompanyServiceSupplier("invoice", companyservice.getCompanyid());

            serviceManageService.companyConsume("invoice", companyId);
            billInfo.setServiceSupplierKey(serviceKey);
            IInvoiceApiService invoiceService = invoiceServiceFactory.getService(serviceKey);

            return invoiceService.addInvoice(billInfo, companyservice);
        } catch (Exception e) {
            log.error("简税产品端，发票开具失败，请求报文={},企业税号={},servicekey={}",billInfoPDTO.toString(),companyservice.toString(),serviceKey);
            throw new JianshuiServiceException("发票开具系统异常！");
        }

    }




}
