<template>
  <a-card>
    <a-tabs v-model="activeTab" @change="tabChange">
      <a-tab-pane v-if="showAllApp" key="allApp" :tab="allAppTab">
        <sd-application-list
          ref="allApp"
          :filter-expressions="expressionAll"
          list-type="all"
          @appDeleted="appDeleted"
        />
      </a-tab-pane>
      <a-tab-pane key="myApp" :tab="myAppTab">
        <sd-application-list
          ref="myApp"
          :filter-expressions="expressionMine"
          list-type="my"
          @appDeleted="appDeleted"
        />
      </a-tab-pane>
      <a-tab-pane key="myMaintained" :tab="maintainedAppTab">
        <sd-application-list
          ref="myMaintained"
          :filter-expressions="expressionMaintained"
          list-type="maintained"
          @appDeleted="appDeleted"
        />
      </a-tab-pane>
      <a-tab-pane v-if="showShareApp" key="shareApp" :tab="shareAppTab">
        <sd-application-list
          ref="shareApp"
          :form-id="'weAppNode'"
          :filter-expressions="expressionShare"
          list-type="share"
          @appDeleted="appDeleted"
        />
      </a-tab-pane>
    </a-tabs>
    <div :class="$style.extra">
      <a-button type="primary" @click="createApp">创建应用</a-button>
      <a-button :disabled="importing" @click="() => (visible = true)">导入应用</a-button>
      <a-button @click="() => (categoryVisible = true)" v-text="categoryMgrLabel" />
      <div :class="$style.searchdiv">
        <a-input-search
          v-model="searchValue"
          placeholder="请输入应用名称"
          allow-clear
          @search="onSearch"
        />
      </div>
    </div>
    <!-- 导入应用 -->
    <a-modal
      :footer="null"
      title="导入应用"
      :visible="visible"
      :width="650"
      destroy-on-close
      :mask-closable="false"
      @cancel="visible = false"
    >
      <a-form>
        <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
          <sd-attachment :max="1" :group-id="filegroupid()" accept=".gz" @change="importfromfile">
          </sd-attachment>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分类管理 -->
    <a-modal
      :footer="null"
      :title="categoryMgrLabel"
      :visible="categoryVisible"
      :width="800"
      destroy-on-close
      :mask-closable="false"
      @cancel="categoryVisible = false"
    >
      <sd-data-table-ex
        ref="dataTable"
        form-id="weAppGroup"
        page-id="app/appgroup/weAppGroup"
        :columns="columns"
        show-selection
        :actions="actions"
        :search-fields="['name']"
      >
        <template v-slot:form>
          <sd-form-item name="name" />
          <sd-form-item name="sortNumber" />
          <!-- 父节点默认为根节点 -->
          <sd-form-item name="parentId" hidden :input-props="{ defaultValue: '0' }" />
        </template>
      </sd-data-table-ex>
    </a-modal>

    <!-- 创建应用 -->
    <sd-detail-modal
      ref="appDetail"
      :record-id="null"
      page-id="app/app/weApp"
      :modal-props="{ width: 800 }"
      @saved="appSaved"
    >
      <sd-application-info-form slot-scope="scope" v-bind="scope" />
    </sd-detail-modal>
    <SdImportConfig ref="importConfig" @configOk="(value) => importAppSubmit(1, value)" />
  </a-card>
</template>

<script>
import { message, Modal } from '@/common/one-ui'
import errorUtil from '@/common/services/error-util'
import TableActionTypes from '@/common/services/table-action-types'
import storeMixin from '@/common/store-mixin'
import SdImportConfig from './components/sd-important-config.vue'
import ApplicationService from './application-service'
import components from './_import-components/sd-application-center-import'

