<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span>机构名称:</span>
        <el-input v-model="listQuery.authParty" placeholder="机构名称" @keyup.enter.native="handleFilter" />
      </div>
      <div class="filter-control">
        <span>审核状态:</span>
        <el-select v-model="listQuery.auditStatus" placeholder="审核状态" clearable @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 @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">
        <span>明星机构</span>
        <el-checkbox v-model="listQuery.starFlag" :true-label="1" :false-label="null" @change="getList" />
      </div>
      <div class="filter-control">
        <span>设备名称:</span>
        <el-input v-model="listQuery.name" placeholder="设备名称" @keyup.enter.native="handleFilter" />
      </div>
      <div class="filter-control">
        <span>设备SN码:</span>
        <el-input v-model="listQuery.snCode" placeholder="设备SN码" @keyup.enter.native="handleFilter" />
      </div>
      <div class="filter-control">
        <permission-button type="primary" @click="getList">查询</permission-button>
        <permission-button type="primary" @click="navigationTo('club-add?type=edit')">添加</permission-button>
      </div>
      <div class="filter-control">
        <permission-button type="primary" @click="downLoadTemplate">机构导入模板</permission-button>
      </div>
      <!-- 机构设备信息导出  -->
      <div class="filter-control">
        <permission-button type="primary" @click="improtDialogVisible = true">导入机构信息</permission-button>
        <permission-button type="primary" @click="onHandleExport(5)">导出机构信息</permission-button>
        <permission-button type="primary" @click="onHandleExport(6)">导出设备信息</permission-button>
      </div>
      <!-- 机构设备授权牌导出 -->
      <div class="filter-control">
        <permission-button type="primary" @click="onHandleExport(1)">下载机构授权牌</permission-button>
        <permission-button type="primary" @click="onHandleExport(2)">下载设备授权牌</permission-button>
      </div>
      <!-- 机构设备二维码下载 -->
      <div class="filter-control">
        <permission-button type="primary" @click="onHandleExport(3)">一键下载机构二维码</permission-button>
        <permission-button type="primary" @click="onHandleExport(4)">一键下载设备二维码</permission-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 }">
          <audit-status :status="row.auditStatus" :reason="row.invalidReason" />
        </template>
      </el-table-column>

      <el-table-column label="上线状态" width="160px" 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>
              <permission-button type="primary" size="mini" @click="handleChangeStatus(row)">上线</permission-button>
            </template>
            <template v-else>
              <span style="margin-right: 10px" class="status success">已上线</span>
              <permission-button type="info" size="mini" @click="handleChangeStatus(row)">下线</permission-button>
            </template>
          </template>
          <template v-else>
            <span style="margin-right: 10px" class="status warning">待上线</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="扫码次数" align="center" prop="scanCount" width="80" />

      <el-table-column label="明星机构/排序" align="center" width="160">
        <template slot-scope="{ row }">
          <div class="star-sort">
            <el-checkbox v-model="row.starFlag" :true-label="1" :false-label="0" @change="onStarChange(row, $event)" />
            <el-input v-model="row.starNum" placeholder="排序" size="mini" @blur="onStarChange(row, row.starFlag)" />
          </div>
        </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="180px" prop="createBy" />
      <el-table-column label="操作" align="center" width="430px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <permission-button type="primary" size="mini" @click="navigationTo(`club-edit?type=edit&id=${row.authId}`)">
            编辑
          </permission-button>
          <!-- <permission-button type="danger" size="mini" @click="handleRemoveAuth(row)"> 删除 </permission-button> -->
          <permission-button type="primary" size="mini" @click="navigationTo(`device-list?id=${row.authId}`)">
            设备认证
          </permission-button>
          <permission-button type="primary" size="mini" :disabled="row.status !== 1" @click="createClubQrcode(row)">
            二维码
          </permission-button>
          <permission-button type="primary" size="mini" @click="cotyClubLink($event, row)">
            复制注册链接
          </permission-button>
          <permission-button
            type="primary"
            size="mini"
            :disabled="row.status !== 1 || row.sendStatus === 0"
            @click="navigationTo(`logistics-licensed?id=${row.authId}`)"
          >
            授权牌物流
          </permission-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 导入对话框 -->
    <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">
        <permission-button @click="improtDialogVisible = false">取 消</permission-button>
        <permission-button
          type="primary"
          :disabled="!saveBtnClickable"
          :loading="requestLoading"
          @click="submitUpload"
        >确 定</permission-button>
      </span>
    </el-dialog>

    <!-- 导出时选择机构 -->
    <el-dialog title="选择机构" :visible.sync="exportDialogVisible" width="70%">
      <club-list-selector v-if="exportDialogVisible" @cancel="onSelectorCancel" @confirm="onSelectorConfirm" />
    </el-dialog>

    <!-- 二维码 -->
    <transition name="fade">
      <qrcode-club v-if="showQRcode" :qrcode-data="clubInfo" @close="showQRcode = false" />
    </transition>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import QrcodeClub from '@/components/QrcodeClub'
