package cn.superdesk.uniorder.service.thirdpart.szhtxx.paperInvoice.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceReqfCodeEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceUsedEnum;
import cn.superdesk.uniorder.common.numerical.AnBigDecimalUtils;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxExtendInfo;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfo;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.common.redBitchLlq.SzhtxxInvoiceFptxxOpRedLowerWorkLlqForm;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.common.singleBilling.SzhtxxInvoiceFptxxOpSingleBillingForm;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxListItemVo;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.request.SID20BitchLlq.ID0200.RedInvReqBillType;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.request.SID20BitchLlq.SID20BitchLlqRequestBody;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.FpxtComOutputStruct;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.SID20BitchLlqResponseBody;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.SID20BitchLlqResponseBodyEncmsgVo;
import cn.superdesk.uniorder.service.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxExtendInfoService;
import cn.superdesk.uniorder.service.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceFptxxSID20BitchLlqService;
import cn.superdesk.uniorder.service.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @Description: 金税盘页面-op申请红字信息表编号
 * @Author: linjinyu
 * @CreateDate: 2022/5/27 3:34 下午
 * @UpdateUser: linjinyu
 * @UpdateDate: 2022/5/27 3:34 下午
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class SzhtxxPaperInvoiceFptxxSID20BitchLlqServiceImpl implements SzhtxxPaperInvoiceFptxxSID20BitchLlqService {

    @Autowired
    private SzhtxxPaperInvoiceRedTaxInfoService szhtxxPaperInvoiceRedTaxInfoService;

    @Autowired
    private SzhtxxElectronicInvoiceFptxxExtendInfoService szhtxxElectronicInvoiceFptxxExtendInfoService;

    @Autowired
    private ResourceConstant resourceConstant;

    private void tmpLog(String type,
                        String fpqqlsh,
                        String batchId,
                        String messageBody,
                        String now) {

        String excelExportPathRoot             = resourceConstant.getPathRoot();
        String excelExportRelativePathTemplate = resourceConstant.getPathTemplate();
        String excelExportRelativePathStorage  = resourceConstant.getPathStorage();

        String relativePath = File.separator + "thirdpart" +
                File.separator + "szhtxx" +
                File.separator + "paperInvoice" +
                File.separator + "SID20BitchLlq" +
                File.separator + fpqqlsh +
                File.separator;

        String targetFullPath = excelExportPathRoot + excelExportRelativePathStorage;

        // 请求记录
        tmpLogWithFpqqlsh(targetFullPath, relativePath, type, fpqqlsh, batchId, messageBody, now);
    }

    protected void tmpLogWithFpqqlsh(
            String targetFullPath,
            String relativePath,
            String type,
            String fpqqlsh,
            String batchId,
            String jsonBody,
            String now) {

        String targetResponseFileName          = StrUtil.format("{}_{}_{}_{}.json", fpqqlsh, batchId, type, now);
        String targetResponseWriteFileFullPath = targetFullPath + relativePath + targetResponseFileName;
        FileUtil.touch(targetResponseWriteFileFullPath);
        FileUtil.writeUtf8String(jsonBody, targetResponseWriteFileFullPath);// CharsetUtil.CHARSET_UTF_8

    }

    /**************************************** 金税盘页面-op申请红字信息表编号-op确认申请(纸质专用发票)(深圳航信纸质票) start ****************************************/

    public int recordSID20BitchLlqID0200Request(
            SzhtxxInvoiceFptxxOpSingleBillingForm form,
            SzhtxxElectronicInvoiceFptxxListItemVo fptxxListItemVo,
            InvoiceApply invoiceApplyCustomerEnity,
            SID20BitchLlqRequestBody sid20BitchLlqRequestBody,
            DateTime nowDate,
            LoginSysUser loginSysUser) {

        tmpLog("request_form", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(form), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("request_fptxxListItemVo", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(fptxxListItemVo), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("request_invoiceApplyCustomerEnity", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(invoiceApplyCustomerEnity), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("request_requestBody", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(sid20BitchLlqRequestBody), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));


        int ret = 0;

        String            batchId       = sid20BitchLlqRequestBody.getBatchId();
        RedInvReqBillType redInvReqBill = sid20BitchLlqRequestBody.getFpxtTypeID0200().getINPUT().getRedInvReqBill();

        szhtxxPaperInvoiceRedTaxInfoService.saveOrUpdateByRedTaxInfoLshAndBatchId(
                SzhtxxPaperInvoiceRedTaxInfo
                        .builder()

                        .redTaxInfoLsh(redInvReqBill.getReqBillNo())
                        .batchId(batchId)

                        .deleted(CommonSoftDeleteEnum.临时.getKey()) // ---- 注意

                        .returnCode("")
                        .returnMsg("")


                        .redTaxInfoSn("") // 申请成功后才会有
                        .redTaxInfoStatus("") // 申请成功后才会有
                        .redTaxInfoDesc("") // 申请成功后才会有

                        .used(SzhtxxPaperInvoiceUsedEnum.未使用.getKey())

                        .fpdm(redInvReqBill.getTypeCode())
                        .fphm(redInvReqBill.getInvNo())
                        .fjh(redInvReqBill.getKpjh())

                        .ghfNsrsbh(redInvReqBill.getBuyTaxCode())
                        .ghfmc(redInvReqBill.getBuyerName())

                        .xhfNsrsbh(redInvReqBill.getSellTaxCode())
                        .xhfmc(redInvReqBill.getSellerName())

                        .ssyf(redInvReqBill.getKpjh())

//                        .kphjje() // add -- 价税合计金额^_^小数点后2位,以元为单位,精确到分
                        .hjbhsje(AnBigDecimalUtils.getBigDecimal(redInvReqBill.getAmount())) // 13 合计金额(不含税): 1. 取该申请数据提交时的不含税合计金额=-原发票的不含税合计金额; 2. 金额保留小数点两位，无需红色字体显示; 3. 此字段数据不可能为空;
                        .sl(AnBigDecimalUtils.getBigDecimal(redInvReqBill.getTax())) // 14 税率: 1. 取该申请数据提交时的税率; 2. 以`%`显示; 3. 此字段数据不可能为空;
                        .hjse(AnBigDecimalUtils.getBigDecimal(redInvReqBill.getTax())) // 15 税额: 1. 取该申请数据提交时的税额=-原发票的税额; 2. 金额保留小数点两位，无需红色字体显示; 3. 此字段数据不可能为空;

                        .reqfCode(SzhtxxPaperInvoiceReqfCodeEnum.getByReqExplain(redInvReqBill.getReqMemo()).getReqfCode())
                        .reqfName(SzhtxxPaperInvoiceReqfCodeEnum.getByReqExplain(redInvReqBill.getReqMemo()).getReqfName())
                        .reqExplain(redInvReqBill.getReqMemo())

                        .goldenTaxPlateNo(redInvReqBill.getSbbh())
                        .reqNsrsbh(redInvReqBill.getReqNsrsbh())
                        .backendMemo("") // 申请时是没有填的吧

//                        .createTime(now)
//                        .createUserId(loginSysUser.getSysUserId())
//                        .createUserName(loginSysUser.getFullName())

//                        .updateTime(now)
//                        .updateUserId(loginSysUser.getSysUserId())
//                        .updateUserName(loginSysUser.getFullName())

                        .build(),
                nowDate,
                loginSysUser);

        return ret;
    }

    public int recordSID20BitchLlqID0200Response(
            SzhtxxInvoiceFptxxOpSingleBillingForm form,
            SzhtxxElectronicInvoiceFptxxListItemVo fptxxListItemVo,
            InvoiceApply invoiceApplyCustomerEnity,
            SID20BitchLlqResponseBody sid20BitchLlqResponseBody,
            DateTime nowDate,
            LoginSysUser loginSysUser) {


        tmpLog("response_form", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(form), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("response_fptxxListItemVo", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(fptxxListItemVo), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("response_invoiceApplyCustomerEnity", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(invoiceApplyCustomerEnity), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("response_responseBody", form.getFpqqlsh(), form.getBatchId(), JSONUtil.toJsonPrettyStr(sid20BitchLlqResponseBody), DateUtil.format(nowDate, DatePattern.NORM_DATETIME_PATTERN));

        String   batchId     = form.getBatchId();
        String   fpqqlshBlue = form.getFpqqlsh();
//        DateTime now         = DateUtil.date();

        int ret = 0;

        SID20BitchLlqResponseBodyEncmsgVo response = sid20BitchLlqResponseBody.getEncmsgVo();

        // 第一层
        if (ObjectUtil.isNotNull(response) && "0".equals(response.getReturnCode())) {

            // TODO ...


            // 第二层
            FpxtComOutputStruct fpxtComOutputStruct = sid20BitchLlqResponseBody.getFpxtComOutputStruct();

            if (ObjectUtil.isNotNull(fpxtComOutputStruct) && "0000".equals(fpxtComOutputStruct.getCODE())) {

                cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.ID0200.FpxtType fpxtTypeID0200 = sid20BitchLlqResponseBody.getFpxtTypeID0200();


                if (ObjectUtil.isNotNull(fpxtTypeID0200) && "0000".equals(fpxtTypeID0200.getOUTPUT().getCODE())) {

                    List<cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.ID0200.RedInvReqBillType> redInvReqBill =
                            fpxtTypeID0200.getOUTPUT().getDATA().getRedInvReqBill();

                    // 一般情况下只有一条
                    redInvReqBill.forEach(redInvReqBillType -> {

                        szhtxxPaperInvoiceRedTaxInfoService.saveOrUpdateByRedTaxInfoLshAndBatchId(
                                SzhtxxPaperInvoiceRedTaxInfo
                                        .builder()

                                        .redTaxInfoLsh(redInvReqBillType.getReqBillNo()) // 对应INPUT中的ReqBillNo
                                        .batchId(batchId)

                                        .deleted(CommonSoftDeleteEnum.正常.getKey()) // ---- 注意

                                        .returnCode(fpxtTypeID0200.getOUTPUT().getCODE())
                                        .returnMsg(fpxtTypeID0200.getOUTPUT().getMESS())

                                        .redTaxInfoSn(redInvReqBillType.getResBillNo()) // 申请成功后才会有 // 信息表编号（税局返回的 16 位信息表编号）
                                        .redTaxInfoStatus(redInvReqBillType.getStatusDM()) // 申请成功后才会有 // 信息表状态代码，TZD0000、TZD1000 表示可以填开红票
                                        .redTaxInfoDesc(redInvReqBillType.getStatusMC()) // 申请成功后才会有 // 信息表状态描述

                                        .build(),
                                nowDate,
                                loginSysUser);

                        SzhtxxElectronicInvoiceFptxxExtendInfo extendInfoBlue = szhtxxElectronicInvoiceFptxxExtendInfoService.findByFpqqlsh(fpqqlshBlue);

                        if (ObjectUtil.isNotNull(extendInfoBlue)) {

                            szhtxxElectronicInvoiceFptxxExtendInfoService.saveOrUpdateByFpqqlsh(
                                    SzhtxxElectronicInvoiceFptxxExtendInfo
                                            .builder()
                                            .fpqqlsh(fpqqlshBlue)

                                            .redTaxInfoSn(redInvReqBillType.getResBillNo())
                                            .build()
                            );
                        }

                    });

                    ret = 1;

                } else {
//                    操作结果 0000：上传成功，其它上传失败
                }


            } else {
                // 表示 CODE 不为 0000 DATA 为空
            }


        } else {

        }

        return ret;
    }

    /**************************************** 金税盘页面-op申请红字信息表编号-op确认申请(纸质专用发票)(深圳航信纸质票)   end ****************************************/

    /**************************************** 金税盘页面-op下载红字信息表编号-op确认下载(纸质专用发票)(深圳航信纸质票) start ****************************************/

    public int recordSID20LowerWorkLlqRequestID0201Request(
            SzhtxxInvoiceFptxxOpRedLowerWorkLlqForm form,
            SID20BitchLlqRequestBody requestBody,
            DateTime now,
            LoginSysUser loginSysUser) {

        tmpLog("request_form", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN), form.getBatchId(), JSONUtil.toJsonPrettyStr(form), DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("request_requestBody", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN), form.getBatchId(), JSONUtil.toJsonPrettyStr(requestBody), DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));

        return 0;
    }


    public int recordSID20LowerWorkLlqRequestID0201Response(
            SzhtxxInvoiceFptxxOpRedLowerWorkLlqForm form,
            SID20BitchLlqResponseBody sid20BitchLlqResponseBody,
            DateTime now,
            LoginSysUser loginSysUser) {

        tmpLog("request_form", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN), form.getBatchId(), JSONUtil.toJsonPrettyStr(form), DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));
        tmpLog("request_responseBody", DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN), form.getBatchId(), JSONUtil.toJsonPrettyStr(sid20BitchLlqResponseBody), DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN));

        int ret = 0;

        SID20BitchLlqResponseBodyEncmsgVo response = sid20BitchLlqResponseBody.getEncmsgVo();

        // 第一层
        if (ObjectUtil.isNotNull(response) && "0".equals(response.getReturnCode())) {

            // TODO ...


            // 第二层
            FpxtComOutputStruct fpxtComOutputStruct = sid20BitchLlqResponseBody.getFpxtComOutputStruct();

            if (ObjectUtil.isNotNull(fpxtComOutputStruct) && "0000".equals(fpxtComOutputStruct.getCODE())) {

                cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.ID0200.FpxtType fpxtTypeID0200 = sid20BitchLlqResponseBody.getFpxtTypeID0200();


                if (ObjectUtil.isNotNull(fpxtTypeID0200) && "0000".equals(fpxtTypeID0200.getOUTPUT().getCODE())) {

                    List<cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.response.SID20BitchLlq.ID0200.RedInvReqBillType> redInvReqBill =
                            fpxtTypeID0200.getOUTPUT().getDATA().getRedInvReqBill();

                    // 一般情况下只有一条
                    redInvReqBill.forEach(redInvReqBillType -> {



                    });

                    ret = 1;

                } else {
//                    操作结果 0000：上传成功，其它上传失败
                }


            } else {
                // 表示 CODE 不为 0000 DATA 为空
            }


        } else {

        }

        return ret;
    }

    /**************************************** 金税盘页面-op下载红字信息表编号-op确认下载(纸质专用发票)(深圳航信纸质票)   end ****************************************/
}
