<!-- 新增发票 -->
<template>
  <view class="invoice">
    <!-- 导航栏 -->
    <u-navbar
      title-color="#fff"
      :custom-back="customBack"
      :border-bottom="false"
      back-icon-color="#CCE8FF"
      :background="{ background: '#008CFF' }"
      title="开发票"
    />
    <view class="invoice-form">
      <u-form :model="form" :rules="rules" ref="uForm" label-width="150" label-align="right">
        <u-form-item label="抬头：" required>
          <u-radio-group v-model="queryParams.invoHeadType" @change="invoTypeChange">
            <u-radio :name="1">企业</u-radio>
            <u-radio :name="2">个人</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="抬头名称：" prop="invoName" required>
          <u-input v-model="form.invoName" placeholder="请选择发票抬头" border disabled />
          <u-icon slot="right" name="list-dot" size="40" color="#606266" @click="moreCompany" />
        </u-form-item>
        <u-form-item label="税号：" prop="invoCode" required v-if="queryParams.invoHeadType === 1">
          <u-input v-model="form.invoCode" placeholder="税号自动填充" border disabled />
        </u-form-item>
        <u-form-item label="更多内容：" prop="moreContentValue">
          <u-input v-model="moreContentPop.moreContentValue" placeholder="开户银行、银行账号等" border disabled />
          <u-icon slot="right" name="arrow-right" size="36" color="#606266" @click="moreContent" />
        </u-form-item>
        <u-form-item label="发票金额："> ￥{{ form.amount }} </u-form-item>
      </u-form>
    </view>
    <view class="invoice-form margin-top">
      <u-form :model="form" ref="uForm1" label-width="150" label-align="right">
        <u-form-item label="电子邮箱：" prop="invoMail">
          <u-input v-model="form.invoMail" placeholder="选填" border />
        </u-form-item>
        <u-form-item label="手机号码：" prop="invoPhone">
          <u-input v-model="form.invoPhone" placeholder="选填" border />
        </u-form-item>
      </u-form>
    </view>
    <view class="invoice-submit">
      <u-button type="primary" :loading="loading" @click="submitForm">提交</u-button>
    </view>
    <!-- 公司弹框 -->
    <u-popup v-model="companyPop.show" mode="bottom" :closeable="true" height="50vh">
      <view class="popup">
        <view class="popup-list" v-if="companyPop.list.length">
          <u-radio-group class="popup-list-group" v-model="companyPop.form.name" :wrap="true">
            <u-radio class="popup-list-item" v-for="(item, index) in companyPop.list" :key="index" :name="item.id" @change="companyRadioClick(item)">
              {{ item.invoName }}
            </u-radio>
          </u-radio-group>
        </view>
        <view class="popup-list" v-else>
          <view class="popup-list-item">暂无抬头，请先添加</view>
        </view>
        <view class="popup-bottom">
          <u-button type="info" @click="addInvoiceHeader">添加常用发票抬头</u-button>
        </view>
      </view>
    </u-popup>
    <!-- 更多内容 -->
    <u-popup v-model="moreContentPop.show" mode="center" width="100%" height="100%">
      <view class="invoice-more-pop">
        <view class="invoice-more-pop-form">
          <u-form :model="moreContentPop.form" ref="uForm2" label-width="150" label-align="right">
            <u-form-item label="开户银行：" prop="openBank">
              <u-input v-model="form.openBank" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="银行账号：" prop="numBank">
              <u-input v-model="form.numBank" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="企业地址：" prop="mapCom">
              <u-input v-model="form.mapCom" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="企业电话：" prop="phoneCom">
              <u-input v-model="form.phoneCom" placeholder="选填" border />
            </u-form-item>
          </u-form>
        </view>
        <view class="invoice-more-pop-submit">
          <u-button type="primary" @click="moreContentConfirm">确定</u-button>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        invoName: '',
        invoCode: '',
        invoHeadId: '',
        invoMail: '',
        invoPhone: '',
        invoType: 1,
        phoneCom: '',
        mapCom: '',
        openBank: '',
        numBank: '',
        amount: '',
        orderIds: []
      },
      rules: {
        invoType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        invoName: [{ required: true, message: '请输入抬头名称', trigger: 'blur' }],
        invoCode: [{ required: true, message: '请输入税号', trigger: 'blur' }]
      },
      companyPop: {
        show: false,
        form: {
          name: ''
        },
        list: []
      },
      loading: false,
      queryParams: {
        invoHeadType: 1
      },
      moreContentPop: {
        show: false,
        moreContentValue: ''
      }
    };
  },
  onLoad(options) {
    const { invoType } = options;
    this.form.invoType = invoType;
  },
  onShow() {
    uni.getStorage({
      key: 'availableOrderKey',
      success: (res) => {
        const { total, ids, invoType } = JSON.parse(res.data);
        this.form.amount = total;
        this.form.orderIds = ids;
        this.form.invoType = invoType;
      },
      fail: (err) => {
        uni.showModal({
          title: '提示',
          content: '当前页面的订单已经开票完毕，请返回开票页面',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.redirectTo({
                url: `/pages/invoiceModule/myInvoice/myInvoice`
              });
            }
          }
        });
      }
    });
    this.getInvoiceHeaderSelect();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    /**
     * @description: 选择企业
     * @return {*}
     */
    moreCompany() {
      this.companyPop.show = true;
    },
    customBack() {
      uni.navigateBack();
    },
    moreContent() {
      this.moreContentPop.show = true;
    },
    /**
     * @description: 获取发票抬头下拉
     * @return {*}
     */
    async getInvoiceHeaderSelect() {
      const { code, data } = await this.$u.api.invoiceModuleApi.getInvoiceHeadSelectApi({ ...this.queryParams });
      if (code === 200) {
        this.companyPop.list = data;
        const { invoName, invoCode, id, invoMail, invoPhone, invoStatus } = data[0] || {};
        const isEmpty = invoStatus !== 1;
        this.form.invoName = isEmpty ? '' : invoName;
        this.form.invoCode = isEmpty ? '' : invoCode;
        this.form.invoHeadId = isEmpty ? '' : id;
        this.form.invoMail = isEmpty ? '' : invoMail;
        this.form.invoPhone = isEmpty ? '' : invoPhone;
        this.companyPop.form.name = isEmpty ? '' : id;
      }
    },
    /**
     * @description: 选择抬头
     * @param {*} item
     * @return {*}
     */
    companyRadioClick(item) {
      this.companyPop.show = false;
      this.form.invoName = item.invoName;
      this.form.invoCode = item.invoCode;
      this.form.invoHeadId = item.id;
      this.form.invoMail = item.invoMail;
      this.form.invoPhone = item.invoPhone;
      this.companyPop.form.name = item.id;
    },
    addInvoiceHeader() {
      this.companyPop.show = false;
      this.$u.route({
        url: '/pages/invoiceModule/invoiceHeaderList/invoiceHeaderList'
      });
    },
    /**
     * @description: 抬头类型切换
     * @param {*} val
     * @return {*}
     */
    invoTypeChange(val) {
      this.queryParams.invoHeadType = val;
      this.getInvoiceHeaderSelect();
    },
    /**
     * @description: 更多内容弹框确认
     * @return {*}
     */
    moreContentConfirm() {
      this.moreContentPop.show = false;
      const { openBank, numBank, mapCom, phoneCom } = this.form;
      const moreContentTotal = [openBank, numBank, mapCom, phoneCom].filter(Boolean).length;
      this.moreContentPop.moreContentValue = moreContentTotal ? `共4项 已填写${moreContentTotal}项` : '';
    },
    submitForm() {
      this.$refs.uForm.validate(async (valid) => {
        if (!valid) return;
        try {
          this.loading = true;
          uni.showLoading({
            title: '提交中...'
          });
          const { invoHeadId, invoName, invoCode, invoMail, invoPhone, invoType, phoneCom, mapCom, openBank, numBank, orderIds } = this.form;
          const { code } = await this.$u.api.invoiceModuleApi.addInvoiceApi({
            invoHeadId,
            invoName,
            invoCode,
            invoMail,
            invoPhone,
            invoType,
            phoneCom,
            mapCom,
            openBank,
            numBank,
            orderIds
          });
          if (code === 200) {
            uni.removeStorage({
              key: 'availableOrderKey',
              success: function (res) {
                console.log('success');
              }
            });
            this.$refs.uToast.show({
              title: '添加成功!',
              type: 'success',
              duration: 1000
              // url: '/pages/invoiceModule/invoiceSuccess/invoiceSuccess'
            });
            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/invoiceModule/invoiceSuccess/invoiceSuccess`
              });
              uni.hideLoading();
              this.loading = false;
            }, 1000);
          }
        } catch (error) {
          uni.hideLoading();
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './addInvoice.scss';
</style>
