<template>
  <div id="invoice_red_letter_edit" class="body" v-loading="load" element-loading-text="开具中，请稍等">
    <div class="body" v-loading="specialStatus" :element-loading-text="specialMessage" element-loading-spinner="22">
      <div class="invoice_print">
        <div class="flex: 1">
          <el-radio-group class="invoice_radio" v-model="taxIncluded" v-on:change="taxIncludedState">
            <el-radio-button label="含税"></el-radio-button>
            <el-radio-button label="不含税"></el-radio-button>
          </el-radio-group>
          <el-radio-group class="invoice_radio" v-model="detailed" v-on:change="detailedState">
            <el-radio-button label="明细"></el-radio-button>
            <el-radio-button label="清单"></el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button class="invoice_button" type="primary" v-on:click="submitInvoice(false)">
            保存
          </el-button>
          <el-button class="invoice_button" type="primary" v-on:click="submitInvoice(true)">
            提交
          </el-button>
        </div>
      </div>
      <div class="invoice_print">
        <div>
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="addDomain"
          >新增行
          </el-button>
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="removeDomain"
          >删除行
          </el-button>
        </div>
      </div>
<!--      <div>-->
<!--        <span>开票日期：</span>-->
<!--      </div>-->
      <div style="margin-top:20px">
        <keep-alive>
          <div id="invoice-container" class="invoice">
            <ul class="pointGroup">
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
            </ul>
            <div class="invoiceMain" style="min-height: 621px">
              <div class="invoice-body">
                <div data-v-ab32345e class="grid-hf">
                  <div data-v-ab32345e class="grid-hf-col col-a">
                    购买单位
                  </div>
                  <div data-v-ab32345e class="grid-hf-col col-b roll-height" style="width: 50%">
                    <ul data-v-ab32345e class="trader">
                      <li data-v-ab32345e>
                        <span data-v-ab32345e class="label">名称</span>：
                        <div data-v-ab32345e style="display: inline-block;width: 52.5%;margin-left: 1px;">
                          <div data-v-ab32345e
                               class="ivu-auto-complete input name ivu-select ivu-select-single ivu-select-default"
                               remote
                               type="text">
                            <div tabindex="-1" class>
                              <div class="ivu-input-wrapper ivu-input-wrapper-default ivu-input-type">
                                <i class="ivu-icon ivu-icon-ios-loading ivu-load-loop ivu-input-icon ivu-input-icon-validate"></i>
                                <span>{{ buyerName }}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </li>
                      <li data-v-ab32345e>
                        <span data-v-ab32345e class="label" style="width: 20%">纳税人识别号</span>：
                        <span>{{ buyerTaxNumber }}</span>
                      </li>
                    </ul>
                  </div>
                  <div data-v-ab32345e class="grid-hf-col col-a">销货单位</div>
                  <div data-v-ab32345e class="grid-hf-col col-d last" style="text-align: left">
                    <ul data-v-ab32345e class="trader">
                      <li data-v-ab32345e>
                        <span data-v-ab32345e class="label">名称</span>：
                        <div data-v-ab32345e style="display: inline-block;width: 70%;margin-left: 1px;">
                          <div data-v-ab32345e
                               class="ivu-auto-complete input name ivu-select ivu-select-single ivu-select-default"
                               remote
                               type="text"
                          >
                            <div tabindex="-1" class>
                              <div class="ivu-input-wrapper ivu-input-wrapper-default ivu-input-type">
                                <i class="ivu-icon ivu-icon-ios-loading ivu-load-loop ivu-input-icon ivu-input-icon-validate"></i>
                                <span>{{ sellerName }}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </li>
                      <li data-v-ab32345e>
                        <span data-v-ab32345e class="label" style="width: 30%">纳税人识别号</span>：
                        {{ sellerTaxNumber }}
                      </li>
                    </ul>
                  </div>
                </div>
                <div class="grid-list">
                  <div class="grid-list-main">
                    <div class="grid-list-head">
                      <div class="grid-list-col col-index" style="height: 31px">
                        行号
                      </div>
                      <div class="grid-list-col col-index" style="height: 31px" v-if="checkShow">
                        <el-checkbox :indeterminate="isIndeterminate"
                                     v-model="productCheckAll"
                                     v-on:change="productCheckAllChange"
                        ></el-checkbox>
                      </div>
                      <div class="grid-list-col col-a" style="height: 31px" v-if="isDetailed == false">
                        <span>货物或应税劳务.服务名称</span>
                      </div>
                      <div class="grid-list-col col-a" style="height: 31px" v-if="isDetailed == true">
                        <span class="fontColor: red">(清单)</span>货物或应税劳务.服务名称
                      </div>
                      <div class="grid-list-col col-b" style="height: 31px">
                        规格型号
                      </div>
                      <div class="grid-list-col col-c" style="height: 31px">
                        单位
                      </div>
                      <div class="grid-list-col col-d" style="height: 31px">
                        数 量
                      </div>
                      <div class="grid-list-col col-e" style="height: 31px" v-if="isTaxIncluded == false">
                        单价<span>(不含税)</span>
                      </div>
                      <div class="grid-list-col col-e" style="height: 31px" v-if="isTaxIncluded == true">
                        单价<span class="fontColor: red">(含税)</span>
                      </div>
                      <div class="grid-list-col col-f" style="height: 31px" v-if="isTaxIncluded == false">
                        金额<span>(不含税)</span>
                      </div>
                      <div class="grid-list-col col-f" style="height: 31px" v-if="isTaxIncluded == true">
                        金额<span class="fontColor: red">(含税)</span>
                      </div>
                      <div class="grid-list-col col-g" style="height: 31px">
                        税率
                      </div>
                      <div class="grid-list-col col-h col-i tax" style="height: 31px">
                        税 额
                      </div>
                      <div class="grid-list-col col-j last"></div>
                    </div>
                    <el-form :model="productData" ref="dynamicValidateForm" class="from-item">
                      <div class="grid-list-body">
                        <div class="grid-list-body-outline">
                          <div class="grid-list-col col-index"></div>
                          <div class="grid-list-col col-index" v-if="checkShow"></div>
                          <div class="grid-list-col col-a"></div>
                          <div class="grid-list-col col-b"></div>
                          <div class="grid-list-col col-c"></div>
                          <div class="grid-list-col col-d"></div>
                          <div class="grid-list-col col-e"></div>
                          <div class="grid-list-col col-f"></div>
                          <div class="grid-list-col col-g"></div>
                          <div class="grid-list-col col-h col-i tax"></div>
                          <div class="grid-list-col col-j last"></div>
                        </div>
                        <div class="grid-list-body-data">
                          <div class="grid-list-item" v-bind:key="index" v-for="(domain,index) in productData.product">
                            <div class="grid-list-col col-index">
                              {{ index + 1 }}
                            </div>
                            <div class="grid-list-col col-index" v-if="checkShow">
                              <el-checkbox
                                  v-bind:key="index "
                                  v-model="domain.productCheck"
                                  v-on:change="productCheckChange"
                              ></el-checkbox>
                            </div>
                            <div class="grid-list-col col-a">
                              <div style="display: inline-block;width: 85%;">
                                <div class="ivu-auto-complete name ivu-select ivu-select-single ivu-select-default"
                                     remote
                                     type="text">
                                  <div tabindex="-1" class>
                                    <div class="ivu-input-wrapper ivu-input-wrapper-default ivu-input-type ground">
                                      <i class="ivu-icon ivu-icon-ios-loading ivu-load-loop ivu-input-icon ivu-input-icon-validate"
                                      ></i>
                                      <input
                                          autocomplete="off"
                                          spellcheck="false"
                                          type="text"
                                          placeholder
                                          readonly="readonly"
                                          v-model="domain.productName"
                                          class="ivu-input ivu-input-default"
                                      />
                                    </div>
                                  </div>
                                </div>
                              </div>
                              <span
                                  class="selector ellipsis skin-background"
                                  v-on:click="selectCommodity(index)"
                              >...</span
                              >
                            </div>
                            <div class="grid-list-col col-b">
                              <input type="text" class="input" v-model="domain.specification"/>
                            </div>
                            <div class="grid-list-col col-c">
                              <input type="text"
                                     readonly="readonly"
                                     class="input"
                                     v-model="domain.units"
                              />
                            </div>
                            <div class="grid-list-col col-d">
                              <div data-v-33b11dca class>
                                <input
                                    data-v-33b11dca
                                    type="text"
                                    autocomplete="off"
                                    class="input"
                                    v-model="domain.number"
                                    v-on:change="numberChange(index)"
                                />
                              </div>
                            </div>
                            <div class="grid-list-col col-e">
                              <div data-v-33b11dca class>
                                <input
                                    data-v-33b11dca
                                    type="text"
                                    autocomplete="off"
                                    class="input"
                                    v-model="domain.price"
                                    v-on:change=" priceChange(index)"
                                />
                              </div>
                            </div>
                            <div class="grid-list-col col-f">
                              <div data-v-33b11dca class>
                                <input
                                    data-v-33b11dca
                                    type="text"
                                    autocomplete="off"
                                    class="input"
                                    v-model="domain.amount"
                                    v-on:change="amountChange(index)"
                                />
                              </div>
                            </div>
                            <div class="grid-list-col col-g" v-if="domain.preferentialFlag !== 1">
                              <select class style="width: 96%;"
                                      v-model="domain.taxRate"
                                      v-on:change="rateChange($event,index)"
                              >
                                <option :value="value"
                                        v-bind:key="row"
                                        v-for="(value,row) in domain.taxRates"
                                >
                                  {{ value * 100 }}%
                                </option>
                              </select>
                            </div>
                            <div class="grid-list-col col-g" v-if="domain.preferentialFlag === 1">
                              <input
                                  type="text"
                                  class="input"
                                  v-model="domain.preferentialType"
                                  :disabled="true"
                                  :title="domain.preferentialType"
                              />
                            </div>
                            <div class="grid-list-col col-h col-i tax">
                              <input
                                  type="text"
                                  readonly="readonly"
                                  class="input"
                                  v-model="domain.taxAmount"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-form>
                    <div class="grid-list-foot">
                      <div
                          class="grid-list-col col-a sum"
                      >
                        合计
                      </div>
                      <div class="grid-list-col col-b">
                        &nbsp;
                      </div>
                      <div class="grid-list-col col-c">
                        &nbsp;
                      </div>
                      <div class="grid-list-col col-d">
                        &nbsp;
                      </div>
                      <div class="grid-list-col col-e">
                        &nbsp;
                      </div>
                      <div class="grid-list-col col-f">
                        ￥
                        <span>{{ totalAmountRate }}</span>
                      </div>
                      <div
                          class="grid-list-col col-g"
                      ></div>
                      <div class="grid-list-col col-h">
                        ￥{{ totalTaxAmount }}
                      </div>
                      <div class="grid-list-col col-i">
                        &nbsp;
                      </div>
                      <div
                          class="grid-list-col col-j last"
                      >
                        &nbsp;
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <p style="font-weight: bold">其它说明信息</p>
                <div style="display: flex">
                  <div>
                    <span>【{{sellerType}}】</span>
                  </div>
                  <div>
                    <p v-if="this.status === 1">对应蓝字专用发票抵扣增值税销项税额情况:{{deductionFont}}</p>
                    <span v-if="this.deduction === false || this.status === 2">对应蓝字专用发票密码区内打印的发票信息：</span>
                  </div>
                </div>
                <div style="display: flex; flex-direction: column" v-if="this.deduction === false || this.status === 2">
                  <span>发票代码：{{ invoiceCode }}</span>
                  <span>发票号码：{{ invoiceNumber }}</span>
                  <span>发票类型：{{ invoiceTypeName }}</span>
                </div>

                <div style="display: flex;margin-bottom: 10px;margin-top: 10px">
                  <span><span style="color: red">*</span>联系电话：</span>
                  <el-input
                      v-model="contactNumber"
                      placeholder="请输入联系电话"
                      class="invoice_input"
                  ></el-input>
                </div>
                <div style="display: flex">
                  <span><span style="color: red">*</span>申请理由：</span>
                  <el-input
                      type="textarea"
                      :rows="2"
                      placeholder="请输入申请理由"
                      v-model="explain"
                      class="invoice_text">
                  </el-input>
                </div>
              </div>
            </div>
            <ul class="pointGroup">
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
            </ul>
          </div>
        </keep-alive>
      </div>
      <el-dialog title="选择客户信息" :visible.sync="isCustomer" :append-to-body="true">
        <div>
          <!-- <el-input placeholder="" v-model="queryTaxId" class="invoice_input">
