<template>
  <Modal class-name="relate-invoice-modal" v-model="modalVisible" fullscreen title="引用票据" @on-ok="handleOk">
    <InvoiceList :mode="1" @selectionChange="handleSelectionChange" />
  </Modal>
</template>

<script>
import InvoiceList from '../../../../@rbc/invoice/src/components/invoice-list.vue'
export default {
  components: {
    InvoiceList,
  },
  data() {
    return {
      selectedRows: [],
      modalVisible: true,
      bill: null,
      invoiceName: '',
    }
  },
  methods: {
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleOk() {
      if (!this.selectedRows) {
        this.$Message.error('请选择数据')
      }
      if (this.selectedRows.some((row) => !row.frontendVerificationStatus)) {
        this.$Message.error('部分数据需先查验成功方可选择')
      }
      for (let i = 0; i < this.selectedRows.length; ++i) {
        const row = this.selectedRows[i]
        let templateName = this.invoiceName.split('.')[1]
        templateName = `${templateName}.res.json`
        GMS.$http.post(
          '/yxgl/getImageAndInvoiceMappingRelation',
          {
            imageId: row.id,
            templateName: templateName,
            yearFlag: row.yearFlag,
          },
        ).then((res) => {
          const arr = res && res.data && res.data.data || []
          arr.forEach((tableMap) => {
            const mapContent = tableMap.content
            const subBillName = tableMap.subBillName
            this.bill.addSubData(subBillName)
            const obj = this.bill.getSubData(subBillName)
            const index = obj.length - 1
            for (let key of Object.keys(mapContent)) {
              const keyVal = mapContent[key]
              obj[index].setValue(key, keyVal)
            }
            this.bill.refreshSubDataRow(subBillName)
          })
        })
      }
      
    },
  },
}
</script>

<style lang="less">
.relate-invoice-modal {
  .ivu-modal-body {
    padding: 0;
  }
}

</style>