<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline :label-width="'100px'">
      <el-form-item :label="$t('ec.app.name')" prop="appName">
        <el-input v-model="queryParams.appName" type="text" :placeholder="$t('ec.app.name')" />
      </el-form-item>
      <el-form-item label="APPID" prop="appId">
        <!--        <ec-select v-model="queryParams.typeApp" dict-type="typeApp" />-->
        <el-input v-model="queryParams.appId" type="text" placeholder="appId" />
      </el-form-item>
      <!--      <el-form-item :label="$t('ec.app.authType')" prop="typeAuth">-->
      <!--        <ec-select v-model="queryParams.typeAuth" dict-type="authType" />-->
      <!--      </el-form-item>-->
      <el-form-item class="searchItem" :label-width="'50px'">
        <el-button type="primary" @click="queryData">{{ $t('ec.table.query') }}</el-button>
        <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <vxe-grid
      ref="vxe"
      highlight-hover-row
      border
      resizable
      sync-resize
      auto-resize
      max-height="1000"
      class="vxe-table-element"
      show-overflow
      show-header-overflow
      :loading="loading"
      :start-index="(page.currentPage - 1) * page.pageSize"
      :pager-config="page"
      :sort-config="{ trigger: 'cell' }"
      :columns="columns"
      :data="tableData"
      :toolbar="tableToolbar"
      @sort-change="sortMethod"
      @page-change="handlePageChange"
    >
      <template v-slot:toolbar_buttons>
        <el-button v-permission="['app:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['app:edit']" type="warning" :disabled="!onlyOne" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['app:delete']" type="danger" :disabled="oneMore" @click="remove()">{{ $t('ec.table.delete') }}</el-button>
        <!--        <el-button @click="handleReset">{{ $t('ec.table.reset') }}</el-button>-->
        <el-button v-permission="['app:import']" type="primary" @click="baseImportVisible = true">{{ $t('ec.table.importBase') }}</el-button>
        <el-button v-permission="['app:export']" type="success" @click="exportBaseData">{{ $t('ec.table.exportBase') }}</el-button>
      </template>

      <!--      <template v-slot:sort_operation="{ row }">-->
      <!--        <el-input-number v-model="row.sortNum" @change="updateSort(row)" />-->
      <!--      </template>-->
      <template v-slot:flagIp_operation="{ row }">
        <el-switch v-model="row.flagIp" :disabled="!checkPermission(['app:edit'])" active-color="#13ce66" active-value="1" inactive-value="0" @change="updateStatus(row, 'flagIp')" />
      </template>
      <!--      <template v-slot:flagLLog_operation="{ row }">-->
      <!--        <el-switch v-model="row.flagLLog" :disabled="!checkPermission(['app:edit'])" active-color="#13ce66" active-value="1" inactive-value="0" @change="updateStatus(row, 'flagLLog')" />-->
      <!--      </template>-->
      <!--      <template v-slot:flagLogOpt_operation="{ row }">-->
      <!--        <el-switch v-model="row.flagLogOpt" :disabled="!checkPermission(['app:edit'])" active-color="#13ce66" active-value="1" inactive-value="0" @change="updateStatus(row, 'flagLogOpt')" />-->
      <!--      </template>-->
      <!--      <template v-slot:status_operation="{ row }">-->
      <!--        <el-switch v-model="row.status" :disabled="!checkPermission(['app:edit'])" active-color="#13ce66" active-value="1" inactive-value="0" @change="updateStatus(row, 'status')" />-->
      <!--      </template>-->
      <template v-slot:auditStatus_operation="{ row }">
<!--        <div v-permission="['app:edit']" style="width: 40px" @click="updateAuditStatus(row)">-->
          <el-switch :value="row.auditStatus" :disabled="!enableAudit(row.auditStatus)" active-color="#13ce66" active-value="agree" @change="updateAuditStatus(row)"/>
