<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline label-width="100px">
      <el-form-item :label="$t('ec.errorLog.tenant')" v-if="enableTenant" prop="tenantId">
        <ec-tenant v-model="queryParams.tenantId" clearable filterable @change="queryData" />
      </el-form-item>
      <el-form-item :label="$t('ec.app.app')" prop="appId">
        <ec-register-app v-model="queryParams.appId" :tenantId="queryParams.tenantId" clearable filterable @change="queryData" />
      </el-form-item>
      <el-form-item :label="$t('ec.user.insider')" prop="insider">
        <el-select v-model="queryParams.insider" :placeholder="$t('ec.log.viewAll')" clearable>
          <el-option :label="$t('ec.log.onlyView') + $t('ec.user.insider')" :value="true" />
          <el-option :label="$t('ec.log.notView') + $t('ec.user.insider')" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.user')" prop="userId" v-permission="['user:list']">
        <!--        <el-input v-model="queryParams.userId" type="text" placeholder="用户Id" />-->
        <ec-contact v-model="queryParams.userId" />
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.serverIp')" prop="serverIp">
        <el-input v-model="queryParams.serverIp" type="text" :placeholder="$t('ec.errorLog.serverIp')" />
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.remoteIp')" prop="remoteIp">
        <el-input v-model="queryParams.remoteIp" type="text" :placeholder="$t('ec.errorLog.remoteIp')" />
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.requestUri')" prop="requestUri">
        <el-input v-model="queryParams.requestUri" type="text" :placeholder="$t('ec.errorLog.requestUri')" />
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.method')" prop="method">
        <el-input v-model="queryParams.method" type="text" :placeholder="$t('ec.errorLog.method')" />
      </el-form-item>
      <el-form-item :label="$t('ec.errorLog.methodName')" prop="methodName">
        <el-input v-model="queryParams.methodName" type="text" :placeholder="$t('ec.errorLog.methodName')" />
      </el-form-item>
      <el-form-item :label="$t('ec.log.optTime')" prop="searchDate">
        <el-date-picker
          v-model="queryParams.searchDate"
          type="datetimerange"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          :range-separator="$t('ec.date.rangeSeparator')"
          :start-placeholder="$t('ec.date.startDate')"
          :end-placeholder="$t('ec.date.endDate')"
        />
      </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
      show-overflow
      max-height="1000"
      class="vxe-table-element"
      :loading="loading"
      :start-index="(page.currentPage - 1) * page.pageSize"
      :sort-config="{ trigger: 'cell' }"
      :pager-config="page"
      :columns="columns"
      :data="tableData"
      :toolbar="tableToolbar"
      @sort-change="sortMethod"
      @page-change="handlePageChange"
    >
      <template v-slot:user_default="{ row }">
        <ec-user-modal :value="row.userId" readonly />
      </template>

      <template v-slot:tenant_default="{ row }">
        <span>{{ tenantTranslate(row.tenantId) }}</span>
      </template>

      <template v-slot:app_default="{ row }">
        <span>{{ appTranslate(row.appId) }}</span>
      </template>

      <template v-slot:detail_content="{ row }">
        <el-form>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.user')">
                <ec-user-modal :value="row.userId" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="enableTenant">
              <el-form-item :label="$t('ec.errorLog.tenant')">
                <span>{{ tenantTranslate(row.tenantId) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.app.app')"><span>{{ appTranslate(row.appId) }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.serviceId')"><span>{{ row.serviceId }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.serverHost')"><span>{{ row.serverHost }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.serverIp')"><span>{{ row.serverIp }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.env')"><span>{{ row.env }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.method')"><span>{{ row.method }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.requestUri')"><span>{{ row.requestUri }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.stackTrace')">
                <el-input type="textarea" :value="row.stackTrace" disabled :autosize="{minRows: 3, maxRows: 5}" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.errorMsg')"><el-input type="textarea" :value="row.message" disabled :autosize="{minRows: 3, maxRows: 5}" /></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.requestParam')"><el-input type="textarea" :value="row.params" disabled :autosize="{minRows: 3, maxRows: 5}" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.exceptionName')"><span>{{ row.exceptionName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.lineNumber')"><span>{{ row.lineNumber }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.remoteIp')"><span>{{ row.remoteIp }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.userAgent')">
                <span>{{ row.userAgent }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.methodClass')"><span>{{ row.methodClass }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.methodName')"><span>{{ row.methodName }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.executionTime')"><span>{{ row.executionTime }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.table.createBy')"><ec-user-modal :value="row.createBy && row.createBy.id" readonly /></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.createTime')"><span>{{ dateFormat(row.createTime) }}</span></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>

      <template v-slot:toolbar_buttons>
        <el-button v-permission="['ecipWebErrorLog:export']" type="primary" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
<!--        <el-button @click="getData">{{ $t('ec.table.refresh') }}</el-button>-->
        <el-button @click="showSearch = !showSearch">{{ $t('ec.table.search') }}</el-button>
      </template>
    </vxe-grid>

<!--    <ec-import-->
<!--      :upload-url="importUrl"-->
<!--      :tpl-url="tplUrl"-->
<!--      title="错误日志表数据导入"-->
<!--      :visible="importVisible"-->
<!--      @onSuccess="getData"-->
<!--      @close="importVisible = false"-->
<!--    >-->
<!--      <template v-slot:extra_params="{ extraParams }">-->
<!--        <el-form-item label="是否生成新主键">-->
<!--          <ec-radio-group v-model="extraParams.isNewPk" :ec-data="[ {value: false, label: '否'}, {value: true, label: '是' } ]" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="导入策略">-->
<!--          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: '忽略'}, {value: 'update', label: '更新' } ]" />-->
<!--        </el-form-item>-->
<!--      </template>-->
<!--    </ec-import>-->

  </div>