<template slot="prepend">企业税号</template>
          </el-input>-->
          <el-input
              placeholder
              v-model="queryTaxName"
              class="invoice_input"
          >
            <template slot="prepend">客户名称</template>
          </el-input>
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="customerQuery"
          >查询
          </el-button
          >
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="addBuyer()"
          >新增
          </el-button
          >
        </div>
        <el-table
            :data="customerData"
            height="250px"
            style="width: 100%"
            highlight-current-row
            border
            @row-dblclick="selectCustomerData"
            @row-click="setCustomerInfo"
        >
          <el-table-column
              prop="customerEntTaxId"
              label="企业税号"
              width="180"
          ></el-table-column>
          <el-table-column
              prop="customerName"
              label="客户名称"
              width="180"
          ></el-table-column>
          <el-table-column
              prop="customerMobile"
              label="客户手机号"
              width="100"
          ></el-table-column>
          <el-table-column
              prop="address"
              label="客户地址"
              width="160"
          ></el-table-column>
          <el-table-column
              prop="contactPhone"
              label="联系电话"
              width="100"
          ></el-table-column>
          <el-table-column
              prop="bankName"
              label="开户银行"
              width="120"
          ></el-table-column>
          <el-table-column
              prop="bankAccountNumber"
              label="银行账户"
              width="120"
          ></el-table-column>
        </el-table>
        <div slot="footer" class="customer">
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="selectCustomerButton"
          >确 定
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择产品信息" :visible.sync="isCommodity" :append-to-body="true"
                 v-on:opened="productPageOpen" v-on:closed="productPageClose">
        <div>
          <el-input
              placeholder
              v-model="queryProductName"
              class="invoice_input"
          >
            <template slot="prepend">产品名称</template>
          </el-input>
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="productQuery"
          >查询
          </el-button
          >
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="addCommodity()"
          >新增
          </el-button
          >
        </div>
        <el-table
            :data="productList"
            height="250px"
            style="width: 100%"
            highlight-current-row
            border
            @row-dblclick="selectProductData"
            @row-click="setProductInfo"
        >
          <el-table-column
              prop="taxationCateCode"
              label="税收分类编码"
              width="180"
          ></el-table-column>
          <el-table-column
              prop="taxationCateAbbr"
              label="税收分类简称"
              width="180"
          ></el-table-column>
          <el-table-column
              prop="productName"
              label="产品名称"
              width="180"
          ></el-table-column>
          <el-table-column
              prop="productCode"
              label="商品编码"
              width="120"
          ></el-table-column>
          <el-table-column
              prop="specsModel"
              label="规格型号"
              width="100"
          ></el-table-column>
          <el-table-column
              prop="price"
              label="单价"
              width="60"
          ></el-table-column>
          <el-table-column
              prop="unit"
              label="计量单位"
              width="80"
          ></el-table-column>
          <el-table-column
              prop="taxRate"
              label="税率"
              width="60"
          ></el-table-column>
          <el-table-column
              prop="taxRates"
              label="可用税率"
              width="180"
          ></el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="120"
          >
            <template slot-scope="scope">
              <el-button
                  @click="editCommodity(scope.row)"
                  type="primary"
                  size="small"
              >编辑
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
              @current-change="productPageChange"
              :page-size="10"
              layout="total, prev, pager, next"
              :total="totalNumber"
          ></el-pagination>
        </div>
        <div slot="footer" class="customer">
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="selectProductButton"
          >确 定
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="新增购方信息" :visible.sync="customerAddData.dialogVisible" center
                 @close="handleCloseDialog('customerAdd')" :append-to-body="true"
      >
        <buyer_info_add
            ref="customerAdd"
            :inputCustomerInfo="customerAddData.inputCustomerInfo"
        ></buyer_info_add>
        <span slot="footer">
                    <el-button
                        type="primary"
                        @click="handleCustomerModifyOrAddSubmit('customerAdd')"
                    >立即添加</el-button
                    >
                    <el-button @click="customerAddData.dialogVisible = false"
                    >取 消</el-button
                    >
                </span>
      </el-dialog>
      <el-dialog title="商品信息" :visible.sync="productAddData.productAddShow" center :append-to-body="true"
                 @close="handleCloseDialog('productAddForm')">
        <product_info_add ref="productAddForm" :inputProductInfo="productAddData.inputProductInfo"></product_info_add>
        <span slot="footer">
          <el-button type="primary" @click="handleProductModifyOrAddSubmit('productAddForm')">立即添加</el-button>
          <el-button @click="productAddData.productAddShow = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-dialog title="商品列表" :visible.sync="isShowProduct" v-on:opened="productListPageOpen"
                 v-on:closed="productListPageClose" :append-to-body="true"
                 width="70%">
        <product_list ref="productList" :productList="this"/>
        <div slot="footer" class="customer">
          <el-button
              class="invoice_button"
              type="primary"
              v-on:click="isShowProduct = false"
          >取 消
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import '@/utils/css/54.bdcd03887ce3138b0f6f.css'
import '@/utils/css/vendors_cloud.5d0cbba7097d23ee8c5f.css'
import '@/utils/css/cloud.28e91b0965c466baef7a.css'
import '@/utils/54.83af1a94df1e7e208022'
import cache from '@/utils/cache'
import {AxiosRequestData} from '@/data/axios_request'
import {
  ProductListCalculation,
  InvoiceTotalAmount,
  ProductTaxRateSwitch,
  InvoiceReopen, InvoiceProducts, RedLetterInfoProduct
} from '@/data/invoice_calculation'
import BuyerInfo from './buyer_info_add'
import ProductInfo from './product_info_add'
import {customerModifyOrAdd, productModifyOrAdd} from '@/api/user_config'
import ProductList from './product_list'
import {timeCompare} from '@/utils/time_handle'

