<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span>机构名称:</span>
        <el-input
          v-model="listQuery.authParty"
          placeholder="授权机构"
          style="width: 280px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
      </div>
      <div class="filter-control">
        <span>审核状态:</span>
        <el-select
          v-model="listQuery.auditStatus"
          placeholder="审核状态"
          clearable
          style="width: 200px"
          class="filter-item"
          @change="getList"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="2" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核未通过" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>上线状态:</span>
        <el-select
          v-model="listQuery.status"
          placeholder="上线状态"
          clearable
          style="width: 200px"
          class="filter-item"
          @change="getList"
        >
          <el-option label="全部" value="" />
          <el-option label="已上线" :value="1" />
          <el-option label="待上线" :value="2" />
          <el-option label="未上线" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
        <!-- <el-button icon="el-icon-upload" type="primary" @click="improtDialogVisible = true">导入</el-button> -->
        <el-button type="primary" @click="handleExportExcel">导出</el-button>
        <!-- <el-button icon="el-icon-document-copy" type="primary" @click="downLoadExportExcel">获取导入模板</el-button> -->
      </div>
    </div>
    <!-- 表格区域 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" align="center" width="80" type="index" />

      <el-table-column label="机构名称" align="center" prop="authParty" />

      <el-table-column label="审核状态" width="120px" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.auditStatus === 2" size="small" type="warning">待审核</el-tag>
          <el-tag v-if="row.auditStatus === 1" size="small" type="success">审核通过</el-tag>
          <!-- 未通过原因展示 -->
          <template v-if="row.auditStatus === 0">
            <!-- <span class="status danger">审核未通过&nbsp;</span> -->
            <el-popover placement="top-start" title="审核说明" width="400" trigger="hover" :content="row.invalidReason">
              <el-tag slot="reference" size="small" type="danger" class="reason">
                <span>审核未通过</span>
                <span class="el-icon-question status danger " />
              </el-tag>
            </el-popover>
            <!-- 未通过原因展示END -->
          </template>
        </template>
      </el-table-column>

      <el-table-column label="上线状态" width="120px" align="center">
        <template slot-scope="{ row }">
          <!-- 只有审核通过了才能操作上下线 auditStatus ：审核状态 -->
          <template v-if="row.auditStatus === 1">
            <template v-if="row.status === 0">
              <span style="margin-right:10px;" class="status danger">已下线</span>
            </template>
            <template v-else>
              <span style="margin-right:10px;" class="status success ">已上线</span>
            </template>
          </template>
          <template v-else>
            <!-- <el-tag type="warning">待上线</el-tag> -->
            <span style="margin-right:10px;" class="status warning">待上线</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" class-name="status-col" width="160px">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | formatTime }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="创建人" class-name="status-col" width="160px" prop="createBy" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240px">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="$_navigationTo(`club-detail?id=${row.authId}&authParty=${row.authParty}`)"
          >
            查看
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="$_navigationTo(`club-device-list?id=${row.authId}&authParty=${row.authParty}`)"
          >
            查看设备认证
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { fecthAuthList, authImportExcel } from '@/api/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { mapGetters } from 'vuex'
import { debounce, downLoadWithATag } from '@/utils/tools'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        authParty: '', // 授权机构
        authUserId: '', // 供应商用户id
        pageNum: 1, // 页码
        pageSize: 10, // 分页
        status: ''
      },
      disabled: false,

      // ------------------
      improtDialogVisible: false,
      requestLoading: false,
      uploadFileList: [],
      improtDialogFormData: {
        fileUrl: ''
      },
      improtDialogFormRules: {
        fileUrl: [
          {
            required: true,
            message: '请选择文件',
            trigger: 'change'
          }
        ]
      },
      chooseFile: ''
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'proxyInfo', 'copyUserInfo']),
    saveBtnClickable() {
      return this.uploadFileList.length > 0
    }
  },
  created() {
    this.listQuery.authUserId = this.$route.query.id || this.proxyInfo?.authUserId || this.authUserId
    const type = this.$route.query.type
    // 如果是通过路由参数传递的type,则需要同步到store
    if (type) {
      this.$store.commit('user/SET_SHOP_TYPE', parseInt(type))
    }
    this.getList()
  },
  methods: {
    // 下载模板
    downLoadExportExcel() {
      downLoadWithATag(
        `${process.env.VUE_APP_BASE_API}/download/file?ossName=%E6%AD%A3%E5%93%81%E8%81%94%E7%9B%9F%E6%9C%BA%E6%9E%84%E3%80%81%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx&fileName=%E6%AD%A3%E5%93%81%E8%81%94%E7%9B%9F%E6%9C%BA%E6%9E%84%E3%80%81%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx`
      )
    },

    // 导出为Excel
    async handleExportExcel() {
      const text = await this.$confirm('确认导出所有授权机构的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      // 使用a链接下载
      downLoadWithATag(`${process.env.VUE_APP_BASE_API}/auth/export/excel?authUserId=${this.authUserId}`)
    },

    // 导入Excel 并提交
    handleSave: debounce(function() {
      console.log('保存')
      console.log(this.improtDialogFormData)
      console.log(this.proxyInfo, this.authUserId)
      // 上传文件使用 multipart/form-data
      const formData = new FormData()

      formData.append('authUserId', this.authUserId)
      formData.append('createBy', this.copyUserInfo.authUserId)
      formData.append('file', this.chooseFile)

      authImportExcel(formData)
        .then(res => {
          this.$message.success(res.data)
          this.improtDialogVisible = false
          this.getList()
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.requestLoading = false
        })
    }, 200),
    // 获取授权列表
    getList() {
      this.listLoading = true
      fecthAuthList(this.listQuery)
        .then(response => {
          if (response.code !== 0) {
            return this.$message.error('授权列表信息获取失败')
          }
          const { list, total } = response.data
          this.list = list
          this.total = total
        })
        .catch(err => {
          console.log(err)
          return this.$message.error('授权列表信息获取失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
