<template>
  <div>
    <a-table bordered :pagination="false" :columns="columns" :data-source="detailItemList">
      <template slot="itemName" slot-scope="text, record">
        <a-input v-if="!readOnly" v-model="record.itemName" :maxLength="20" :placeholder="'请输入'+title+'项目'"></a-input>
        <div v-else>{{ record.itemName }}</div>
      </template>
      <template slot="itemAmount" slot-scope="text, record">
        <a-input-number
          v-if="!readOnly"
          style="width:100%"
          :min="0"
          :max="99999999"
          :precision="2"
          :placeholder="'请输入'+title+'金额'"
          @change="getTotal"
          v-model="record.itemAmount"></a-input-number>
        <div v-else>{{ Number(record.itemAmount).toFixed(2) }}</div>
      </template>
      <template slot="action" slot-scope="text, record,index">
        <div>
          <a-button
            v-if="!readOnly"
            size="small"
            type="link"
            class="button-error"
            @click="delItem(record,index)"
          >删除</a-button>
        </div>
      </template>
    </a-table>
    <div style="border:1px solid #eee;border-top:0;" v-if="!readOnly">
      <a-button @click="addItem" type="link" ghost class="button-info" block>+ 新增{{ title }}明细</a-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SxItemList',
  props: {
    title: {
      type: String,
      default: ''
    },
    list: [Array],
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 使用授信合集
      detailItemList: this.list
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: this.title + '项目', scopedSlots: { customRender: 'itemName' }, width: '45%', align: 'center' },
        { title: this.title + '金额', scopedSlots: { customRender: 'itemAmount' }, width: '45%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.readOnly) {
        arr.pop()
      }
      return arr
    }
  },
  mounted () {
    if (this.detailItemList.length == 0) {
      this.addItem()
    }
    this.getTotal()
  },
  methods: {
    getTotal () {
      let ret = 0
      this.detailItemList.map(item => {
        ret = ret + (item.itemAmount || 0)
        delete item.id
      })
      this.$emit('updateItemAmount', ret.toFixed(2))
    },
    addItem () {
      this.detailItemList.push({
        itemName: '',
        itemAmount: ''
      })
    },
    delItem (row, index) {
      this.detailItemList.splice(index, 1)
      this.getTotal()
    }
  }
}
</script>

<style>
</style>