export default {
  name: 'invoice_red_letter_edit',
  components: {
    buyer_info_add: BuyerInfo,
    product_info_add: ProductInfo,
    product_list: ProductList
  },
  data() {
    return {
      status: 1, // 1：购买方申请 2：销货方申请
      load: false,
      account: '',
      token: '',
      pageNum: 1,
      pageSize: 10,
      numericalValue: '正数',
      taxation: '普通征税',
      taxIncluded: '不含税',
      detailed: '明细',
      purchaserName: '',
      buyerName: '',
      buyerTaxNumber: '',
      sellerName: '',
      sellerTaxNumber: '',
      taxNumber: '',
      addressPhone: '',
      openingBank: '',
      sellerAddress: '',
      sellerPhone: '',
      sellerBankName: '',
      sellerBankAccountNumber: '',
      purchaserNameTemporary: '',
      taxNumberTemporary: '',
      addressPhoneTemporary: '',
      openingBankTemporary: '',
      payees: "", // 收款人
      reviewers: "", // 复核人
      payeesList: [],
      reviewersList: [],
      remark: "",
      totalPage: 0,
      totalNumber: 0,
      selectIndex: -1,
      isIndeterminate: false,
      productCheckAll: false,
      productData: {
        product: [
          {
            productCheck: false,
            productName: "",
            productCode: "",
            specification: "",
            units: "",
            number: "",
            price: "",
            amount: "",
            taxRate: "",
            taxAmount: "",
            taxRates: "",
            totalAmountRate: "",
            preferentialFlag: 0,
            preferentialType: "",
            zeroRateFlag: null,
            rowStatus: 0, // 0表示正常行，1表示被折扣行，2表示折扣行，3表示开票成功展示数据, 4表示产品有优惠政策或者零税率，税率和税额不可修改
          },
        ],
      },
      billingName: "",
      billingTaxId: "",
      billingAddress: "",
      billingBank: "",
      productList: [],
      isCustomer: false,
      isCommodity: false,
      queryProductName: "",
      productRowInfo: {},
      customerData: [],
      queryTaxName: "",
      pageCustomerNum: 1,
      pageCustomerSize: 10,
      totalAmount: 0.0,
      totalTaxAmount: 0.0,
      totalAmountRate: 0.0,
      capitalizedAmount: "",
      rates: "",
      isTaxIncluded: false,
      isDetailed: false,
      invoiceReqFlowNo: "",
      nowTime: "",
      specialStatus: false,
      specialMessage: "",
      entTaxId: "",
      isDiscount: false,
      originalAmount: "",
      selectDiscount: -1,
      discountTotalRate: 0.0,
      timerRequestNum: 1,
      timer: "",
      buyerTimer: "",
      orderId: "",
      invoiceType: null,
      machineNo: "",
      invoiceCheckCode: "",
      taxControlCode: "",
      isShow: false,
      discountRowNumber: 1,
      buyerData: [],
      blurTimer: "",
      customerAddData: {
        dialogVisible: false,
        inputCustomerInfo: {}, // 绑定后，用于清空上次的输入
      },
      productAddData: {
        productAddShow: false,
        inputProductInfo: {}, // 绑定后，用于清空上次的输入
      },
      isShowInvoiceCopy: false,
      searchInvoiceType: 4, // 发票种类 1.增值税普通电子发票   2.增值税电子专用发票  3.增值税普通纸质发票  4 增值税专用纸质发票
      isInvoiceInfo: false,
      invoiceAmount: {
        monthPupiaoTotal: 0,
        monthTotal: 0,
        monthZhuanpiaoTotal: 0,
        quarterPupiaoTotal: 0,
        quarterTotal: 0,
        quarterZhuanpiaoTotal: 0,
      },
      checkShow: true,
      expirationTime: '',
      isShowProduct: false,
      isShowSplit: false,
      isSplit: false,
      defaultDeviceInfo: {},
      invoiceSplitList: [],
      isClose: true,
      contactNumber: '',
      explain: '',
      testShow: false,
      invoiceCode: '',
      invoiceNumber: '',
      invoiceDate: '',
      printObj: {
        id: '#printTest', // 这里是要打印元素的ID
        popTitle: "", // 打印的标题
        extraCss: "", // 打印可引入外部的一个 css 文件
        extraHead: "", // 打印头部文字
      },
      buyer: null,
      deduction: false,
      requestId: '',
      sellerType: '',
      deductionFont: '未抵扣',
      invoiceTypeName: '',
      isRedInvoice: true
    }
  },
  methods: {
    // 点击空白处隐藏购方信息查询列表
    showBlur() {
      this.blurTimer = setTimeout(() => {
        this.isShow = false;
        clearInterval(this.blurTimer);
      }, 300);
    },
    // 产品分页查询
    productPageChange(page) {
      this.pageNum = page;
      this.getProductData();
    },
    // 产品查询
    productQuery() {
      this.pageNum = 1;
      this.getProductData();
    },
    // 客户信息查询
    customerQuery() {
      this.pageCustomerNum = 1;
      this.getCustomerData();
    },
    // 添加产品列表
    addDomain() {
      this.productData.product.push({
        key: Date.now(),
        productCheck: false,
        productName: "",
        productCode: "",
        specification: "",
        units: "",
        number: "",
        price: "",
        amount: "",
        taxRate: "",
        taxAmount: "",
        totalAmountRate: "",
        rowStatus: 0,
      });
      if (this.productData.product.length === 9) {
        this.isDetailed = true;
        this.detailed = "清单";
        this.$message({
          message:
              "超过8行明细将必须使用清单打印,票面将只显示（详见销货清单）和折扣!",
          type: "warning",
        });
      }
      if (this.productCheckAll) {
        this.isIndeterminate = true;
        this.productCheckAll = false;
      }
    },
    // 删除产品列表
    removeDomain() {
      let productRows = 0;
      for (let i = 0; i < this.productData.product.length; i++) {
        if (this.productData.product[i].rowStatus === 1) {
          if (this.productData.product[i].productCheck) {
            productRows++;
            if (!this.productData.product[i + 1].productCheck) {
              this.$message({
                message:
                    "选择被折扣行时请同时选择折扣行再进行删除！",
                type: "warning",
              });
              return;
            }
          }
        } else {
          if (this.productData.product[i].productCheck) {
            productRows++;
          }
        }
      }
      if (productRows <= 0) {
        this.$message({
          message: "请选择需要删除的信息！",
          type: "warning",
        });
        return;
      }
      this.$confirm("确定删除选中行的信息吗？")
          .then((_) => {
            for (let i = 0; i < this.productData.product.length; i++) {
              if (this.productData.product[i].productCheck === true) {
                if (this.productData.product[i].rowStatus === 2) {
                  if (i > 0) {
                    if (
                        this.productData.product[i - 1]
                            .rowStatus === 1
                    ) {
                      this.productData.product[
                      i - 1
                          ].rowStatus = 0;
                    }
                  }
                  this.productData.product.splice(i, 1);
                } else {
                  this.productData.product.splice(i, 1);
                }
                i--;
              }
            }
            this.isIndeterminate = false;
            if (
                this.productData.product.length === 8 ||
                this.productData.product.length < 8
            ) {
              this.isDetailed = false;
              this.detailed = "明细";
            }
            this.calculationTotalAmount(this.productData.product);
            this.productCheckChange(false);
          })
          .catch((_) => {
          });
    },
    // 显示选择购方信息页面
    selectCustomer() {
      this.getCustomerData();
      this.isCustomer = true;
    },
    // 显示选择产品信息页面
    selectCommodity(rowNumber) {
      this.selectIndex = rowNumber;
      this.isCommodity = true;
    },
    // 设置开票成功后产品列表状态
    productPrintList() {
      this.productData.product.map((_, i) => {
        this.productData.product[i].rowStatus = 3;
      });
    },
    // 获取产品列表数据
    async getProductData() {
      if (this.account) {
        const url = "/sys/product/findPage";
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              productName: this.queryProductName,
              mobile: this.account,
              reqChannel: 4,
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              entTaxId: this.billingTaxId,
            },
            false,
            2
        );
        if (response) {
          if (response.code === 0) {
            this.totalNumber = response.data.total;
            this.totalPage = response.data.pages;
            if (response.data.records.length > 0) {
              let rates = "";
              let productList = [];
              for (
                  let i = 0;
                  i < response.data.records.length;
                  i++
              ) {
                const url = "/sys/entInfo/rates";
                let res = await AxiosRequestData(
                    url,
                    this.token,
                    {
                      entTaxId: this.billingTaxId,
                      taxCateCode:
                      response.data.records[i]
                          .taxationCateCode,
                    },
                    false,
                    2
                );
                if (res) {
                  let rate = response.data.records[
                      i
                      ].taxRate.toString();
                  if (res.code === 0) {
                    if (res.data.length > 0) {
                      for (
                          let i = 0;
                          i < res.data.length;
                          i++
                      ) {
                        if (
                            rate.indexOf(
                                res.data[i].toString()
                            ) == -1
                        ) {
                          rate =
                              rate +
                              "," +
                              res.data[i];
                        }
                      }
                    }
                    rates = rate;
                  } else {
                    rates = rate;
                  }
                }
                let list = {
                  productId:
                  response.data.records[i].productId,
                  productName:
                  response.data.records[i].productName,
                  productCode:
                  response.data.records[i].productCode,
                  parentCode:
                  response.data.records[i].parentCode,
                  taxItem: response.data.records[i].taxItem,
                  shortCode:
                  response.data.records[i].shortCode,
                  taxRate: response.data.records[i].taxRate,
                  specsModel:
                  response.data.records[i].specsModel,
                  price:
                      response.data.records[i].price ==
                      null ||
                      response.data.records[i].price == ""
                          ? ""
                          : response.data.records[i].price,
                  unit: response.data.records[i].unit,
                  taxPriceFlag:
                  response.data.records[i].taxPriceFlag,
                  hiddenFlag:
                  response.data.records[i].hiddenFlag,
                  taxationCateCode:
                  response.data.records[i]
                      .taxationCateCode,
                  taxationCateName:
                  response.data.records[i]
                      .taxationCateName,
                  taxationCateAbbr:
                  response.data.records[i]
                      .taxationCateAbbr,
                  preferentialFlag:
                  response.data.records[i]
                      .preferentialFlag,
                  preferentialType:
                  response.data.records[i]
                      .preferentialType,
                  zeroRateFlag:
                  response.data.records[i].zeroRateFlag,
                  taxSpeManage:
                  response.data.records[i].taxSpeManage,
                  manageUserId:
                  response.data.records[i].manageUserId,
                  entName: response.data.records[i].entName,
                  entTaxId: response.data.records[i].entTaxId,
                  taxRates: rates,
                };
                productList = productList.concat(list);
              }
              this.productList = productList;
            }
          }
        }
      }
    },
    // 获取产品的可用税率
    async getCompanyTaxRate(code) {
      if (this.account) {
        const url = "/sys/entInfo/rates";
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              entTaxId: this.billingTaxId,
              taxCateCode: code,
            },
            false,
            2
        );
        if (response) {
          let rate = "";
          if (response.code === 0) {
            if (response.data.length > 0) {
              for (let i = 0; i < response.data.length; i++) {
                rate = rate + "," + response.data[i];
              }
              rate = rate.substring(1, rate.length);
            }
            this.rates = rate;
          } else {
            this.rates = rate;
          }
        }
      }
    },
    // 获取客户信息
    async getCustomerData() {
      if (this.account) {
        const url = "/sys/customer/customerSearch";
        let args = {
          customerName: this.queryTaxName,
          entTaxId: this.entTaxId,
          reqChannel: 4,
        };
        let response = await AxiosRequestData(
            url,
            this.token,
            args,
            false,
            2
        );
        if (response) {
          if (response.code === 0) {
            this.customerData = response.data;
          } else {
            this.$message.error(response.msg);
          }
        }
      }
    },
    // 双击选择产品信息
    selectProductData(row, event, column) {
      this.productData.product[this.selectIndex].productName =
          "*" + row.taxationCateAbbr + "*" + row.productName;
      this.productData.product[this.selectIndex].productCode =
          row.taxationCateCode;
      this.productData.product[this.selectIndex].specification =
          row.specsModel;
      this.productData.product[this.selectIndex].units = row.unit;
      this.productData.product[this.selectIndex].price = row.price;
      this.productData.product[this.selectIndex].taxRate = row.taxRate;
      if (row.taxRates.length > 0) {
        this.productData.product[
            this.selectIndex
            ].taxRates = row.taxRates.split(",");
      }
      this.productData.product[this.selectIndex].number = "";
      this.productData.product[this.selectIndex].amount = "";
      this.productData.product[this.selectIndex].taxAmount = "";
      if (row.preferentialFlag === 1 || row.zeroRateFlag != null) {
        this.productData.product[this.selectIndex].rowStatus = 4;
      } else {
        this.productData.product[this.selectIndex].rowStatus = 0;
      }
      this.productData.product[this.selectIndex].preferentialFlag =
          row.preferentialFlag;
      this.productData.product[this.selectIndex].preferentialType =
          row.preferentialType;
      this.productData.product[this.selectIndex].zeroRateFlag =
          row.zeroRateFlag;
      this.isCommodity = false;
    },
    // 单击通过确认按钮选择产品信息
    setProductInfo(row, event, column) {
      this.productRowInfo = row;
    },
    // 产品选择确认
    selectProductButton() {
      this.productData.product[this.selectIndex].productName =
          "*" +
          this.productRowInfo.taxationCateAbbr +
          "*" +
          this.productRowInfo.productName;
      this.productData.product[
          this.selectIndex
          ].productCode = this.productRowInfo.taxationCateCode;
      this.productData.product[
          this.selectIndex
          ].specification = this.productRowInfo.specsModel;
      this.productData.product[
          this.selectIndex
          ].units = this.productRowInfo.unit;
      this.productData.product[
          this.selectIndex
          ].price = this.productRowInfo.price;
      this.productData.product[
          this.selectIndex
          ].taxRate = this.productRowInfo.taxRate;
      if (this.productRowInfo.taxRates.length > 0) {
        this.productData.product[
            this.selectIndex
            ].taxRates = this.productRowInfo.taxRates.split(",");
      }
      this.productData.product[this.selectIndex].number = "";
      this.productData.product[this.selectIndex].amount = "";
      this.productData.product[this.selectIndex].taxAmount = "";
      if (
          this.productRowInfo.preferentialFlag === 1 ||
          this.productRowInfo.zeroRateFlag != null
      ) {
        this.productData.product[this.selectIndex].rowStatus = 4;
      } else {
        this.productData.product[this.selectIndex].rowStatus = 0;
      }
      this.productData.product[
          this.selectIndex
          ].preferentialFlag = this.productRowInfo.preferentialFlag;
      this.productData.product[
          this.selectIndex
          ].preferentialType = this.productRowInfo.preferentialType;
      this.productData.product[
          this.selectIndex
          ].zeroRateFlag = this.productRowInfo.zeroRateFlag;
      this.isCommodity = false;
    },
    // 产品选择页面关闭
    productPageClose() {
    },
    // 产品选择页面打开
    productPageOpen() {
      let date = timeCompare(this.expirationTime)
      if (date.hour === 0 && date.minute <= 60) {
        this.getTokenStatus()
      }
      this.getProductData()
    },
    // 双击选择客户信息
    selectCustomerData(row, event, column) {
      if (this.buyer === 1) {
        this.sellerName = row.customerName
        this.sellerTaxNumber = row.customerEntTaxId
      } else {
        this.buyerName = row.customerName
        this.buyerTaxNumber = row.customerEntTaxId
      }
      // this.purchaserName = row.customerName;
      // this.taxNumber = row.customerEntTaxId;
      if (row.address != null) {
        if (row.contactPhone != null) {
          this.addressPhone = row.address + " " + row.contactPhone;
        } else {
          this.addressPhone = row.address;
        }
      } else {
        if (row.contactPhone != null) {
          this.addressPhone = row.contactPhone;
        } else {
          this.addressPhone = "";
        }
      }
      if (row.bankName != null) {
        if (row.bankAccountNumber != null) {
          this.openingBank =
              row.bankName + " " + row.bankAccountNumber;
        } else {
          this.openingBank = row.bankName;
        }
      } else {
        if (row.bankAccountNumber != null) {
          this.openingBank = row.bankAccountNumber;
        } else {
          this.openingBank = "";
        }
      }
      this.isCustomer = false;
      this.isShow = false;
    },
    // 单击通过确认按钮选择客户信息
    setCustomerInfo(row, event, column) {
      this.purchaserNameTemporary = row.customerName;
      this.taxNumberTemporary = row.customerEntTaxId;
      if (row.address != null) {
        if (row.contactPhone != null) {
          this.addressPhoneTemporary =
              row.address + " " + row.contactPhone;
        } else {
          this.addressPhoneTemporary = row.address;
        }
      } else {
        if (row.contactPhone != null) {
          this.addressPhoneTemporary = row.contactPhone;
        } else {
          this.addressPhoneTemporary = "";
        }
      }
      if (row.bankName != null) {
        if (row.bankAccountNumber != null) {
          this.openingBankTemporary =
              row.bankName + " " + row.bankAccountNumber;
        } else {
          this.openingBankTemporary = row.bankName;
        }
      } else {
        if (row.bankAccountNumber != null) {
          this.openingBankTemporary = row.bankAccountNumber;
        } else {
          this.openingBankTemporary = "";
        }
      }
    },
    // 客户选择确认
    selectCustomerButton() {
      if (this.buyer === 1) {
        this.sellerName = this.purchaserNameTemporary
        this.sellerTaxNumber = this.taxNumberTemporary
      } else {
        this.buyerName = this.purchaserNameTemporary
        this.buyerTaxNumber = this.taxNumberTemporary
      }
      // this.purchaserName = this.purchaserNameTemporary;
      // this.taxNumber = this.taxNumberTemporary;
      this.addressPhone = this.addressPhoneTemporary;
      this.openingBank = this.openingBankTemporary;
      this.isCustomer = false;
    },
    // 打印发票
    async printInvoice() {
      if (this.invoiceReqFlowNo) {
        window.location.href =
            'PrintAssist://{"Type":"PrintInvoice","reqFlowNo":"' +
            this.invoiceReqFlowNo +
            '","InvoiceType":"0","Token":"' +
            this.token +
            '"}';
      }
    },
    // 产品数量变化
    numberChange(rowId) {
      let products = ProductListCalculation(
          this.productData.product,
          this.isTaxIncluded,
          this.isRedInvoice
      );
      this.productData.product = products;
      this.calculationTotalAmount(products);
    },
    // 产品单价变化
    priceChange(rowId) {
      let products = ProductListCalculation(
          this.productData.product,
          this.isTaxIncluded,
          this.isRedInvoice
      );
      this.productData.product = products;
      this.calculationTotalAmount(products);
    },
    // 产品金额变化
    amountChange(rowId) {
      let products = ProductListCalculation(
          this.productData.product,
          this.isTaxIncluded,
          this.isRedInvoice
      );
      this.productData.product = products;
      this.calculationTotalAmount(products);
    },
    // 产品税率变化
    rateChange(value, row) {
      this.productData.product[row].taxRate = value.target.value;
      let products = ProductListCalculation(
          this.productData.product,
          this.isTaxIncluded,
          this.isRedInvoice
      );
      this.productData.product = products;
      this.calculationTotalAmount(products);
    },
    // 产品含税和不含税变化
    taxIncludedState() {
      this.isTaxIncluded = !this.isTaxIncluded;
      let products = ProductTaxRateSwitch(
          this.productData.product,
          this.isTaxIncluded,
          this.isRedInvoice
      );
      this.productData.product = products;
      this.calculationTotalAmount(products);
    },
    // 计算总金额和总折扣金额
    calculationTotalAmount(products) {
      let total = InvoiceTotalAmount(products, this.isTaxIncluded, this.isRedInvoice);
      this.totalAmount = total.totalAmount;
      this.totalTaxAmount = total.totalTaxRate;
      this.totalAmountRate = total.totalAmountRate;
      this.discountTotalRate = total.discountTotalRate;
    },
    // 清单和明细切换
    detailedState() {
      if (this.detailed === "明细") {
        if (this.productData.product.length > 8) {
          this.$message({
            message: "超过8行清单不允许转换为明细!",
            type: "warning",
          });
          this.detailed = "清单";
          return;
        }
      }
      this.isDetailed = !this.isDetailed;
    },
    // 显示打印页边距设置页面
    setMargins() {
      window.location.href = 'PrintAssist://{"Type":"set"}';
    },
    // 获取当前时间，格式：2012年12月12日
    TimeFormate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      };
      this.nowTime =
          date.year + "年" + date.month + "月" + date.date + "日";
    },
    // 清空信息
    clearInfo(state) {
      if (state) {
        this.purchaserName = "";
        this.taxNumber = "";
        this.addressPhone = "";
        this.openingBank = "";
        this.purchaserNameTemporary = "";
        this.taxNumberTemporary = "";
        this.addressPhoneTemporary = "";
        this.openingBankTemporary = "";
      }
      this.buyerName = ''
      this.buyerTaxNumber = ''
      this.sellerName = ''
      this.sellerTaxNumber = ''
      this.status = 0;
      this.load = false;
      this.pageNum = 1;
      this.pageSize = 10;
      this.numericalValue = "正数";
      this.taxation = "普通征税";
      this.taxIncluded = "不含税";
      this.detailed = "明细";
      this.remark = "";
      this.totalPage = 0;
      this.totalNumber = 0;
      this.selectIndex = -1;
      this.productData = {
        product: [
          {
            productCheck: false,
            productName: "",
            productCode: "",
            specification: "",
            units: "",
            number: "",
            price: "",
            amount: "",
            taxRate: "",
            taxAmount: "",
            taxRates: "",
            totalAmountRate: "",
            rowStatus: 0,
          },
        ],
      };
      this.queryProductName = "";
      this.productRowInfo = {};
      this.customerData = [];
      this.queryTaxName = "";
      this.pageCustomerNum = 1;
      this.pageCustomerSize = 10;
      this.totalAmount = 0.0;
      this.totalTaxAmount = 0.0;
      this.capitalizedAmount = "";
      this.rates = "";
      this.invoiceReqFlowNo = "";
      this.invoiceCode = "";
      this.invoiceNumber = "";
      this.originalAmount = "";
      this.selectDiscount = -1;
      this.discountTotalRate = 0.0;
      this.timer = "";
      this.orderId = "";
      this.invoiceType = "";
      this.machineNo = "";
      this.invoiceCheckCode = "";
      this.taxControlCode = "";
      this.discountRowNumber = 1;
      this.getProductData();
      this.checkShow = true;
    },
    // 新增购方信息
    addBuyer() {
      this.customerAddData.inputCustomerInfo = {};
      this.customerAddData.dialogVisible = true;
    },
    // 新增商品信息
    addCommodity() {
      this.productAddData.inputProductInfo = {};
      this.productAddData.productAddShow = true;
    },
    // 编辑商品
    editCommodity(row) {
      this.productAddData.inputProductInfo = {...row};
      this.productAddData.productAddShow = true;
    },
    // 销方信息变化触发事件
    buyerChange() {
      if (this.purchaserName.length > 0) {
        this.buyerTimer = setTimeout(() => {
          this.getBuyerInfo(this.purchaserName);
        }, 1000);
      }
    },
    // 查询销方信息
    async getBuyerInfo(taxName) {
      if (this.account) {
        const url = "/sys/customer/customerSearch";
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              customerName: taxName,
              entTaxId: this.billingTaxId,
              reqChannel: 4,
            },
            false,
            2
        );
        if (response) {
          if (response.code === 0) {
            this.buyerData = response.data;
            if (response.data.length > 0) {
              this.isShow = true;
              clearInterval(this.timer);
            } else {
              this.isShow = false;
            }
          }
        }
      }
    },
    // 新增购方信息
    handleCustomerModifyOrAddSubmit(refName) {
      console.log("客户修改和添加 参数：" + refName);
      this.$refs[refName]
          .getCustomerInfo()
          .then((val) => {
            let args = {
              customerId: val.customerId,
              customerType: val.customerType,
              customerName: val.customerName,
              customerMobile: val.customerMobile,
              email: val.email,
            };
            if (args.customerType === 2) {
              // 企业客户
              args.customerEntTaxId = val.customerEntTaxId;
              args.address = val.address;
              args.bankName = val.bankName;
              args.bankAccountNumber = val.bankAccountNumber;
              args.contactPhone = val.contactPhone;
            }
            customerModifyOrAdd(args)
                .then((val) => {
                  // 成功关闭弹窗
                  this.customerAddData.dialogVisible = false;
                  // this.customerModifyData.dialogVisible = false
                  this.getCustomerData();
                  this.$message({
                    message: "购方信息添加成功！",
                    type: "success",
                  });
                })
                .catch((err) => {
                  this.$message.error(err);
                });
          })
          .catch((err) => {
            this.$message.error(err);
          });
    },
    // 新增购方信息窗口关闭
    handleCloseDialog(refName) {
      // 取消验证提示
      this.$refs[refName].resetFormFields();
    },
    // 添加产品信息
    handleProductModifyOrAddSubmit(refName) {
      console.log("产品修改和添加 参数：" + refName);
      this.$refs[refName]
          .getProductInfo()
          .then((val) => {
            productModifyOrAdd({
              taxationCateCode: val.taxationCateCode,
              taxationCateName: val.taxationCateName,
              taxationCateAbbr: val.taxationCateAbbr,
              productId: val.productId,
              productName: val.productName,
              shortCode: val.shortCode,
              specsModel: val.specsModel,
              price: val.price,
              unit: val.unit,
              taxPriceFlag: val.taxPriceFlag,
              taxRate: val.taxRate,
              zeroRateFlag: val.zeroRateFlag,
              preferentialFlag: val.preferentialFlag,
              preferentialType: val.preferentialType,
            })
                .then((val) => {
                  // 成功关闭弹窗
                  this.productAddData.productAddShow = false;
                  // this.productModifyData.dialogVisible = false
                  this.getProductData();
                  this.$message({
                    message: "商品信息添加成功！",
                    type: "success",
                  });
                })
                .catch((err) => {
                  this.$message.error(err);
                });
          })

          .catch((err) => {
            this.$message.error(err);
          });
    },
    // 获取选择的开票信息
    async getInvoice(invoiceData) {
      let products = [];
      this.purchaserName = invoiceData.buyerName;
      this.taxNumber = invoiceData.buyerEntTaxId;
      this.addressPhone = invoiceData.buyerAddressPhone;
      this.openingBank = invoiceData.buyerBankAccount;
      this.remark = invoiceData.remarks;
      products = await InvoiceReopen(
          invoiceData.goodsDetailVOs,
          this.billingTaxId,
          this.token,
          false
      );
      products = ProductTaxRateSwitch(products, this.isRedInvoice, this.isRedInvoice);
      this.calculationTotalAmount(products);
      this.productData.product = products;
      this.isShowInvoiceCopy = false;
    },
    // 商品选择折扣信息
    productCheckChange(value) {
      let productNumber = this.productData.product.length;
      let checkNumber = 0;
      this.productData.product.map((_, i) => {
        if (this.productData.product[i].productCheck === true) {
          checkNumber++;
        }
      });
      if (checkNumber > 0 && productNumber === checkNumber) {
        this.productCheckAll = true;
      } else {
        this.productCheckAll = false;
      }
      if (checkNumber > 0 && checkNumber < productNumber) {
        this.isIndeterminate = true;
      } else {
        this.isIndeterminate = false;
      }
    },
    // 产品列表全选
    productCheckAllChange(value) {
      this.isIndeterminate = false;
      if (value) {
        this.productData.product.map((_, i) => {
          if (this.productData.product[i].productCheck === false) {
            this.productData.product[i].productCheck = true;
          }
        });
      } else {
        this.productData.product.map((_, i) => {
          if (this.productData.product[i].productCheck === true) {
            this.productData.product[i].productCheck = false;
          }
        });
      }
    },
    // 判断token状态
    async getTokenStatus() {
      const url = "/auth/comm/user/refreshToken";
      if (this.token && this.account) {
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              account: this.account,
              reqChannel: 4,
            },
            false,
            1
        );
        if (response) {
          if (response.code === 0) {
            let user = JSON.parse(cache.getSession("user"));
            user.expirationTime = response.data.expirationTime;
            // user.token = response.data.token
            cache.setToken(response.data.token);
            cache.setSession("user", user);
            this.token = response.data.token;
            this.expirationTime = response.data.expirationTime;
          }
        }
      }
    },
    // 显示产品列表
    seeProductList() {
      this.isShowProduct = true
    },
    // 商品列表打开
    productListPageOpen() {
      this.$refs.productList.getProductList(this.productData.product)
    },
    // 商品列表关闭
    productListPageClose() {
      this.$refs.productList.cleanProductList()
    },
    // 加载发票默认信息
    setInvoiceInfo() {
      let user = JSON.parse(cache.getSession('user'))
      let company = JSON.parse(cache.getSession('company'))
      this.entTaxId = company.entTaxId
      this.defaultDeviceInfo = company.defaultDeviceInfo
      this.account = user.account
      this.expirationTime = user.expirationTime
      this.token = cache.getToken()
      this.requestId = this.$attrs.invoiceRedLetterEdit.requestId
      this.getRedLetterData()
    },
    // 保存
    async submitInvoice(isUpload) {
      if (this.contactNumber === '') {
        this.$message({
          message: '请输入联系电话！',
          type: 'warning'
        })
        return
      }
      if (this.explain === '') {
        this.$message({
          message: '请输入申请理由！',
          type: 'warning'
        })
        return
      }
      let product = InvoiceProducts(this.productData.product, this.isTaxIncluded, false)
      console.log(product)
      if (product.state !== 0) {
        this.$message({
          message: '货物或应税劳务.服务名称和金额不能为空！',
          type: 'warning'
        })
        return
      }
      let tax = '1'
      if (this.taxIncluded !== '含税') {
        tax = '0'
      }
      if (this.token) {
        let data = {}
        if (this.buyer === 1) {
          data = {
            SBLX: this.defaultDeviceInfo.deviceType, // 设备类型 设备类型1：证书  2：税控盘  3：金税盘  4：税控ukey  5:税控服务器
            SBBH: this.defaultDeviceInfo.taxDiscId, //设备编号	税控盘盘号
            FPZL: this.invoiceType, //发票种类	1.增值税普通电子发票   2.增值税电子专用发票  3.增值税普通纸质发票  4 增值税专用纸质发票
            ZSFS: '0', //	征税方式	String	4	yes		"征税方式， 0：普通征税；2：差额征税（默认是0普通征税）"
            KCE: 0, //	扣除额	decimal				扣除额， ZSFS=2，差额征税时必传。数值必须小于价税合计。
            KPF_NSRSBH: this.sellerTaxNumber, //	开票方纳税人识别号	String	20	yes		开票企业税号
            KPF_MC: this.sellerName, //	开票方名称	String	80	yes		开票企业名称
            FPDM: this.invoiceCode, //	发票代码	String	20	yes		需要红字申请的发票的代码
            FPHM: this.invoiceNumber, //	发票号码	String	20	yes		需要红字申请的发票的号码
            SPF_NSRSBH: this.buyerTaxNumber, //	收票方纳税人识别号	String	20	yes		收票方企业税号
            SPF_MC: this.buyerName, //	收票方名称	String	80	yes		收票方名称
            JSHJ: -this.totalAmountRate, //	价税合计	decimal		yes		单位：元（精确 2 位小数）
            HJJE: -this.totalAmount, //	合计金额	decimal		yes		不含税，单位：元（精确 2 位小数）
            HJSE: -this.totalTaxAmount, //	合计税额	decimal		yes		单位：元（精确 2 位小数）
            HSBZ: this.isTaxIncluded === true ? '1' : '0', //	含税标志	String	4	no		含税标志   1:含税   0 不含税   默认不含税0
            SLBZ: tax, //	税率标志	String	4	no		税率标志：默认为：1
            SQLX: this.buyer, //	申请类型	Integer	2	yes		申请类型：1:购方申请     2：销方申请
            DKBZ: this.deduction, //	抵扣标志	Boolean 	1	no		抵扣标志：0:未抵扣  1：已抵扣(SQLX=1 时必填)
            SQLY: this.explain, //	申请理由	String	100	yes		申请理由
            LXDH: this.contactNumber, //	联系电话	String	20	yes		联系电话  购方申请电话留购方，销方申请留销方
            COMMON_FPKJ_XMXXS: {
              COMMON_FPKJ_XMXX: product.products
            }
          }
        } else {
          data = {
            SBLX: this.defaultDeviceInfo.deviceType, // 设备类型 设备类型1：证书  2：税控盘  3：金税盘  4：税控ukey  5:税控服务器
            SBBH: this.defaultDeviceInfo.taxDiscId, //设备编号	税控盘盘号
            FPZL: this.invoiceType, //发票种类	1.增值税普通电子发票   2.增值税电子专用发票  3.增值税普通纸质发票  4 增值税专用纸质发票
            ZSFS: '0', //	征税方式	String	4	yes		"征税方式， 0：普通征税；2：差额征税（默认是0普通征税）"
            KCE: 0, //	扣除额	decimal				扣除额， ZSFS=2，差额征税时必传。数值必须小于价税合计。
            KPF_NSRSBH: this.sellerTaxNumber, //	开票方纳税人识别号	String	20	yes		开票企业税号
            KPF_MC: this.sellerName, //	开票方名称	String	80	yes		开票企业名称
            FPDM: this.invoiceCode, //	发票代码	String	20	yes		需要红字申请的发票的代码
            FPHM: this.invoiceNumber, //	发票号码	String	20	yes		需要红字申请的发票的号码
            SPF_NSRSBH: this.buyerTaxNumber, //	收票方纳税人识别号	String	20	yes		收票方企业税号
            SPF_MC: this.buyerName, //	收票方名称	String	80	yes		收票方名称
            JSHJ: -this.totalAmountRate, //	价税合计	decimal		yes		单位：元（精确 2 位小数）
            HJJE: -this.totalAmount, //	合计金额	decimal		yes		不含税，单位：元（精确 2 位小数）
            HJSE: -this.totalTaxAmount, //	合计税额	decimal		yes		单位：元（精确 2 位小数）
            HSBZ: this.isTaxIncluded === true ? '1' : '0', //	含税标志	String	4	no		含税标志   1:含税   0 不含税   默认不含税0
            SLBZ: tax, //	税率标志	String	4	no		税率标志：默认为：1
            SQLX: this.buyer, //	申请类型	Integer	2	yes		申请类型：1:购方申请     2：销方申请
            SQLY: this.explain, //	申请理由	String	100	yes		申请理由
            LXDH: this.contactNumber, //	联系电话	String	20	yes		联系电话  购方申请电话留购方，销方申请留销方
            COMMON_FPKJ_XMXXS: {
              COMMON_FPKJ_XMXX: product.products
            }
          }
        }
        let url = '/sys/invoice/redInfo/save'
        if (isUpload) {
          url = '/sys/invoice/redInfo/commit'
        } else {
          url = '/sys/invoice/redInfo/save'
        }
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              applyEntTaxId: this.entTaxId,
              requestId: this.requestId,
              mobile: this.account,
              hzsqCmdParam: {
                REQUEST_COMMON_HZSQ: data
              },
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            this.$attrs.invoiceRedLetterEdit.redLetterEditShow()
          } else {
            this.$message.error('保存失败！')
          }
        }
      }
    },
    // 读取数据
    async getRedLetterData() {
      if (this.token) {
        const url = '/sys/invoice/redInfo/findApplyDetail'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              requestId: this.requestId
            },
            false,
            2
        )
        if (response) {
          if (response.code === 0) {
            this.buyerName = response.data.REQUEST_COMMON_HZSQ.SPF_MC
            this.buyerTaxNumber = response.data.REQUEST_COMMON_HZSQ.SPF_NSRSBH
            this.sellerName = response.data.REQUEST_COMMON_HZSQ.KPF_MC
            this.sellerTaxNumber = response.data.REQUEST_COMMON_HZSQ.KPF_NSRSBH
            this.invoiceCode = response.data.REQUEST_COMMON_HZSQ.FPDM
            this.invoiceNumber = response.data.REQUEST_COMMON_HZSQ.FPHM
            this.invoiceType = response.data.REQUEST_COMMON_HZSQ.FPZL
            if (this.invoiceType === 1) {
              this.invoiceTypeName = '增值税普通电子发票'
            }
            if (this.invoiceType === 2) {
              this.invoiceTypeName = '增值税电子专用发票'
            }
            if (this.invoiceType === 3) {
              this.invoiceTypeName = '增值税普通纸质发票'
            }
            if (this.invoiceType === 4) {
              this.invoiceTypeName = '增值税专用纸质发票'
            }
            this.buyer = response.data.REQUEST_COMMON_HZSQ.SQLX
            if (response.data.REQUEST_COMMON_HZSQ.SQLX === 1) {
              this.sellerType = '购买方申请'
              this.status = 1
            } else {
              this.sellerType = '销售方申请'
              this.status = 2
            }
            if (response.data.REQUEST_COMMON_HZSQ.DKBZ) {
              this.deduction = true
              this.deductionFont = '已抵扣'
            } else {
              this.deduction = false
              this.deductionFont = '未抵扣'
            }
            this.contactNumber = response.data.REQUEST_COMMON_HZSQ.LXDH
            this.explain = response.data.REQUEST_COMMON_HZSQ.SQLY
            let products = await RedLetterInfoProduct(response.data.REQUEST_COMMON_HZSQ
                .COMMON_FPKJ_XMXXS.COMMON_FPKJ_XMXX, this.entTaxId, this.token)
            // products = ProductTaxRateSwitch(products, true)
            this.calculationTotalAmount(products)
            this.productData.product = products
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.body {
  flex: 1;
}

.invoice_print {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}

.invoice_radio {
  margin: 5px;
}

.invoice_button {
  margin: 5px;
}

.invoice_input {
  width: 250px;
}

.invoice_text {
  width: 90%;
}

.customer {
  height: 40%;
}
</style>
