package cn.superdesk.uniorder.controller._thirdpart.szhtxx.paperInvoice;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.enums.common.CommonFormStateEnum;
import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceResponseCodeEnum;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.config.mail.MailAccountConfigFactory;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
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.param.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxQueryCriteria;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxDetailVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxListItemVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceFptxxOpRedBitchLlqVo;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceFptxxopRedLowerWorkLlqVo;
import cn.superdesk.uniorder.dubbo.consumer._common.ProviderEnvConstantDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.thirdpart.szhtxx.electronicInvoice.SzhtxxElectronicInvoiceFptxxDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceFptxxDubboConsumerService;
import cn.superdesk.uniorder.openapicall.thirdpart.szhtxx.paperInvoice.dto.request.SID20BitchLlq.SID20BitchLlqRequestBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2022/5/24 5:35 下午
 * @UpdateUser: linjinyu
 * @UpdateDate: 2022/5/24 5:35 下午
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "第三方-深圳航信纸质票", tags = {"第三方-深圳航信纸质票"})
@Slf4j
@RestController
@RequestMapping("/thirdpart/szhtxx/paperInvoiceFptxx/RedFxck")
public class SzhtxxPaperInvoiceFptxxRedFxckController extends BaseController {

    @Autowired
    private SzhtxxElectronicInvoiceFptxxDubboConsumerService szhtxxElectronicInvoiceFptxxDubboConsumerService;
    @Autowired
    private SzhtxxPaperInvoiceFptxxDubboConsumerService      szhtxxPaperInvoiceFptxxDubboConsumerService;


    @Autowired
    private InvoiceApplyCustomerDubboConsumerService invoiceApplyCustomerDubboConsumerService;

    @Autowired
    private MailAccountConfigFactory mailAccountConfigFactory;
    @Autowired
    private TemplateEngine           templateEngine;

    @Resource
    private ProviderEnvConstantDubboCustomerService providerEnvConstantDubboCustomerService;

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


