<template>
  <div class="rece">
    <div class="rece-form">
      <cr-form ref="form" v-model="formData">
        <cr-field name="radio" label="发票内容" class="formItem rece-btn">
          <template #input>
            <cr-radio-group v-model="formData.invoiceContentType">
              <cr-radio btn-style btn-size="small" :name="1">商品明细</cr-radio>
              <cr-radio btn-style btn-size="small" :name="2">商品类别</cr-radio>
            </cr-radio-group>
          </template>
        </cr-field>
        <cr-field name="radio" label="抬头类型" class="formItem rece-btn">
          <template #input>
            <cr-radio-group
              v-model="formData.invoiceTitleType"
              direction="horizontal"
              checked-color="#ec1500"
              @change="changeType"
            >
              <cr-radio btn-style btn-size="small" :name="1">个人</cr-radio>
              <cr-radio btn-style btn-size="small" :name="2">企业</cr-radio>
            </cr-radio-group>
          </template>
        </cr-field>
        <div @click="openInvoiceTitlePopup">
          <cr-field
            v-model="formData.invoiceTitle"
            placeholder="请选择发票抬头"
            right-icon="arrow"
            label="发票抬头"
            name="发票抬头"
            required
            :max-length="40"
            :readonly="true"
            clearable
            class="formItem"
            type="text"
            :rules="rules.invoiceTitle"
            @input="stripscript"
          />
        </div>
        <cr-field
          v-if="formData.invoiceTitleType === 2"
          v-model.trim="formData.taxNumber"
          placeholder="请输入单位税号"
          label="发票税号"
          name="发票税号"
          class="formItem"
          required
          :rules="rules.taxNumber"
        />
        <cr-field
          v-model.trim="formData.email"
          placeholder="请输入发票收取邮箱"
          type="email"
          required
          clearable
          label="发送邮箱"
          class="formItem"
          name="发送邮箱"
          :rules="rules.email"
        />
        <cr-field
          v-model.trim="formData.mobile"
          placeholder="请输入联系方式"
          type="tel"
          required
          label="联系电话"
          name="联系电话"
          class="formItem"
          :max-length="11"
          :rules="rules.mobile"
        />
        <div v-if="formData.invoiceTitleType === 2">
          <cr-field
            v-model.trim="formData.registAddress"
            placeholder="选填"
            label="注册地址"
            name="注册地址"
            class="formItem"
            :rules="rules.registAddress"
          />
          <cr-field
            v-model.trim="formData.depositBank"
            placeholder="选填"
            label="开户银行"
            name="开户银行"
            class="formItem"
            :rules="rules.depositBank"
          />
          <cr-field
            v-model.trim="formData.bankAccount"
            placeholder="选填"
            label="银行账号"
            name="银行账号"
            class="formItem"
            type="digit"
          />
        </div>
        <cr-field
          v-model.trim="formData.remarks"
          placeholder="选填"
          label="备注"
          name="备注"
          class="formItem"
        />
      </cr-form>
      <div class="rece-ticket">
        <div class="example sample">
          <p class="example-text">开票须知</p>
          <ul class="example-content">
            <li>1.开票金额为实际的支付金额。</li>
            <li>2.虚拟类（优惠券）支付的订单商品不能参与开票。</li>
          </ul>
        </div>
        <div class="example instructions">
          <p class="example-text">发票样例</p>
          <div class="example-pic">
            <cr-image
              src="@/assets/images/electronicInvoice/invoiceExample.png"
              width="100%"
              height="100%"
            />
          </div>
        </div>
      </div>
      <footerButton
        :fixed="true"
        btn-text="提交电子发票"
        :disabled="isDisabled || isSubmitDisabled"
        @btn-click="submit"
      />
    </div>
    <invoiceTitlePopup
      :value.sync="invoiceTitleVisble"
      :list="invoiceTitleList"
      :invoice-title-type="formData.invoiceTitleType"
      @select="selectInvoiceTitleEvent"
    />
  </div>
</template>
<script>
import api from '@/api/receipts.js';
import invoiceTitlePopup from '../components/invoiceTitlePopup.vue';
import footerButton from '../components/footerButton.vue';
import jumpAppMixin from '../mixins/jumpApp.mixin';
import validateMixin from '../mixins/validate.mixin';
import checkOpenMixin from '../mixins/checkOpen.mixin';
import localStorageService from '@/service/localStorage.service';

