<template>
  <m-dialog title="同级机构合并" ref="dialog" @sure="onSure">
    <m-form :items="formItems" v-model="formValues" v-loading="loading">
      <template #organizationName>
        <el-tag>{{ formValues.organizationName }}</el-tag>
      </template>
    </m-form>
  </m-dialog>
</template>

<script>
import { getOrganizationByType, margeOrganization } from '@/api/system'
export default {
  name: 'organizationMerge',
  data () {
    return {
      items: [],
      formValues: {},
      loading: false
    }
  },
  computed: {
    formItems () {
      return [
        {
          label: '当前机构',
          prop: 'organizationName'
        },
        {
          label: '目标机构',
          prop: 'slaveOrganizationNos',
          type: 'select',
          options: {
            filterable: true,
            placeholder: '请选择被合并的机构',
            multiple: true,
            items: this.items,
            labelText: 'organizationName',
            labelValue: 'organizationNo'
          }
        }
      ]
    }
  },
  methods: {
    async open (item) {
      this.formValues.organizationName = item.name
      this.formValues.masterOrganizationNo = item.value
      this.formValues.slaveOrganizationNos = []
      this.$refs.dialog.open()
      try {
        const { data } = await getOrganizationByType({
          entity: {
            organizationCategory: item.organization.organizationCategory
          },
          page: {
            current: 1,
            size: 1000
          }
        })
        this.items = data.records.filter(e => e.organizationNo !== item.value)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    async onSure () {
      this.loading = true
      const { masterOrganizationNo, slaveOrganizationNos } = this.formValues
      try {
        await margeOrganization({
          masterOrganizationNo,
          slaveOrganizationNos
        })
        this.$message.success('合并成功')
        this.$refs.dialog.close()
        this.$emit('refresh')
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