export default {
  name: 'SdApplicationCenter',
  metaInfo: {
    title: '应用中心',
  },
  components: { SdImportConfig, ...components },
  mixins: [storeMixin],
  data() {
    return {
      activeTab: 'allApp',
      searchValue: '',
      searchMine: '',
      searchMaintained: '',
      searchAll: '',
      searchShare: '',
      categoryMgrLabel: '分类管理',
      categoryVisible: false,
      columns: [
        {
          title: '分类名称',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '排序号',
          dataIndex: 'sortNumber',
          defaultSortOrder: 'ascend',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete,
        },
      ],
      initdCount: false,
      appCount: {},
      visible: false,
      msgKey: 'import',
      loadingMsg: null,
      importing: false,
    }
  },
  computed: {
    allAppTab() {
      return this.initdCount ? `全部应用(${this.appCount.allCount || 0})` : '全部应用'
    },
    myAppTab() {
      return this.initdCount ? `我的应用(${this.appCount.creatorCount || 0})` : '我的应用'
    },
    maintainedAppTab() {
      return this.initdCount ? `我维护的(${this.appCount.maintainerCount || 0})` : '我维护的'
    },
    shareAppTab() {
      return this.initdCount ? `公共应用(${this.appCount.appNodeCount || 0})` : '公共应用'
    },
    showAllApp() {
      return !!this.userPerms['weApp-all']
    },
    showShareApp() {
      return !!this.userPerms['weApp-all']
    },
    expressionShare() {
      const expression = []
      if (this.searchShare) {
        return expression.concat(this.getExpressions(this.searchShare))
      } else {
        return expression
      }
    },
    expressionMaintained() {
      const expression = [
        {
          dataType: 'str',
          name: 'maintainerAccounts',
          op: 'like',
          stringValue: `@@{currentUser}@@`,
        },
      ]
      if (this.searchMaintained) {
        return expression.concat(this.getExpressions(this.searchMaintained))
      } else {
        return expression
      }
    },
    expressionMine() {
      const expression = [
        {
          dataType: 'str',
          name: 'creatorAccount',
          op: 'eq',
          stringValue: '@@{currentUser}@@',
        },
      ]
      if (this.searchMine) {
        return expression.concat(this.getExpressions(this.searchMine))
      } else {
        return expression
      }
    },
    expressionAll() {
      if (this.searchAll) {
        return this.getExpressions(this.searchAll)
      } else {
        return []
      }
    },
  },
  created() {
    this.activeTab = this.showAllApp ? 'allApp' : 'myApp'
    this.initdAppCount()
  },
  methods: {
    initdAppCount() {
      ApplicationService.getAppCount()
        .then((res) => {
          this.appCount = res.data
        })
        .finally(() => {
          this.initdCount = true
        })
    },
    tabChange(key) {
      this.searchValue =
        key === 'allApp'
          ? this.searchAll
          : key === 'myApp'
          ? this.searchMine
          : key === 'myMaintained'
          ? this.searchMaintained
          : this.searchShare
    },
    onSearch(value) {
      const sValue = value.trim()
      switch (this.activeTab) {
        case 'allApp':
          this.searchAll = sValue
          break
        case 'myApp':
          this.searchMine = sValue
          break
        case 'myMaintained':
          this.searchMaintained = sValue
          break
        case 'shareApp':
          this.searchShare = sValue
          break
        default:
          break
      }
    },
    getExpressions(value) {
      return value
        ? [
            {
              dataType: 'str',
              name: 'appName',
              op: 'like',
              stringValue: `%${value}%`,
            },
          ]
        : []
    },
    createApp() {
      this.$refs.appDetail.show()
    },
    appSaved(data) {
      this.$refs[this.activeTab].queryAppList()
      this.initdAppCount()
      // 创建应用后，直接进入应用
      const fields = data?.pageFormData.pageFieldInfos
      const appId = fields.find((f) => f.name === 'id')?.value
      const appName = fields.find((f) => f.name === 'appName')?.value
      this.$router.push({ path: 'sd-application-manage', query: { appId, appName } })
    },
    appDeleted() {
      this.initdAppCount()
    },
    filegroupid() {
      return 'app_' + new Date().getTime() + '_' + (Math.floor(Math.random() * 100) + 1)
    },
    importfromfile(data) {
      this.fileId = data[0].code
      this.importAppSubmit(0)
      this.importing = true
      this.visible = false
    },
    importAppSubmit(type, params) {
      let form = {}
      let moduleImportParams
      if (params) {
        form = params.appConfigForm
        moduleImportParams = params.moduleImportParams
      }
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '正在导入，请稍候...',
        duration: 0,
      })
      ApplicationService.importApp({
        fileId: this.fileId,
        type,
        ...form,
        moduleImportParams,
      })
        .then((res) => {
          const code = res.data?.code
          const msg = res.data?.message
          const data = res.data.data
          let appConfigForm
          if (data) {
            appConfigForm = {
              importPermission: data.importPermission,
              importAutoNumber: data.importAutoNumber,
              importDict: data.importDict,
              importMenu: data.importMenu,
              importTreeDict: data.importTreeDict,
              importPrintTemp: data.importPrintTemp,
              importRedHead: data.importRedHead,
            }
          }
          const moduleImportParams =
            code === 99
              ? data.moduleImportParams.map((param, index) => {
                  param.key = index + 1
                  if (param.flowConfigs) {
                    param.flowConfigs = param.flowConfigs.map((config) => {
                      config.key = param.moduleId + config.configId
                      config.parentKey = index + 1
                      config.disabled = false
                      return config
                    })
                  }
                  return param
                })
              : []
          switch (code) {
            case -1:
              message.error({
                key: this.msgKey,
                content: '导入出错：' + msg || '原因未知',
              })
              this.importing = false
              break
            case 2:
              Modal.confirm({
                content: msg.split('\r\n').map((item) => (item ? <div>{item}</div> : '')),
                okText: '确认',
                okType: 'danger',
                onOk: () => {
                  this.importAppSubmit(1)
                },
                onCancel: () => {
                  this.loadingMsg?.()
                  this.importing = false
                },
              })
              break
            case 3:
              message.warn({
                key: this.msgKey,
                content: () => {
                  return msg
                    .split('\r\n')
                    .map((item, index) =>
                      item && index !== 0 ? (
                        <div>{item}</div>
                      ) : item && index === 0 ? (
                        <span>{item}</span>
                      ) : (
                        ''
                      )
                    )
                },
              })
              this.importing = false
              this.$refs.allApp?.refresh()
              this.$refs.myApp?.refresh()
              break
            case 4:
              Modal.confirm({
                content: msg.split('\r\n').map((item) => (item ? <div>{item}</div> : '')),
                okText: '确认',
                okType: 'danger',
                onOk: () => {
                  this.importAppSubmit(3)
                },
                onCancel: () => {
                  this.loadingMsg?.()
                  this.importing = false
                },
              })
              break
            case 99:
              this.loadingMsg?.()
              this.importing = false
              this.$refs.importConfig.show({ appConfigForm, moduleImportParams })
              break
            default:
              message.success({ key: this.msgKey, content: '导入成功！' })
              this.importing = false
              this.$refs.allApp?.refresh()
              this.$refs.myApp?.refresh()
          }
        })
        .catch((err) => {
          this.importing = false
          message.error({
            key: this.msgKey,
            content: errorUtil.getMessage(err) || '出错了！',
          })
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.extra {
  position: absolute;
  top: 22px;
  right: 16px;
  display: flex;
  :global(.ant-btn) {
    margin-left: 10px;
  }
}
.searchdiv {
  margin-left: 10px;
  :global(.ant-input-search) {
    width: 200px;
  }
}

.step {
  padding: 0 90px;
  margin-bottom: 20px;
}
</style>
