<template>
  <div class="app-container">
    <div class="filter-container">
      <span>机构名称:</span>
      <el-input v-model="listQuery.authParty" placeholder="授权机构" style="width: 280px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <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>
      <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>
      <el-button icon="el-icon-search" type="primary" @click="getList">查询</el-button>
      <el-button icon="el-icon-upload" type="primary" @click="improtDialogVisible = true">导入</el-button>
      <el-button icon="el-icon-document" type="primary" @click="handleExportExcel">导出</el-button>
      <el-button icon="el-icon-document-copy" type="primary" @click="downLoadExportExcel">获取导入模板</el-button>
    </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="220px" 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="140px" 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="360px">
        <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">
        <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" />

    <!-- 导入对话框 -->
    <!-- dialog Start -->
    <el-dialog
      title="导入"
      :visible.sync="improtDialogVisible"
      width="30%"
      @close="improtDialogClose"
    >
      <el-form ref="dialogForm" :model="improtDialogFormData" label-width="86px" :rules="improtDialogFormRules">
        <el-form-item label="文件路径:" prop="fileUrl">
          <file-upload ref="fileUpload" :file-list="uploadFileList" @change="fileUploadChange" />
          <el-input v-show="false" v-model="improtDialogFormData.fileUrl" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="improtDialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="!saveBtnClickable" :loading="requestLoading" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
    <!-- dialog END -->
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import { fecthAuthList, authImportExcel } from '@/api/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils'
import { debounce, downLoadWithATag } from '@/utils/tools'
export default {
  name: 'ComplexTable',
  components: { Pagination, FileUpload },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },
  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: {
    // 上传文件
    submitUpload() {
      this.$refs.dialogForm.validate(valid => {
        console.log(valid)
        if (!valid) return
        this.requestLoading = true // 上传文件
        // this.$refs.fileUpload.submit()
        this.handleSave()
      })
    },
    // 监听上传文件的状态变化
    async fileUploadChange(fileList) {
      this.uploadFileList = fileList
      try {
        await this.handleFileUploadStatus(fileList)
        this.handleSave.apply(this)
      } catch (error) {
        console.log(error)
      }
    },

    // 下载模板
    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),

    // 处理文件上传状态
    handleFileUploadStatus(fileList) {
      console.log(fileList)
      this.chooseFile = fileList[0].raw
      // 文件列表为空
      if (fileList.length <= 0) {
        this.improtDialogFormData.fileUrl = ''
        return Promise.reject('faild')
      }
      // 取第一个文件
      const { response, status } = fileList[0]
      // 文件已选择但未上传
      if (status === 'ready') {
        this.improtDialogFormData.fileUrl = status
        return Promise.reject('faild')
      }
      // 文件已上传
      if (status === 'success') {
        this.improtDialogFormData.fileUrl = response.previewUrl
        return Promise.resolve('success')
      }
    },
    improtDialogClose() {
      console.log(123)
      // this.uploadFileList = []
      this.$refs.fileUpload.clearAllFiles()
      this.$refs.dialogForm.resetFields()
    },
    // 获取授权列表
    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
      })
    },
    // 格式化列表数据
    formatList(list = []) {
      list.forEach(i => {
        i.status = i.status === 1
      })
    },
    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

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

<style lang="scss" scoped>
.filter-container{
  span{
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
    font-size: 14px;
  }
  .el-button{
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
  }
  .el-input,.el-select{
    margin-right: 10px;
    margin-left: 10px;
  }
}
</style>