<!--        <el-button v-permission="['app:edit']" size="mini" v-if="enableAudit(row.auditStatus)" @click="updateAuditStatus(row)">审核</el-button>-->
<!--        </div>-->
      </template>
      <template v-slot:fromExternal_operation="{ row }">
        <el-switch v-model="row.fromExternal" :disabled="!checkPermission(['app:edit'])" active-color="#13ce66" active-value="1" inactive-value="0" @change="updateStatus(row, 'fromExternal')" />
      </template>

      <template v-slot:operation="{ row }">
        <!--        <el-button v-permission="['app:findSecret']" size="mini" @click="findSecret(row.appId)">{{ $t('ec.app.findSecret') }}</el-button>-->
        <!--        <el-button v-permission="['app:generateSecret']" size="mini" type="primary" @click="generateSecret(row.appId)">-->
        <!--          {{ $t('ec.app.generateSecret') }}-->
        <!--        </el-button>-->
        <el-button v-permission="['app:view']" size="mini" @click="view(row.appId)">{{ $t('ec.table.view') }}</el-button>
        <el-button v-permission="['app:findSecret']" size="mini" type="primary" @click="findSecret(row.appId)">
          {{ $t('ec.app.appSecret') }}
        </el-button>
        <el-button v-permission="['app:tenant']" size="mini" type="success" @click="saasTenant(row)">{{ $t('ec.table.linkTenant') }}</el-button>
        <el-button v-permission="['app:edit']" size="mini" type="warning" @click="edit(row.appId)">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['app:delete']" size="mini" type="danger" @click="remove(row.appId)">{{ $t('ec.table.del') }}</el-button>
      </template>
    </vxe-grid>

    <ec-import
      :upload-url="baseImportUrl"
      :tpl-url="baseTplUrl"
      :title="$t('ec.table.importBase')"
      :visible="baseImportVisible"
      @onSuccess="getData"
      @close="baseImportVisible = false"
    >
      <template v-slot:extra_params="{ extraParams }">
        <el-form-item :label="$t('ec.import.strategy')">
          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: $t('ec.import.ignore')}, {value: 'overwrite', label: $t('ec.import.overwrite') } ]" />
        </el-form-item>
      </template>
    </ec-import>

    <detail ref="sysrRegisterAppDialog" @refreshDataList="getData" />
    <app-tenant-modal ref="appTenantModal" />

    <app-export-modal ref="appExportModal" @refresh="getData" />

    <app-audit-modal ref="appAuditModal" @refresh="getData" />

    <el-dialog :title="appSecretTitle" :visible.sync="appSecretVisible" :close-on-click-modal="false" append-to-body top="4%">
      <el-input v-model="appSecret" style="width:400px;max-width:100%;" />
      <el-button v-if="!appSecretBlank" style="margin-left: 20px" type="primary" icon="el-icon-document" @click="handleClipboard(appSecret,$event)">
        {{ $t('ec.table.copy') }}
      </el-button>
      <el-button v-permission="['app:generateSecret']" style="margin-left: 20px" size="mini" type="danger" @click="generateSecret(appIdSecret)">
        {{ $t('ec.app.generateSecret') }}
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData, remove, updateStatus, updateFlagIp, updateFlagLLog, updateFlagLogOpt, updateSort, updateFromExternal, generateSecret, findSecret } from 'ecip-web/api/vue/app/sysrRegisterAppApi'
import Detail from './components/detail'
import AppTenantModal from './components/appTenantModal'
import AppExportModal from './components/appExportModal'
import clipboard from 'ecip-web/utils/clipboard'
import AppAuditModal from './components/appAuditModal'