</template>

<script>
import permissionMixin from 'ecip-web/utils/permission-mixin'
import { getData } from 'ecip-web/api/vue/log/ecipErrorLogApi'
import { download } from 'ecip-web/utils'
import { findTenantList } from 'ecip-web/api/vue/tenant/saasTenantApi'
import { getAppList } from 'ecip-web/api/vue/app/sysrRegisterAppApi'
import checkPermission from 'ecip-web/utils/permission' // 权限判断指令
import XEUtils from 'xe-utils'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']

export default {
  name: 'WebLogEcipErrorLogView',
  mixins: [permissionMixin],
  data() {
    return {
      enableTenant,
      showSearch: false,
      loading: false,
      exportUrl: 'api/v1/log/ecipErrorLog/exportExcel',
      tableToolbar: {
        id: 'web.log.ecipErrorLogView-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: 'desc',
        field: 'createTime'
      },
      tableData: [],
      appList: [],
      tenantList: [],
      columns: [
        { type: 'expand', width: 60, align: 'center', slots: { content: 'detail_content' }},
        { title: 'ec.app.name', field: 'appId', minWidth: 180, sortable: true, slots: { default: 'app_default' }},
        { title: 'ec.errorLog.user', field: 'userId', minWidth: 180, sortable: true, visible: checkPermission('user:list'), slots: { default: 'user_default' }},
        { title: 'ec.errorLog.tenant', field: 'tenantId', minWidth: 180, visible: enableTenant, sortable: true, slots: { default: 'tenant_default' }},
        { title: 'ec.errorLog.serverIp', field: 'serverIp', minWidth: 180, sortable: true },
        { title: 'ec.errorLog.requestUri', field: 'requestUri', minWidth: 180, sortable: true },
        { title: 'ec.errorLog.remoteIp', field: 'remoteIp', minWidth: 180, sortable: true },
        { title: 'ec.errorLog.createTime', field: 'createTime', minWidth: 180, sortable: true, formatter: ['date', 'yyyy-MM-dd HH:mm:ss'] }
      ],
      queryParams: {
        tenantId: '',
        appId: '',
        insider: null,
        userId: '',
        serverIp: '',
        remoteIp:'',
        requestUri: '',
        method: '',
        methodName: '',
        searchDate: []
      }
    }
  },
  created() {
    this.findDataList()
    this.getData()
  },
  methods: {
    async findDataList() {
      this.loading = true
      const res1 = await findTenantList()
      const res2 = await getAppList()
      this.tenantList = res1.data
      this.appList = res2.data
      this.loading = false
    },
    async getData() {
      // 每次查询初始化checkbox selections
      this.selections = []
      this.loading = true
      let start = null
      let end = null
      if (this.queryParams.searchDate.length > 0) {
        start = this.queryParams.searchDate[0]
        end = this.queryParams.searchDate[1]
      }
      const { data } = await getData(Object.assign({}, {
        size: this.page.pageSize,
        current: this.page.currentPage,
        field: this.page.field,
        order: this.page.order,
        start: start,
        end: end,
        insider: this.queryParams.insider
      }), this.queryParams)
      this.tableData = data.records
      this.page.total = data.total
      this.loading = false
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    sortMethod({ column, property, order }) {
      this.page.field = property
      this.page.order = order
      this.getData()
    },
    async exportExcel() {
      this.loading = true
      let start = null
      let end = null
      if (this.queryParams.searchDate.length > 0) {
        start = this.queryParams.searchDate[0]
        end = this.queryParams.searchDate[1]
      }
      await download({ url: this.exportUrl, method: 'post', params: { start, end }, data: this.queryParams })
      this.loading = false
    },
    dateFormat(date) {
      return XEUtils.toDateString(date, 'yyyy-MM-dd HH:mm:ss')
    },
    tenantTranslate(tenantId) {
      const tenant = this.tenantList.filter(item => item.id === tenantId)[0]
      return tenant && tenant.name
    },
    appTranslate(appId) {
      const app = this.appList.filter(item => item.appId === appId)[0]
      return app && app.appName
    },
    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()
    }
  }
}
</script>

<style scoped>
  /deep/ .vxe-table .vxe-body--expanded-column.col--ellipsis>.vxe-body--expanded-cell {
    white-space: normal;
  }
</style>