export default {
  components: {
    footerButton,
    invoiceTitlePopup
  },
  mixins: [jumpAppMixin, validateMixin, checkOpenMixin],
  data() {
    return {
      invoiceTitleVisble: false,
      invoiceTitleList: [], // 发票抬头列表
      isSubmitDisabled: false,
      formData: {
        invoiceContentType: 1,
        invoiceTitleType: 1,
        invoiceTitle: '',
        email: '',
        mobile: '',
        taxNumber: '',
        registAddress: '',
        depositBank: '',
        bankAccount: '',
        remarks: ''
      }
    };
  },
  computed: {
    isDisabled: function() {
      let val = true;
      if (this.formData.type === 2) {
        val = this.titleFlag && this.taxIdFlag && this.emailFlag && this.phoneNumFlag;
      } else {
        val = this.titleFlag && this.emailFlag && this.phoneNumFlag;
      }
      return !val;
    }
  },
  mounted() {
    const query = this.$route.query;
    console.log(query.orderNosCombine);
    const orderNosCombine = query.orderNosCombine ? query.orderNosCombine.split(',') : [];
    const orderNosSingle = query.orderNosSingle ? query.orderNosSingle.split(',') : [];
    console.log(orderNosCombine);
    console.log(orderNosSingle);
    // const showInvoice = localStorageService.get('showInvoice');
    // if (showInvoice) {
    //   this.openInvoiceTitlePopup();
    //   localStorageService.remove('showInvoice');
    // }
  },
  methods: {
    // 从上个页面返回的时候刷新
    refreshChange() {
      this.openInvoiceTitlePopup();
    },
    async openInvoiceTitlePopup() {
      this.invoiceTitleVisble = true;
      const [res, error] = await api.userInoviceTitleList();
      if (!error) {
        this.invoiceTitleList = [];
        const type = this.formData.invoiceTitleType;
        const invoiceTitleList = (res || []).filter(item => item.invoiceTitleType === type);
        this.$set(this, 'invoiceTitleList', invoiceTitleList);
      }
    },
    selectInvoiceTitleEvent(val) {
      this.formData.bankAccount = val.bankAccount;
      this.formData.depositBank = val.depositBank;
      this.formData.invoiceTitle = val.invoiceTitle;
      this.formData.registAddress = val.registAddress;
      this.formData.taxNumber = val.taxNumber;
    },

    async addInvoice() {
      const formData = this.formData;
      const query = this.$route.query;
      const orderNosCombine = query.orderNosCombine ? query.orderNosCombine.split(',') : [];
      const orderNosSingle = query.orderNosSingle ? query.orderNosSingle.split(',') : [];
      const [res, error] = await api.addInvoice({ orderNosCombine, orderNosSingle, ...formData });
      if (!error) {
        this.goReceiptAfter(res);
      } else {
        this.isSubmitDisabled = false;
      }
      // const invoicePageType = query.invoicePageType;
      // const orderNos = query.orderNos?.split(',');
      // const [res, error] = await api.addInvoice({ orderNos, invoicePageType, ...formData });
      // const [res, error] = await api.addInvoice({ orderNos, invoicePageType, ...formData });
      // if (!error) {
      //   this.goReceiptAfter(res);
      // }
    },

    async reAddInvoice() {
      const formData = this.formData;
      const invoiceSerialNum = this.$route.query.invoiceSerialNum;
      const [res, error] = await api.reAddInvoice({ invoiceSerialNum, ...formData });
      if (!error) {
        this.goReceiptAfter(res);
      } else {
        this.isSubmitDisabled = false;
      }
    },

    goReceiptAfter(res) {
      localStorageService.set('receiptSuccessOptions', res);
      this.jumpAppUrl('/electronicReceipt/success', {}, true);
    },

    async submit() {
      this.$refs.form.validate().then(() => {
        const isReadd = this.$route.query.invoiceSerialNum; // 是否是重新开票
        console.log('==============>isReadd', isReadd);
        this.isSubmitDisabled = true;
        if (isReadd) {
          this.reAddInvoice();
          return;
        }
        this.addInvoice();
      });
    },
    back() {
      this.$router.go(-1);
    },
    changeType() {
      this.formData.invoiceTitle = '';
      this.formData.taxNumber = '';
      this.formData.registAddress = '';
      this.formData.depositBank = '';
      this.formData.bankAccount = '';
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