export default {
  name: 'VueAppSysrRegisterAppView',
  components: { AppAuditModal, AppTenantModal, AppExportModal, Detail },
  mixins: [...mixin],
  data() {
    return {
      importVisible: false,
      baseImportVisible: false,
      loading: false,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      baseImportUrl: 'api/v1/app/sysrRegisterApp/importBaseData',
      baseTplUrl: 'api/v1/app/sysrRegisterApp/baseDataTemplate',
      baseExportUrl: `api/v1/app/sysrRegisterApp/exportBaseData`,
      tableToolbar: {
        id: 'vue.app.sysrRegisterAppView-toolbar',
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        align: 'left',
        pageSizes: [10, 20, 50, 100, 200, 500],
        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
        perfect: true,
        order: 'asc',
        field: 'appId'
      },
      selections: [],
      tableData: [],
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'APPID', field: 'appId', fixed: 'left', minWidth: 100, sortable: true },
        { title: 'ec.app.name', field: 'appName', fixed: 'left', minWidth: 180 },
        { title: 'ec.table.sort', field: 'sortNum', minWidth: 100, sortable: true },
        { title: 'ec.app.externalFlag', field: 'fromExternal', minWidth: 180, slots: { default: 'fromExternal_operation' }},
        { title: 'ec.app.type', field: 'typeApp', minWidth: 180, formatter: ['dict', 'typeApp'] },
        // { title: 'ec.app.authType', field: 'typeAuth', minWidth: 180, formatter: ['dict', 'authType'] },
        // { title: 'ec.table.sort', field: 'sortNum', minWidth: 180, sortable: true, slots: { default: 'sort_operation' }},
        // { title: 'ec.app.lLogFlag', field: 'flagLLog', minWidth: 180, slots: { default: 'flagLLog_operation' }},
        // { title: 'ec.app.logOptFlag', field: 'flagLogOpt', minWidth: 180, slots: { default: 'flagLogOpt_operation' }},
        // { title: 'ec.table.version', field: 'rsvn', minWidth: 100, showOverflow: true },
        { title: 'ec.app.url', field: 'url', minWidth: 100, showOverflow: true },
        { title: 'ec.app.proposer', field: 'proposer', minWidth: 100, showOverflow: true },
        { title: 'ec.app.auditStatus', field: 'auditStatus', minWidth: 180, slots: { default: 'auditStatus_operation' }},
        { title: 'ec.app.ipFlag', field: 'flagIp', minWidth: 180, slots: { default: 'flagIp_operation' }},
        // { title: 'ec.table.enableStatus', field: 'status', minWidth: 180, slots: { default: 'status_operation' }},
        // { title: 'ec.app.icon', field: 'icon', minWidth: 100, showOverflow: true },
        { title: 'ec.table.actions', minWidth: 400, fixed: 'right', align: 'center', slots: { default: 'operation' }}
      ],
      queryParams: {
        appId: '',
        appName: ''
        // typeApp:'',
        // typeAuth:''
      },
      appSecretVisible: false,
      appSecret: '',
      appSecretTitle: '',
      appIdSecret: '',
      appSecretBlank: false
    }
  },
  mounted() {
    this.$watch(this.$refs.vxe.getCheckboxRecords, (newValue, oldValue) => {
      this.selections = newValue
      this.onlyOne = this.selections.length === 1
      this.oneMore = this.selections.length > 0
    })
  },
  created() {
    this.getData()
  },
  methods: {
    async updateSort(row) {
      try {
        this.loading = true
        const { message } = await updateSort(row.appId, { sortNum: row.sortNum })
        this.$notify.success(message)
        await this.getData()
      } finally {
        this.loading = false
      }
    },
    async updateStatus(row, field) {
      try {
        this.loading = true
        let msg = ''
        if (field === 'flagIp') {
          const { message } = await updateFlagIp(row.appId, { flagIp: row.flagIp })
          msg = message
        } else if (field === 'flagLLog') {
          const { message } = await updateFlagLLog(row.appId, { flagLLog: row.flagLLog })
          msg = message
        } else if (field === 'flagLogOpt') {
          const { message } = await updateFlagLogOpt(row.appId, { flagLogOpt: row.flagLogOpt })
          msg = message
        } else if (field === 'status') {
          const { message } = await updateStatus(row.appId, { status: row.status })
          msg = message
        } else if (field === 'fromExternal') {
          const { message } = await updateFromExternal(row.appId, { fromExternal: row.fromExternal })
          msg = message
        }
        this.$notify.success(msg)
        await this.getTreeData()
      } finally {
        this.loading = false
      }
    },
    async getData() {
      // 每次查询初始化checkbox selections
      this.selections = []
      this.loading = true
      const { data } = await getData(Object.assign({}, { size: this.page.pageSize, current: this.page.currentPage,
        order: this.page.order, field: this.page.field }, this.queryParams))
      this.tableData = data.records
      this.page.total = data.total
      this.loading = false
    },
    sortMethod({ column, property, order }) {
      this.page.field = property
      this.page.order = order
      this.getData()
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    add() {
      this.$refs.sysrRegisterAppDialog.init('add')
    },
    edit(id) {
      const dataId = id || this.selections[0].appId
      this.$refs.sysrRegisterAppDialog.init('edit', dataId)
    },
    view(id) {
      const dataId = id || this.selections[0].appId
      this.$refs.sysrRegisterAppDialog.init('view', dataId)
    },
    async findSecret(id) {
      try {
        const { data } = await findSecret(id)
        this.appIdSecret = id
        this.appSecret = data
        this.appSecretBlank = false
        if (data == null || data === '') {
          this.appSecretBlank = true
        }
        this.appSecretTitle = this.$t('ec.app.searchSecret')
        this.appSecretVisible = true
      } finally {
        this.loading = false
      }
    },
    generateSecret(id) {
      this.$confirm(this.$t('ec.app.secretConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        this.loading = true
        try {
          const { data } = await generateSecret(id)
          this.appSecret = data
          this.appSecretTitle = this.$t('ec.app.generateSecretSuccess')
          this.appSecretVisible = true
        } finally {
          this.appSecretBlank = false
          this.loading = false
        }
      })
    },
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    saasTenant(row) {
      this.$refs.appTenantModal.init(row)
    },
    remove(id) {
      this.$confirm(this.$t('ec.message.delConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        let deleteIds = []
        if (id) {
          deleteIds.push(id)
        } else {
          deleteIds = this.selections.map(item => item.appId)
        }
        this.loading = true
        try {
          await remove(deleteIds)
          await this.getData()
          this.$notify.success(this.$t('ec.message.delSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    exportBaseData() {
      this.$refs.appExportModal.init()
    },
    queryData() {
      Object.assign(this.$data.page, this.$options.data().page)
      this.getData()
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getData()
    },
    enableAudit(auditStatus) {
      if (this.superAdmin) {
        return auditStatus !== 'agree'
      }
      return false
    },
    updateAuditStatus(row) {
      this.$refs.appAuditModal.init(row)
    }
  }
}
</script>

<style scoped>

</style>
