<template>
  <a-modal v-model="visible" destroy-on-close :width="1100" :title="title">
    <span slot="title" :class="$style.modalTitle"
      >{{ title }} <a-icon type="question-circle" @click="openDocs('事件管理')"
    /></span>
    <template slot="footer">
      <a-button @click="visible = false">退出</a-button>
    </template>
    <a-tabs v-model="activeTab" class="sd-has-table">
      <a-tab-pane key="frontend" tab="前端">
        <sd-data-table
          ref="dataTable"
          data-url="api/framework/v1/page/businessList"
          :columns="columns"
          :actions="actions"
          show-selection
          :process-req="
            (req) => {
              req.data.formId = 'onlFormFrontMethod'
              return req
            }
          "
          :filter-expressions="filterExpressions"
          :search-fields="['methodName']"
          @rowClick="rowClick"
        />
      </a-tab-pane>
      <a-tab-pane key="backend" tab="后端">
        <sd-data-table
          ref="dataTable"
          data-url="api/framework/v1/page/businessList"
          :columns="columns"
          :actions="actions"
          show-selection
          :process-req="
            (req) => {
              req.data.formId = 'onlFormMethod'
              return req
            }
          "
          :filter-expressions="filterExpressions"
          :search-fields="['methodName']"
          @rowClick="rowClick"
        />
      </a-tab-pane>
    </a-tabs>

    <!-- 事件表单 -->
    <a-modal
      v-model="detailModal"
      destroy-on-close
      :title="title"
      :width="900"
      ok-text="保存"
      cancel-text="退出"
      :confirm-loading="confirmLoading"
      @ok="saveEvent"
      @cancel="() => (detailModal = false)"
    >
      <component
        :is="formComponent"
        ref="formComponent"
        :events-define="eventsDefine[activeTab]"
        :form-data="curEvent"
        @updateEventsDefine="(events) => (eventsDefine[activeTab] = events)"
      />
    </a-modal>
  </a-modal>
</template>

<script>
import { openDocs } from '@/common/docs/docs-tool'
import { Modal } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import PageService from '@/common/services/page-service'
import ApplicationService from './application-service'
import SdEventsBackendForm from './sd-events-backend-form.vue'
import SdEventsFrontendForm from './sd-events-frontend-form.vue'
import components from './_import-components/sd-events-manage-import'

export default {
  name: 'SdEventsManage',
  components,
  data() {
    return {
      visible: false,
      detailModal: false,
      columns: [
        {
          title: '事件名称',
          dataIndex: 'methodName',
          sdClickable: true,
          sorter: true,
        },
        {
          title: '事件编码',
          dataIndex: 'methodCode',
          width: '180px',
        },
        {
          title: '排序号',
          dataIndex: 'sortNumber',
          defaultSortOrder: 'ascend',
          width: '120px',
          sorter: true,
        },
        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.dateTime,
          defaultSortOrder: 'descend',
          width: '200px',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: 'onlFormMethod-create',
          type: TableActionTypes.primary,
          callback: this.newEvent,
        },
        {
          label: '删除',
          id: 'delete',
          permission: 'onlFormMethod-delete',
          type: TableActionTypes.batch,
          callback: this.deleteEvent,
        },
      ],
      appModuleId: '',
      formId: '',
      appId: '',
      title: '事件管理',
      confirmLoading: false,
      curEvent: null,
      activeTab: 'frontend',
      eventsDefine: {
        frontend: {},
        backend: [],
      },
      isFlow: false,
    }
  },
  computed: {
    filterExpressions() {
      return [
        {
          dataType: 'str',
          name: 'formId',
          op: 'eq',
          stringValue: this.formId,
        },
      ]
    },
    formComponent() {
      return this.activeTab === 'frontend' ? SdEventsFrontendForm : SdEventsBackendForm
    },
  },
  methods: {
    openDocs,
    show(data) {
      this.appId = data.appId
      this.appModuleId = data.id
      this.formId = data.formId
      this.isFlow = data.isFlow
      this.initd()
      this.visible = true
    },
    initd() {
      this.activeTab = 'frontend'
      this.curEvent = null
    },
    rowClick(record) {
      // 获取事件数据
      ApplicationService.getEventInfo(this.activeTab, { id: record.id }).then((res) => {
        this.curEvent = res.data
        this.detailModal = true
      })
    },
    newEvent() {
      this.curEvent = null
      this.detailModal = true
    },
    saveEvent() {
      const form = this.$refs.formComponent
      form.validate().then((flag) => {
        if (flag) {
          this.confirmLoading = true
          const formData = this.curEvent || {}
          Object.assign(formData, form.getSaveData())
          // 新增时，赋值formId
          if (!this.curEvent) {
            formData.formId = this.formId
          }
          ApplicationService.saveEvent(this.activeTab, formData)
            .then((res) => {
              if (res.status === 200) {
                this.detailModal = false
                this.$refs.dataTable.refresh()
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    deleteEvent(keys) {
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            let p
            const params = { ids: keys.join(',') }
            if (this.activeTab === 'frontend') {
              p = PageService.delete(params, 'onlFormFrontMethod')
            } else {
              p = ApplicationService.deleteEvents(params)
            }
            p.then(() => {
              this.$refs.dataTable.clearSelection()
              this.$refs.dataTable.refresh()
            }).finally(() => {
              resolve(true)
            })
          },
          onCancel: () => {
            resolve(false)
          },
        })
      })
    },
  },
  provide() {
    return {
      SdEventsManage: this,
    }
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.modal-title {
  position: relative;
  z-index: 1;
  :global .anticon {
    cursor: pointer;
  }
}
</style>
