<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 v-if="userIdentity === 2 || proxyInfo!==null" icon="el-icon-edit" type="primary" @click="handleShowEditDialog('添加品牌授权')">添加品牌授权</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>
              <el-button v-if="userIdentity===2 || proxyInfo!==null" 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="userIdentity===2 || proxyInfo!==null" type="info" size="mini" plain @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="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" width="240px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="userIdentity === 2|| proxyInfo!==null">
            <el-button type="info" size="mini" @click="handleShowEditDialog('编辑品牌授权',row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleRemoveAuth(row)">
              删除
            </el-button>
          </template>
          <el-button type="primary" size="mini" @click="$_navigationTo(`/product?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" />

    <!-- 对话框区域 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showAddAuthDialog"
      width="30%"
      @close="dialogClosed"
    >
      <el-form ref="addAuthForm" :rules="addAuthFormRules" :model="addAuthFormData" label-width="100px">
        <el-form-item label="授权机构：" prop="authParty">
          <el-input v-model="addAuthFormData.authParty" placeholder="请输入授权机构名称" />
        </el-form-item>
        <!-- <el-form-item label="上线状态：">
          <el-select v-model="addAuthFormData.status">
            <el-option label="上线" :value="1" />
            <el-option label="下线" :value="0" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddAuthDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="disabled" @click="handleUpdateBrandAuth">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fecthAuthList, saveBrandAuth, changeAuthStatus, removeAuth } from '@/api/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      noticeTitle: '添加',
      dialogFlag: true, // 对话框状态
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        authParty: '', // 授权机构
        authUserId: '', // 供应商用户id
        pageNum: 1, // 页码
        pageSize: 10, // 分页
        status: ''
      },
      // 添加品牌授权
      showAddAuthDialog: false, // 显示添加供应商对话框
      dialogTitle: '',
      addAuthFormData: {
        authId: '', // 授权id
        authUserId: '', // 供应商用户id
        authParty: '', // 授权机构
        createBy: '', // 创建人id
        status: 2 // 授权状态 0下线，1上线  2待审核
      },
      addAuthFormRules: {
        authParty: [
          { required: true, message: '请输入授权机构名称', trigger: 'blur' }
        ]
      },
      disabled: false,
      // 审核未通过
      auditFailedList: [],
      auditNoticeFlag: true
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'proxyInfo'])
  },
  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()
  },
  destroyed() {
    // 页面关闭时清空代理数据
    // this.$store.commit('user/SET_PROXY_INFO', null)
  },
  methods: {
    // 获取授权列表
    getList() {
      this.listLoading = true
      fecthAuthList(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
        // 获取审核未通过的列表
        // this.checkAuditFailedList(list)
      }).catch(err => {
        console.log(err)
        return this.$message.error('授权列表信息获取失败')
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 获取审核未通过条数
    // 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
      }
    },
    // 检查机构名是否存在 true:存在  false:不存在
    handleCheckAuthName(name) {
      const flag = this.list.some(item => item.authParty === name)
      console.log(flag)
      return flag
    },
    // 添加授权
    handleUpdateBrandAuth() {
      if (this.handleCheckAuthName(this.addAuthFormData.authParty) && this.dialogFlag) {
        this.$message({
          message: '该授权机构已存在',
          duration: 1000,
          type: 'warning'
        })
        return
      }
      this.$refs.addAuthForm.validate(valide => {
        if (valide) {
          this.disabled = true
          this.listLoading = true
          // authUserId先判断是否为代理操作，是就从代理数据中获取，否则直接获取当前登录用户的信息
          this.addAuthFormData.authUserId = this.$route.query.id || this.proxyInfo?.authUserId || this.authUserId
          this.addAuthFormData.createBy = this.addAuthFormData.authUserId
          saveBrandAuth(this.addAuthFormData).then(res => {
            if (res.code !== 0) {
              return
            }
            this.getList()
            const h = this.$createElement
            this.$notify.success({
              title: `${this.noticeTitle}授权机构`,
              message: h('i', { style: 'color: #333' }, `已${this.noticeTitle}授权机构："${this.addAuthFormData.authParty}"`),
              duration: 3000
            })
            this.$refs.addAuthForm.resetFields()
          }).catch(err => {
            console.log(err)
            this.$message.danger('操作失败')
          }).finally(() => {
            this.showAddAuthDialog = false
            this.listLoading = false
            this.disabled = 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) {
      if (this.userIdentity !== 2 && this.proxyInfo === null) return
      this.listLoading = true
      // const params = {
      //   authId: item.authId,
      //   status: item.status ? 1 : 0
      // }
      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.getList()
    },
    // 添加供应商
    handleAddAuth() {
      console.log('添加供应商')
    },
    // 对话框关闭事件
    dialogClosed() {
      console.log('dialog is closed')
      this.addAuthFormData.authParty = ''
      this.addAuthFormData.authId = ''
      this.addAuthFormData.status = 1
      this.noticeTitle = '添加'
      this.$refs.addAuthForm.resetFields()
    },
    handleShowEditDialog(title, data) {
      this.dialogTitle = title
      if (data) {
        this.addAuthFormData.authId = data.authId
        this.addAuthFormData.authUserId = data.authUserId
        this.addAuthFormData.authParty = data.authParty
        this.addAuthFormData.createBy = data.createBy
        this.status = data.status
        this.noticeTitle = '修改'
        this.dialogFlag = false
      } else {
        this.dialogFlag = true
      }
      this.showAddAuthDialog = true
    },
    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>
