<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span>设备名称:</span>
        <el-input v-model="listQuery.productName" 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">
        <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">
        <permission-button type="primary" @click="handleFilter">查询</permission-button>
        <permission-button
          type="primary"
          @click="navigationTo(`device-add?type=add`)"
        >添加新设备认证</permission-button>
        <permission-button type="primary" @click="navigationTo(`device-bind`)">关联已认证设备</permission-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <el-table
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" type="index" align="center" width="80" />
      <el-table-column label="设备名称" align="center" prop="productName" />
      <el-table-column label="设备SN码" align="center" prop="snCode" />

      <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>
            <!-- <el-tag type="warning">待上线</el-tag> -->
            <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="创建时间" class-name="status-col" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | formatTime }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column v-if="false" label="创建人" width="180px" align="center" prop="createBy" /> -->
      <el-table-column label="操作" align="center" width="340px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <permission-button
            type="primary"
            size="mini"
            @click="navigationTo(`device-edit?type=edit&id=${row.productId}&relationId=${row.relationId}`)"
          >
            编辑
          </permission-button>
          <permission-button v-if="row.auditStatus === 1" type="primary" size="mini" @click="handleShowQRcode(row)">
            二维码
          </permission-button>
          <permission-button v-else type="info" size="mini" disabled> 二维码 </permission-button>
          <permission-button type="primary" size="mini" @click="fetchDeviceAssClubList(row)">
            其他关联机构
          </permission-button>
          <permission-button type="danger" size="mini" @click="handleRemoveProduct(row)"> 删除 </permission-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 二维码 -->
    <transition name="fade">
      <qrcode-device v-if="showQRcode" :product-info="productInfo" @close="showQRcode = false" />
    </transition>

    <!-- 关联机构 -->
    <el-dialog title="其他关联机构" :visible.sync="dialogClubVisible" width="30%">
      <associated-club-list
        class="associated-club-list"
        :selection="false"
        :control="true"
        :show-filter="false"
        height="300"
        :list="assClubList"
      >
        <template #control="{ row }">
          <el-button size="mini" type="primary" @click="onToClubDetail(row)">查看</el-button>
        </template>
      </associated-club-list>
    </el-dialog>
  </div>
</template>

<script>
import { getProdList, setProductStatus, removeProduct, fetchDeviceAssClubList } from '@/api/product'
import { AssociatedClubList } from '@/views/components/index'
import QrcodeDevice from '@/components/QrcodeDevice'
import { mapGetters } from 'vuex'
import { setStorage } from '@/utils/storage'
export default {
  name: 'ComplexTable',
  components: { QrcodeDevice, AssociatedClubList },
  data() {
    return {
      authParty: '',
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        status: '',
        auditStatus: '',
        authId: '',
        productName: '',
        snCode: '',
        pageNum: 1,
        pageSize: 10
      },
      showQRcode: false,
      productInfo: {},
      // 审核未通过
      auditFailedList: [],
      auditNoticeFlag: true,
      dialogClubVisible: false,
      assClubList: []
    }
  },
  computed: {
    ...mapGetters(['userIdentity'])
  },
  created() {
    this.initPage()
  },

  activated() {
    this.initPage()
  },

  methods: {
    initPage() {
      this.listQuery.authId = this.$route.query.id
      this.authParty = this.$route.query.authParty
      // 保存机构id，用于设备管理
      setStorage('device-setting-authId', this.listQuery.authId)
      this.getList()
    },

    // 机构详情
    onToClubDetail(row) {
      this.dialogClubVisible = false
      const fullPath = `/club/device-list?id=${row.authId}`
      this.$router.replace({
        path: '/redirect' + fullPath
      })
    },

    // 获取设备关联机构列表
    async fetchDeviceAssClubList(row) {
      try {
        const res = await fetchDeviceAssClubList({ snCode: row.snCode })
        this.assClubList = res.data
        this.dialogClubVisible = true
      } catch (error) {
        console.log(error)
      }
    },

    // 获取列表信息
    getList() {
      getProdList(this.listQuery)
        .then((res) => {
          const { total, list } = res.data
          this.total = total
          this.list = list
          // this.checkAuditFailedList(list)
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 改变启用状态
    handleChangeStatus(item) {
      if (this.userIdentity === 2 || this.proxyInfo !== null) {
        const { status, productId } = item
        const newStatus = status === 0 ? 1 : 0
        setProductStatus({ status: newStatus, productId })
          .then((res) => {
            // this.$message.success(res.data)
            this.$message({
              message: '操作成功',
              duration: 500,
              type: 'success'
            })
          })
          .catch((error) => {
            console.log(error)
          })
          .finally(() => {
            this.getList()
          })
      }
    },
    // 删除商品
    async handleRemoveProduct(item) {
      const text = await this.$confirm(
        '确定删除该设备认证吗？删除后，其他机构已关联此设备认证的也将一并删除，请慎重操作。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return

      removeProduct({ productId: item.productId })
        .then((res) => {
          const h = this.$createElement
          this.$notify.success({
            title: '删除商品',
            message: h('i', { style: 'color: #333' }, `已删除商品："${item.productName}"`),
            duration: 2000
          })
        })
        .catch((error) => {
          console.log(error)
        })
        .finally(() => {
          this.getList()
        })
    },
    // 显示二维码
    handleShowQRcode(item) {
      this.productInfo = item
      this.productInfo.authParty = this.authParty
      this.showQRcode = true
    },
    // 获取审核未通过条数
    // Audit failed 审核未通过
    checkAuditFailedList(data) {
      this.auditFailedList = data.filter((item) => item.auditStatus === 0)
      if (this.auditFailedList.length > 0 && this.auditNoticeFlag) {
        this.$notify.info({
          title: '消息通知',
          dangerouslyUseHTMLString: true,
          message: `共有<b style="color:red">${this.auditFailedList.length}</b>件商品未能通过审核，请查看原因并及时修改！`,
          duration: 3000
        })
        this.auditNoticeFlag = false
      }
    },
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped></style>