import { ClubListSelector } from '@/views/components'
import { fecthAuthListAll, changeAuthStatus, removeAuth, authImportExcel, setStarClub } from '@/api/auth'
import { mapGetters } from 'vuex'
import { debounce, downloadWithUrl } from '@/utils/tools'
import handleClipboard from '@/utils/clipboard'
export default {
  name: 'ComplexTable',
  components: { FileUpload, QrcodeClub, ClubListSelector },
  data() {
    return {
      showQRcode: false,
      clubInfo: {},
      noticeTitle: '添加',
      dialogFlag: true, // 对话框状态
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        authParty: '', // 授权机构
        authUserId: '', // 供应商用户id
        pageNum: 1, // 页码
        pageSize: 10, // 分页
        status: '',
        starFlag: null,
        name: '',
        snCode: ''
      },

      improtDialogVisible: false,
      requestLoading: false,
      uploadFileList: [],
      improtDialogFormData: {
        fileUrl: ''
      },
      improtDialogFormRules: {
        fileUrl: [
          {
            required: true,
            message: '请选择文件',
            trigger: 'change'
          }
        ]
      },
      chooseFile: '',
      exportDialogVisible: false,
      exportType: '',
      exportClubList: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'UserInfo', 'prefix']),
    saveBtnClickable() {
      return this.uploadFileList.length > 0
    }
  },
  created() {
    this.listQuery.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: {
    // 明星机构设置
    async onStarChange(row, value) {
      console.log(row)
      try {
        await setStarClub({ authId: row.authId, starFlag: value, starNum: row.starNum })
        this.$message.success('操作成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },

    // 机构二维码
    createClubQrcode(item) {
      this.clubInfo = item
      this.showQRcode = true
      console.log('机构二维码')
    },

    // 复制链接
    async cotyClubLink($event, row) {
      console.log(row)
      if (row.productNum === 0) {
        return this.$confirm('请在该机构下完善至少一条设备认证，再复制该注册链接', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {})
      }
      const prefix = this.prefix || 'app'
      handleClipboard(
        `${process.env.VUE_APP_WWW_HOST}/${row.authUserId}/${prefix}/form/club-bind?authId=${row.authId}`,
        '链接已复制到粘贴板',
        $event
      )
    },

    // 上传文件
    submitUpload() {
      this.$refs.dialogForm.validate((valid) => {
        console.log(valid)
        if (!valid) return
        this.requestLoading = true
        this.handleSave()
      })
    },

    // 监听上传文件的状态变化
    async fileUploadChange(fileList) {
      this.uploadFileList = fileList
      try {
        await this.handleFileUploadStatus(fileList)
        this.handleSave.apply(this)
      } catch (error) {
        console.log(error)
      }
    },

    // 取消选择机构
    onSelectorCancel() {
      this.exportType = ''
      this.exportClubList = []
      this.exportDialogVisible = false
    },

    // 选择确认机构
    onSelectorConfirm(list) {
      this.exportClubList = list
      this.onExport(this.exportType)
      this.exportDialogVisible = false
    },

    // 导出下载机构信息
    onHandleExport(type) {
      this.exportDialogVisible = true
      this.exportType = type
    },

    // 导出
    async onExport(type) {
      const confirmText = ['', '机构授权牌', '设备授权牌', '机构二维码', '设备二维码', '机构信息', '设备信息'][type]
      const downloadLinkMap = {
        1: '/shop/image?type=1&',
        2: '/shop/image?type=2&',
        3: '/shop/image?type=3&',
        4: '/shop/image?type=4&',
        5: '/auth/excel?',
        6: '/product/excel?'
      }
      const text = await this.$confirm(`确认下载所选${confirmText}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.exportClubList = []
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      let notification = null
      notification = this.$notify({
        title: '提示',
        message: `正在下载${confirmText}，请勿重复操作！`,
        duration: 0
      })
      const authIds = this.exportClubList.map((item) => item.authId)
      // 使用a链接下载
      const downUrl = `${process.env.VUE_APP_BASE_API}/download${downloadLinkMap[type]}authIds=${authIds}`
      downloadWithUrl(downUrl, confirmText)
        .catch((err) => {
          console.log(err)
          this.$message.error(`下载${confirmText}失败`)
        })
        .finally(() => {
          notification.close()
          this.onSelectorCancel()
        })
    },

    // 下载机构导入模板
    downLoadTemplate() {
      const downUrl = `${process.env.VUE_APP_BASE_API}/download/auth/template`
      let notification = null
      notification = this.$notify({
        title: '提示',
        message: '正在下载机构导入模板，请勿重复操作！',
        duration: 0
      })
      downloadWithUrl(downUrl, '机构导入模板.xlsx')
        .catch((err) => {
          console.log(err)
          this.$message.error(`下载机构导入模板失败`)
        })
        .finally(() => {
          notification.close()
        })
    },

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

      formData.append('authUserId', this.authUserId)
      formData.append('createBy', this.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() {
      console.log(this.listQuery)
      this.listLoading = true
      fecthAuthListAll(this.listQuery)
        .then((response) => {
          if (response.code !== 0) {
            return this.$message.error('授权列表信息获取失败')
          }
          const { list, total } = response.data
          // this.formatList(list)
          this.list = list
          this.total = total
        })
        .catch((err) => {
          console.log(err)
          return this.$message.error('授权列表信息获取失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 删除品牌授权
    async handleRemoveAuth(item) {
      const text = await this.$confirm('确认删除该数据吗？删除后，对应的商品数据也将全部删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      // 要执行的操作
      this.listLoading = true
      removeAuth({ authId: item.authId })
        .then((res) => {
          if (res.code !== 0) return
          const h = this.$createElement
          this.$notify.success({
            title: '移除授权机构',
            message: h('i', { style: 'color: #333' }, `移除授权机构："${item.authParty}"`),
            duration: 3000
          })
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.listLoading = false
          this.getList()
        })
    },

    // 格式化列表数据
    formatList(list = []) {
      list.forEach((i) => {
        i.status = i.status === 1
      })
    },

    // 供应商状态改变
    handleChangeStatus(item) {
      this.listLoading = true
      const params = {
        authId: item.authId,
        status: item.status === 1 ? 0 : 1
      }
      changeAuthStatus(params)
        .then((res) => {
          // this.$message.success(res.data)
          this.$message({
            message: res.data,
            duration: 500,
            type: 'success'
          })
          this.getList()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.getList()
    },

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

<style lang="scss" scoped>
.star-sort {
  display: flex;
  align-items: center;
  justify-content: center;

  .el-input {
    width: 50%;
    margin-left: 16px;
  }
}
</style>
