<template>
  <div class="rece" @click="onBulrInvoiceTitleEvent">
    <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.invoiceTitleType"
              :disabled="Boolean(id)"
              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 class="rece-invoiceTitle">
          <cr-field
            v-model.trim="formData.invoiceTitle"
            placeholder="请输入发票抬头"
            label="发票抬头"
            name="发票抬头"
            required
            :max-length="40"
            clearable
            class="formItem"
            type="text"
            :rules="rules.invoiceTitle"
            @input="searchInvoiceTitleEvent"
          />
          <div v-if="showPrefixVisbale" class="rece-list">
            <ul class="rece-list-container">
              <li
                v-for="(item, index) in prefixInvoiceList"
                :key="index"
                class="rece-list-li"
                @click.stop="setInvoiceTitleEvent(item)"
                v-html="item.html"
              />
            </ul>
          </div>
        </div>
        <cr-field
          v-if="formData.invoiceTitleType === 2"
          v-model.trim="formData.taxNumber"
          placeholder="请输入单位税号"
          label="发票税号"
          name="发票税号"
          class="formItem"
          required
          :rules="rules.taxNumber"
        />
        <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-form>
      <footerButton :fixed="true" :disabled="isDisabled" btn-text="完成" @btn-click="submit" />
    </div>
  </div>
</template>
<script>
import api from '@/api/receipts.js';
import footerButton from '../components/footerButton.vue';
import validateMixin from '../mixins/validate.mixin';
import jumpAppMixin from '../mixins/jumpApp.mixin';
import localStorageService from '@/service/localStorage.service';
import { throtte } from '@/service/utils.service';
export default {
  components: {
    footerButton
  },
  mixins: [validateMixin, jumpAppMixin],
  data() {
    const invoiceTitleType = +this.$route.query.invoiceTitleType || 1;
    return {
      invoiceTitleVisble: false,
      id: '',
      formData: {
        invoiceTitleType,
        invoiceTitle: '',
        taxNumber: '',
        registAddress: '',
        depositBank: '',
        bankAccount: ''
      },
      showPrefix: false,
      prefixInvoiceList: []
    };
  },
  computed: {
    isDisabled: function() {
      let val = true;
      if (this.formData.invoiceTitleType === 2) {
        val = this.titleFlag && this.taxIdFlag;
      } else {
        val = this.titleFlag;
      }
      return !val;
    },
    showPrefixVisbale() {
      if (this.formData.invoiceTitleType === 2) {
        return this.showPrefix;
      }
      return false;
    }
  },
  created() {
    const id = this.$route.query.id;
    if (id) {
      this.id = id;
      // console.log('编辑状态=============>');
      this.userInoviceTitleList(id);
    }
  },
  methods: {
    setInvoiceTitleEvent(item) {
      this.formData.invoiceTitle = item.invoiceTitle;
      this.formData.taxNumber = item.taxNumber;
      this.showPrefix = false;
    },

    onBulrInvoiceTitleEvent() {
      this.showPrefix = false;
    },
    //  stripscript
    searchInvoiceTitleEvent: throtte(function(value) {
      this.stripscript(value);
      if (this.formData.invoiceTitleType === 2) {
        const keyword = this.formData.invoiceTitle;
        if (keyword.length >= 3) {
          this.userInovicePrefixQuery();
        } else {
          this.prefixInvoiceList = [];
        }
      }
    }, 500),

    // 诺诺前缀查询企业名称和税号
    async userInovicePrefixQuery() {
      const value = this.formData.invoiceTitle;
      const [res, error] = await api.userInovicePrefixQuery({ prefix: value });
      if (!error) {
        this.prefixInvoiceList = this.renderActiveHtml(value, res || []);
        console.log(this.prefixInvoiceList);
        this.showPrefix = this.prefixInvoiceList.length ? true : false;
        // this.showPrefix = true;
      }
    },

    renderActiveHtml(keyword, indexList) {
      return (indexList || []).map(item => {
        let templateString = item.invoiceTitle;
        if (item.invoiceTitle.indexOf(keyword) !== -1) {
          const reg = new RegExp(keyword, 'i');
          templateString = item.invoiceTitle.replace(
            reg,
            `<span style="color: #EC1500;">${keyword}</span>`
          );
        }
        return {
          ...item,
          html: templateString
        };
      });
    },
    async userInoviceTitleList(id) {
      const [res, error] = await api.userInoviceTitleList({ id });
      if (!error) {
        const [data = {}] = res || [];
        const { id, ...other } = data;
        this.id = id;
        this.$set(this, 'formData', other);
        this.titleFlag = true;
        this.taxIdFlag = true;
      }
    },
    backPage() {
      localStorageService.set('invoiceRefresh', 1);
      this.closeApp();
    },

    openInvoiceTitlePopup() {
      this.invoiceTitleVisble = true;
    },
    toastMessage(msg) {
      this.$toast(msg);
      this.backPage();
      // const toast = this.$toast(msg);
      // toast.onClose = () => {
      //   this.backPage();
      // };
    },
    async userInoviceTitleModify() {
      const { formData, id } = this;
      const [, error] = await api.userInoviceTitleModify({ id, ...formData });
      if (!error) {
        this.toastMessage('修改成功！');
      }
    },
    async userInoviceTitleAdd() {
      const [, error] = await api.userInoviceTitleAdd(this.formData);
      if (!error) {
        this.toastMessage('添加成功！');
      }
    },

    async submit() {
      this.$refs.form.validate().then(() => {
        if (this.id) {
          this.userInoviceTitleModify();
          return;
        }
        this.userInoviceTitleAdd();
      });
    },
    changeType() {
      // this.formData.taxNumber = '';
      // this.formData.registAddress = '';
      // this.formData.depositBank = '';
      // this.formData.bankAccount = '';
    }
  }
};
</script>
<style lang="less" src="../invoiceReceipt/index.less" scoped></style>
<style lang="less" scoped>
.rece-invoiceTitle {
  position: relative;
}
.rece-list {
  position: absolute;
  top: 49px;
  right: 24px;
  z-index: 1;
  width: 247px;
  max-height: 240px;
  background-color: @white;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(100, 101, 102, 0.12);
  &-container {
    padding: 12px;
    box-sizing: border-box;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      top: -5px;
      left: 14px;
      width: 10px;
      height: 10px;
      background-color: @white;
      transform: rotate(45deg);
    }
  }
  &-li {
    .text-size(12);
    height: 27px;
    line-height: 27px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>
