<template>
  <div class="app-container">
    <div class="filter-container">
      <span>设备名称:</span>
      <el-input v-model="listQuery.productName" placeholder="设备名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <span>设备SN码:</span>
      <el-input v-model="listQuery.snCode" placeholder="设备SN码" style="width: 200px;" 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 type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="isProxy" icon="el-icon-edit" type="primary" @click="$_navigationTo(`device-add?type=add`)">添加</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" 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="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>
              <el-button v-if="isProxy" type="primary" size="mini" @click="handleChangeStatus(row)">上线</el-button>
            </template>
            <template v-else>
              <span style="margin-right:10px;" class="status success ">已上线</span>
              <el-button v-if="isProxy" type="info" size="mini" @click="handleChangeStatus(row)">下线</el-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="创建时间" class-name="status-col" width="300px" 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="240px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="userIdentity === 2|| proxyInfo !== null">
            <el-button type="default" size="mini" @click="$_navigationTo(`device-edit?type=edit&id=${row.productId}`)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleRemoveProduct(row)">
              删除
            </el-button>
          </template>
          <el-button v-if="row.auditStatus === 1" type="primary" size="mini" @click="handleShowQRcode(row)">
            二维码
          </el-button>
          <el-button v-else type="info" size="mini" disabled>
            二维码
          </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" />

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

<script>
import { getProdList, setProductStatus, removeProduct } from '@/api/product'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Qrcode from '@/components/qrcode'
import { formatDate } from '@/utils'
import { mapGetters } from 'vuex'
import { setStorage } from '@/utils/storage'
export default {
  name: 'ComplexTable',
  components: { Pagination, Qrcode },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },

  data() {
    return {
      authParty: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        status: '',
        auditStatus: '',
        authId: '',
        productName: '',
        snCode: '',
        pageNum: 1,
        pageSize: 10
      },
      showQRcode: false,
      productInfo: {},
      // 审核未通过
      auditFailedList: [],
      auditNoticeFlag: true
    }
  },
  computed: {
    ...mapGetters(['userIdentity', 'proxyInfo']),
    isProxy() {
      return this.proxyInfo || this.userIdentity !== 1
    }
  },
  created() {
    this.listQuery.authId = this.$route.query.id
    this.authParty = this.$route.query.authParty
    // 保存机构id，用于设备管理
    setStorage('device-setting-authId', this.listQuery.authId)
    this.getList()
  },

  methods: {
    // 获取列表信息
    getList() {
      getProdList(this.listQuery).then(res => {
        const { total, list } = res.data
        this.total = total
        this.list = list
        // this.checkAuditFailedList(list)
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 改变启用状态
    handleChangeStatus(item) {
      if (this.userIdentity === 2 || this.proxyInfo !== null) {
        this.listLoading = true
        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'
          })
          this.listLoading = false
        }).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
        })
      }).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.userIdentity !== 1 || this.proxyInfo !== null)) {
        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>
.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>