    @ApiOperation(value = "op申请红字信息表编号-Request(纸质专用发票)(深圳航信纸质票)")
    @RequestMapping(value = "/opRedBitchLlq/request", method = RequestMethod.POST)
    @ResponseBody
    public R<SzhtxxPaperInvoiceFptxxOpRedBitchLlqVo> opRedBitchLlqRequest(@RequestBody SzhtxxInvoiceFptxxOpSingleBillingForm form) {

        R<SzhtxxPaperInvoiceFptxxOpRedBitchLlqVo> result = new R<>();

        form.setFormState(CommonFormStateEnum.预览);

        try {


            /******************************************** 初始化 start ********************************************/

            InvoiceApply invoiceApplyCustomerEntity = invoiceApplyCustomerDubboConsumerService.findByInvoiceApplySn(form.getFpqqlsh(), getToken());

            // 该发票的回款状态非“发票红冲/发票作废”，若为“发票红冲/发票作废”，不允许修改，1.5s提示“该发票已红冲/作废，无需修改”；
            Integer[] invoiceApplyCustomerBackAccountStatusContains001 = {
                    InvoiceApplyCustomerBackAccountStatusEnum.发票红冲.getKey(),
                    InvoiceApplyCustomerBackAccountStatusEnum.发票作废.getKey()
            };

            if (ArrayUtil.contains(
                    invoiceApplyCustomerBackAccountStatusContains001,
                    invoiceApplyCustomerEntity.getBackAccountStatus())
            ) {
                return ResponseResultOuterUtils.createErrorResult("500", "该发票已红冲/作废，无需修改");
            }


            // 该发票的回款状态为“未回款”，若非“未回款”，1.5s提示“只允许未回款的发票申请红字信息表编号，请返回检查”；
            Integer[] invoiceApplyCustomerBackAccountStatusContains002 = {
                    InvoiceApplyCustomerBackAccountStatusEnum.未回款.getKey()
            };
            if (!ArrayUtil.contains(
                    invoiceApplyCustomerBackAccountStatusContains002,
                    invoiceApplyCustomerEntity.getBackAccountStatus())
            ) {
                return ResponseResultOuterUtils.createErrorResult("500", "只允许未回款的发票申请红字信息表编号，请返回检查");
            }

            List<SzhtxxElectronicInvoiceFptxxListItemVo> resultList = szhtxxElectronicInvoiceFptxxDubboConsumerService.queryGenericParam(
                    SzhtxxElectronicInvoiceFptxxQueryCriteria.builder()
                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
                            .build(),
                    getToken()
            );

            if (CollUtil.isEmpty(resultList)) {
                return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
            }

            SzhtxxElectronicInvoiceFptxxListItemVo fptxxListItemVo = resultList.get(0);

            if (StrUtil.isNotBlank(fptxxListItemVo.getRedTaxInfoSn())) {
                return ResponseResultOuterUtils.createErrorResult("500", "该发票已申请红字信息表编号，无需重复申请");
            }

            /******************************************** 初始化   end ********************************************/

            /**************************************** 蓝票主体 start ****************************************/

            SzhtxxElectronicInvoiceFptxxDetailVo fptxxOrigin = szhtxxElectronicInvoiceFptxxDubboConsumerService.detailGenericParamSzhtxxElectronicInvoiceFptxx(
                    SzhtxxElectronicInvoiceFptxxQueryCriteria.builder()
                            .fpqqlsh(form.getFpqqlsh())
                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
                            .build(),
                    getToken()
            );

            /**************************************** 蓝票主体 start ****************************************/


            /******************************************** 红票主体 start ********************************************/

            SID20BitchLlqRequestBody sid20BitchLlqRequestBody = szhtxxPaperInvoiceFptxxDubboConsumerService.opRedBitchLlqRequest(
                    form,
                    fptxxListItemVo,
                    invoiceApplyCustomerEntity,
                    getToken()
            );

            /******************************************** 红票主体   end ********************************************/

            result.setSuccess(true);
            result.setData(SzhtxxPaperInvoiceFptxxOpRedBitchLlqVo.builder()
                    .fptxxOrigin(fptxxOrigin)
                    .fttxxRedWrite(
                            sid20BitchLlqRequestBody
                                    .dataID0200()
                                    .shell()
                                    .packing()
                    )
                    .build());

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return result;
    }

    @ApiOperation(value = "op申请红字信息表编号-op确认申请-Response(纸质专用发票)(深圳航信纸质票)")
    @RequestMapping(value = "/opRedBitchLlq/response", method = RequestMethod.POST)
    @ResponseBody
    public R<String> opRedBitchLlqResponse(@RequestBody SzhtxxInvoiceFptxxOpSingleBillingForm form) {

        form.setFormState(CommonFormStateEnum.提交);

        try {
            InvoiceApply invoiceApplyEntity = invoiceApplyCustomerDubboConsumerService.findByInvoiceApplySn(form.getFpqqlsh(), getToken());

            List<SzhtxxElectronicInvoiceFptxxListItemVo> resultList = szhtxxElectronicInvoiceFptxxDubboConsumerService.queryGenericParam(
                    SzhtxxElectronicInvoiceFptxxQueryCriteria
                            .builder()
                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
                            .build(),
                    getToken()
            );

            if (CollUtil.isEmpty(resultList)) {
                return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
            }

            SzhtxxElectronicInvoiceFptxxListItemVo szhtxxElectronicInvoiceFptxxListItemVo = resultList.get(0);

            SysNotify sysNotify = szhtxxPaperInvoiceFptxxDubboConsumerService.opRedBitchLlqResponse(
                    form,
                    szhtxxElectronicInvoiceFptxxListItemVo,
                    invoiceApplyEntity,
                    getToken()
            );

            if (sysNotify.getTitle().equals(SzhtxxElectronicInvoiceResponseCodeEnum.SUCCESS.getReturnCode())) {
                return ResponseResultOuterUtils.createSuccesResult(sysNotify.getContent());
            } else {
                return ResponseResultOuterUtils.createErrorResult("500", sysNotify.getContent());
            }

        } catch (Exception e) {

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();

            return ResponseResultOuterUtils.createErrorResult("500", ResponseMsgConstants.ERROR_UNKNOW);
        }
    }

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

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


    @ApiOperation(value = "op下载红字信息表编号-Request(纸质专用发票)(深圳航信纸质票)")
    @RequestMapping(value = "/opRedLowerWorkLlq/request", method = RequestMethod.POST)
    @ResponseBody
    public R<SzhtxxPaperInvoiceFptxxopRedLowerWorkLlqVo> opRedLowerWorkLlqRequest(@RequestBody SzhtxxInvoiceFptxxOpRedLowerWorkLlqForm form) {

        R<SzhtxxPaperInvoiceFptxxopRedLowerWorkLlqVo> result = new R<>();

        form.setFormState(CommonFormStateEnum.预览);

        try {


//            /******************************************** 初始化 start ********************************************/
//
//            InvoiceApply entity = invoiceApplyCustomerDubboConsumerService.findByInvoiceApplySn(form.getFpqqlsh(), getToken());
//
//            List<SzhtxxElectronicInvoiceFptxxListItemVo> resultList = szhtxxElectronicInvoiceFptxxDubboConsumerService.queryGenericParam(
//                    SzhtxxElectronicInvoiceFptxxQueryCriteria.builder()
//                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
//                            .build(),
//                    getToken()
//            );
//
//            if (CollUtil.isEmpty(resultList)) {
//                return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
//            }
//
//            SzhtxxElectronicInvoiceFptxxListItemVo fptxxListItemVo = resultList.get(0);
//
//            /******************************************** 初始化   end ********************************************/
//
//            /**************************************** 蓝票主体 start ****************************************/
//
//            SzhtxxElectronicInvoiceFptxxDetailVo fptxxOrigin = szhtxxElectronicInvoiceFptxxDubboConsumerService.detailGenericParamSzhtxxElectronicInvoiceFptxx(
//                    SzhtxxElectronicInvoiceFptxxQueryCriteria.builder()
//                            .fpqqlsh(form.getFpqqlsh())
//                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
//                            .build(),
//                    getToken()
//            );
//
//            /**************************************** 蓝票主体 start ****************************************/


            /******************************************** 红票主体 start ********************************************/

            SID20BitchLlqRequestBody sid20BitchLlqRequestBody = szhtxxPaperInvoiceFptxxDubboConsumerService.opRedLowerWorkLlqRequest(
                    form,
                    getToken()
            );

            /******************************************** 红票主体   end ********************************************/

            result.setSuccess(true);
            result.setData(SzhtxxPaperInvoiceFptxxopRedLowerWorkLlqVo
                    .builder()
                    .sid20BitchLlqRequestBody(sid20BitchLlqRequestBody.dataID0201().shell().packing())
                    .build());

        } catch (Exception e) {

            result.setSuccess(false);
            result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return result;
    }

    @ApiOperation(value = "op下载红字信息表编号-op确认下载-Response(纸质专用发票)(深圳航信纸质票)")
    @RequestMapping(value = "/opRedLowerWorkLlq/response", method = RequestMethod.POST)
    @ResponseBody
    public R<String> opRedLowerWorkLlqResponse(@RequestBody SzhtxxInvoiceFptxxOpRedLowerWorkLlqForm form) {

        form.setFormState(CommonFormStateEnum.提交);

        try {
//            InvoiceApply invoiceApplyEntity = invoiceApplyCustomerDubboConsumerService.findByInvoiceApplySn(form.getFpqqlsh(), getToken());
//
//            List<SzhtxxElectronicInvoiceFptxxListItemVo> resultList = szhtxxElectronicInvoiceFptxxDubboConsumerService.queryGenericParam(
//                    SzhtxxElectronicInvoiceFptxxQueryCriteria
//                            .builder()
//                            .szhtxxElectronicInvoiceFptxxId(form.getSzhtxxElectronicInvoiceFptxxId())
//                            .build(),
//                    getToken()
//            );
//
//            if (CollUtil.isEmpty(resultList)) {
//                return ResponseResultOuterUtils.createErrorResult("500", "未查找到相关的信息");
//            }
//
//            SzhtxxElectronicInvoiceFptxxListItemVo szhtxxElectronicInvoiceFptxxListItemVo = resultList.get(0);
//
            SysNotify sysNotify = szhtxxPaperInvoiceFptxxDubboConsumerService.opRedLowerWorkLlqResponse(
                    form,
                    getToken()
            );

            if (sysNotify.getTitle().equals(SzhtxxElectronicInvoiceResponseCodeEnum.SUCCESS.getReturnCode())) {
                return ResponseResultOuterUtils.createSuccesResult(sysNotify.getContent());
            } else {
                return ResponseResultOuterUtils.createErrorResult("500", sysNotify.getContent());
            }

//            return ResponseResultOuterUtils.createSuccesResult();

        } catch (Exception e) {

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();

            return ResponseResultOuterUtils.createErrorResult("500", ResponseMsgConstants.ERROR_UNKNOW);
        }
    }

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


}
