<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span>供应商名称:</span>
        <el-input v-model="listQuery.shopName" placeholder="供应商名称" @keyup.enter.native="handleFilter" />
      </div>
      <div class="filter-control">
        <span>供应商类型:</span>
        <el-select
          v-model="listQuery.shopType"
          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-select>
      </div>
      <div class="filter-control">
        <span>登录账号:</span>
        <el-input v-model="listQuery.loginAccount" placeholder="登录账号" @keyup.enter.native="handleFilter" />
      </div>
      <div class="filter-control">
        <span>手机号:</span>
        <el-input
          v-model="listQuery.mobile"
          placeholder="手机号"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
      </div>
      <div class="filter-control">
        <span>联系人:</span>
        <el-input
          v-model="listQuery.linkMan"
          placeholder="联系人"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
      </div>

      <div class="filter-control">
        <el-button type="primary" @click="getList(listQuery)">查询</el-button>
        <el-button type="primary" @click="navigationTo('supplier-add')">添加供应商</el-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" type="index" sortable="custom" align="center" width="80" />
      <el-table-column label="供应商名称" align="center" prop="name" />
      <el-table-column label="供应商类型" width="100px" align="center">
        <template v-slot="{ row }">
          <span v-if="row.shopType === 1">品牌方</span>
          <span v-if="row.shopType === 2">代理商</span>
        </template>
      </el-table-column>
      <el-table-column label="登录账号" width="120px" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.loginAccount">{{ row.loginAccount }}</span>
          <span v-else>未绑定</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="120px" align="center" prop="mobile" />
      <el-table-column label="联系人" width="100px" align="center" prop="linkMan" />
      <el-table-column label="供应商状态" align="center" width="100px">
        <template v-slot="{ row }">
          <el-switch v-model="row.shopStatus" @change="handleChangeStatus(row)" />
        </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="创建人" width="120px" align="center" prop="createBy" />
      <!-- <el-table-column label="创建人" class-name="status-col" width="100px" prop="createBy" /> -->
      <el-table-column label="操作" align="center" width="360" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="onGetLink(row, $event)"> 首页链接 </el-button>
          <el-button size="mini" type="primary" @click="navigationTo(`supplier-edit?id=${row.authUserId}&type=edit`)">
            编辑
          </el-button>
          <el-button size="mini" type="primary" @click="handleResetPwd(row)"> 重置密码 </el-button>
          <el-button size="mini" type="primary" @click="handleProxy(row)"> 代他操作 </el-button>
          <!-- <el-button size="mini" type="primary" @click="navigationTo(`club-list?id=${row.authUserId}`)">
            查看机构认证
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

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

<script>
import { fetchSupplierList, supplierStatusChange } from '@/api/supplier'
import { generateProxyToken, resetPassword } from '@/api/user'
import handleClipboard from '@/utils/clipboard'

export default {
  name: 'ComplexTable',
  // mixins: [scrollTo],
  data() {
    return {
      slider: 1,
      listLoading: true,
      tableKey: '',
      total: 0, // 条数统计
      listQuery: {
        infoId: '', // 品牌id
        linkMan: '', // 联系人
        mobile: '', // 手机号
        pageNum: 0, // 页码
        pageSize: 10, // 分页大小
        shopName: '', // 供应商名称
        shopType: '', // 供应商类型
        loginAccount: '' // 登录账号
      },
      list: [],
      prevData: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.listLoading = true
      try {
        const res = await fetchSupplierList(this.listQuery)
        const { total, list } = res.data
        this.total = total
        this.list = this.formatList(list)
      } catch (error) {
        console.log(error)
      } finally {
        this.listLoading = false
      }
    },
    // 格式化数组
    formatList(list = []) {
      return list.map((item) => {
        item.shopStatus = item.shopStatus === 1
        return item
      })
    },
    // 供应商状态改变
    async handleChangeStatus(item) {
      console.log(item.shopStatus)
      const oldStatus = !item.shopStatus // 保存旧状态
      try {
        await supplierStatusChange({
          status: item.shopStatus ? 1 : 0,
          authUserId: item.authUserId
        })
        this.$message.success('操作成功')
      } catch (error) {
        // eslint-disable-next-line require-atomic-updates
        item.shopStatus = oldStatus
        console.log(error)
      }
    },
    // 重置密码
    async handleResetPwd(item) {
      const text = await this.$confirm('此操作将重置该供应商的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      // 要执行的操作
      resetPassword({ authUserId: item.authUserId }).then((res) => {
        if (res.code !== 0) return
        const h = this.$createElement
        this.$notify.success({
          title: '重置密码',
          message: h('i', { style: 'color: #333' }, `已重置供应商"${item.name}"的密码`),
          duration: 2000
        })
      })
    },
    // 代他操作
    async handleProxy(item) {
      const text = await this.$confirm('此操作将临时登录该供应商账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return

      if (!item.shopStatus) {
        this.$message.warning('当前供应商未启用')
        return
      }
      try {
        const res = await generateProxyToken({ authUserId: item.authUserId })
        const userInfo = { ...item, token: res.data }
        // 要执行的操作
        this.$store.commit('proxy/OPEN_PROXY', userInfo)
        this.$store.dispatch('user/proxyLogin')
        this.$router.push('/proxy')
      } catch (error) {
        console.log(error)
      }
    },

    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    },

    // 获取供应商链接
    onGetLink(row, $event) {
      const link = process.env.VUE_APP_WWW_HOST + '/' + row.authUserId + '/' + (row.prefix || 'app')
      handleClipboard(link, '已复制到剪切板', $event)
    }
  }
}
</script>

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