<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline label-width="100px">
      <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')"
        v-permission="['user:list']"
        prop="userId"
      >
        <!--        <el-input v-model="queryParams.userId" type="text" placeholder="用户ID" />-->
        <ec-contact v-model="queryParams.userId" />
      </el-form-item>
      <el-form-item v-if="enableTenant"
        :label="$t('ec.errorLog.tenant')"
        prop="tenantId"
      >
        <!--        <el-input v-model="queryParams.tenantId" type="text" placeholder="租户ID" />-->
        <ec-tenant v-model="queryParams.tenantId" clearable filterable :placeholder="$t('ec.errorLog.tenant')" @change="getData" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.errorLog.app')"
        prop="appId"
      >
        <!--        <el-input v-model="queryParams.appId" type="text" placeholder="应用ID" />-->
        <ec-register-app v-model="queryParams.appId"  :tenantId="queryParams.tenantId" clearable filterable @change="getData" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.errorLog.remoteIp')"
        prop="ip"
      >
        <el-input v-model="queryParams.ip" type="text" :placeholder="$t('ec.errorLog.remoteIp')" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.log.device')"
        prop="device"
      >
        <el-input v-model="queryParams.device" type="text" :placeholder="$t('ec.log.device')" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.table.code')"
        prop="code"
      >
        <el-input v-model="queryParams.code" type="text" :placeholder="$t('ec.table.code')" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.log.optTime')"
        prop="searchDate"
      >
        <el-date-picker
          v-model="queryParams.searchDate"
          type="datetimerange"
          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.errorLog.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.table.name')"><span>{{ row.name }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.fromUrl')">
                <div class="word_white_space">{{ row.fromUrl }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.url')">
                <div class="word_white_space">{{ row.url }}</div></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.errorLog.remoteIp')"><span>{{ row.ip }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.location')"><span>{{ row.location }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.device')"><span>{{ row.device }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.table.code')"><span>{{ row.code }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.duration')"><span>{{ row.duration }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.desc')"><span>{{ row.description }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('ec.table.sort')"><span>{{ row.sort }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('ec.log.optTime')"><span>{{ dateFormat(row.createDate) }}</span></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template v-slot:toolbar_buttons>
        <el-button v-permission="['ecipVisitStat:export']" type="primary" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
<!--        <el-button @click="getData">{{ $t('ec.table.refresh') }}</el-button>-->
        <el-button v-permission="['ecipVisitStat:repair']" type="danger" @click="repair">{{ $t('ec.log.repair') }}</el-button>
      </template>
    </vxe-grid>

    <detail ref="ecipVisitStatDialog" @refreshData="getData" />

  </div>
</template>

<script>
import permissionMixin from 'ecip-web/utils/permission-mixin'
import checkPermission from 'ecip-web/utils/permission' // 权限判断指令
import { getData, repair } from 'ecip-web/api/web/stat/visit/ecipVisitStatApi'
import Detail from './components/detail'
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 XEUtils from 'xe-utils'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']

export default {
  name: 'WebStatVisitEcipVisitStatView',
  components: { Detail },
  mixins: [permissionMixin],
  data() {
    return {
      enableTenant,
      loading: false,
      exportUrl: 'api/v1/stat/visit/ecipVisitStat/exportExcel',
      tableToolbar: {
        id: 'web.stat.visit.ecipVisitStatView-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,
        field: 'createDate',
        order: 'desc'
      },
      tableData: [],
      columns: [
        { type: 'expand', width: 60, align: 'center', slots: { content: 'detail_content' }},
        {
          title: 'ec.errorLog.user',
          field: 'userId',
          minWidth: 180,
          sortable: true,
          visible: checkPermission(['user:list']),
          slots: { default: 'user_default' }
        },
        // { title: 'ec.errorLog.tenant', field: 'tenantId', visible: enableTenant, minWidth: 180, sortable: true, slots: { default: 'tenant_default' }},
        { title: 'ec.errorLog.app', field: 'appId', minWidth: 180, sortable: true, slots: { default: 'app_default' }},
        { title: 'ec.table.name', field: 'name', minWidth: 180, sortable: true },
        // { title: '源URL地址', field: 'url', minWidth: 180, sortable: true },
        { title: 'ec.log.url', field: 'url', minWidth: 180, sortable: true },
        { title: 'ec.errorLog.remoteIp', field: 'ip', minWidth: 180, sortable: true },
        { title: 'ec.log.optTime', field: 'createDate', minWidth: 180, sortable: true, formatter: ['date', 'yyyy-MM-dd HH:mm:ss'] }
        // { title: '位置', field: 'location', minWidth: 180, sortable: true },
        // { title: '设备', field: 'device', minWidth: 180, sortable: true },
        // { title: '编码', field: 'code', minWidth: 180, sortable: true },
        // { title: '持续时间', field: 'duration', minWidth: 180, sortable: true },
        // { title: '描述', field: 'description', minWidth: 180, sortable: true },
        // { title: '排序', field: 'sort', minWidth: 180, sortable: true },
        // { title: '节点level', field: 'nodeLevel', minWidth: 180, sortable: true },
        // { title: '创建时间', field: 'createDate', minWidth: 180, sortable: true, formatter: ['date', 'yyyy-MM-dd'] },
      ],
      appList: [],
      tenantList: [],
      queryParams: {
        insider: null,
        userId: '',
        tenantId: '',
        appId: '',
        ip: '',
        device: '',
        code: '',
        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
    },
    async repair() {
      let title
      if (this.queryParams.appId) {
        title = `appId：${this.queryParams.appId} `
      } else {
        title = this.$t('ec.log.allApp')
      }
      this.$confirm(this.$t('ec.log.repairConfirm', {title: title}), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        try {
          this.loading = true
          await repair({ appId: this.queryParams.appId })
          await this.getData()
          this.$notify.success(this.$t('ec.log.repairSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    queryData() {
      Object.assign(this.$data.page, this.$options.data().page)
      this.getData()
    },
    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
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getData()
    }
  }
}
</script>

<style scoped>
  .word_white_space {
    white-space: normal;
  }

</style>
