<template>
  <el-container class="contact-table">
    <el-header height="auto">
      <th-form
        v-bind="form"
        :options="{
          orgNo: hostOrgOptions
        }"
        @handleSubmit="handleSubmit"
      />
      <div class="btn-wrap">
        <template v-for="(item, index) in buttons">
          <el-button :key="index" :icon="item.icon" type="default" @click="item.click">
            {{ item.label }}
          </el-button>
        </template>
      </div>
    </el-header>
    <el-main>
      <th-table
        v-bind="list"
        @handleSelectionChange="handleSelectionChange"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </el-main>
    <add-dialog
      ref="addDailog"
      :request="request"
      :host-org-options="hostOrgOptions"
      @fetchTableApi="fetchTableApi"
    />
  </el-container>
</template>
<script>
import AddDialog from './AddDialog'
import baseForm from '../../../../src/mixins/baseForm'
import baseTable from '../../../../src/mixins/baseTable'
import tableMixin from './tableMixin.js'

export default {
  components: {
    AddDialog
  },
  mixins: [baseTable, baseForm, tableMixin],
  data() {
    return {
      form: {
        isSearch: true
      },
      buttons: [
        {
          key: 'add',
          label: '新增',
          icon: 'el-icon-th-add',
          click: this.handleAdd
        },
        {
          key: 'edit',
          label: '修改',
          icon: 'el-icon-th-edit',
          click: this.handleEdit
        },
        {
          key: 'del',
          label: '删除',
          icon: 'el-icon-th-del',
          click: this.handleDel
        }
      ]
    }
  },
  methods: {
    // 点击新增
    handleAdd() {
      this.$refs.addDailog.showDialog()
    },
    // 点击修改
    handleEdit() {
      if (!this.$length(this.list.selectedRows)) {
        this.$message.warning('请选择!')
      } else if (this.list.selectedRows.length > 1) {
        this.$message.warning('请选择一个用户!')
      } else {
        this.$refs.addDailog.showDialog(this.list.selectedRows[0].userId)
      }
    },
    // 点击删除
    handleDel() {
      if (!this.$length(this.list.selectedRows)) {
        this.$message.warning('请选择!')
      } else {
        this.$confirm('确定要删除吗？', '删除', {
          type: 'warning'
        }).then(() => {
          this.fetchDelPerson()
        })
      }
    },
    // 删除
    fetchDelPerson() {
      if (this.request.fetchDelPerson) {
        const userIds = this.list.selectedRows.map(d => d.userId).join(',')
        this.loading = true
        this.request.fetchDelPerson({ userIds }).then(res => {
          this.loading = false
          if (res.data.successful) {
            this.$message.success('删除成功')
            this.fetchTableApi()
          }
        })
      }
    }
  }
}
</script>
