<template>
    <div>
      <div class="gva-search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item>
            <el-select v-model="searchInfo.searchBox" >
              <el-option
                v-for="item in methodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchInfo.channelName" placeholder="请输入关键字" />
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
        <div class="gva-btn-list">
          <el-button size="small" icon="refresh" @click="onReset">刷新</el-button>
          <el-button size="small" type="primary" icon="plus" @click="openDialog('addGameChannel')">新增</el-button>
          <el-popover v-model="deleteVisible" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
              <el-button size="small" type="primary" link @click="deleteVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
              <el-button icon="delete" type="danger" size="small" :disabled="!apis.length" style="margin-left: 10px;" @click="deleteVisible = true">删除</el-button>
            </template>
          </el-popover>
        </div>
        <el-table :data="tableData" @sort-change="sortChange" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55"
          />
          <!-- <el-table-column align="left" label="厂商ID" min-width="100" prop="id" sortable="custom" aria-disabled="false"/> -->
          <el-table-column align="left" label="厂商名称" min-width="100" prop="channelName" sortable="custom" />
          <el-table-column align="left" label="厂商描述" min-width="150" prop="channelDesc" sortable="custom" />
          <el-table-column align="left" label="显示顺序" min-width="150" prop="displaySequence" sortable="custom" />
          <el-table-column align="left" label="游戏数量" min-width="150" prop="gameCounts" sortable="custom" />
          <el-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom" />
          <el-table-column align="left" label="更新时间" min-width="150" prop="updateTime" sortable="custom" />
  
          <el-table-column align="left" fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button
                icon="edit"
                size="small"
                type="primary"
                link
                @click="editApiFunc(scope.row)"
              >编辑</el-button>
              <el-button
                icon="delete"
                size="small"
                type="primary"
                link
                @click="deleteApiFunc(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
  
      </div>
  
      <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
        <!-- <warning-bar title="新增API，需要在角色管理内配置权限才可使用" /> -->
        <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="厂商名称" prop="channelName">
            <el-input v-model="form.channelName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="厂商描述" prop="channelDesc">
            <el-input v-model="form.channelDesc" :rows="4" type="textarea" autocomplete="off" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="displaySequence">
            <el-input-number v-model="form.displaySequence" min=0 autocomplete="off"  clearable placeholder="0"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="closeDialog">取 消</el-button>
            <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: 'Api',
  }
  </script>
  
  <script setup>
  import {
    getApiById,
    getApiList,
    createApi,
    updateApi,
    deleteApi,
    deleteApisByIds
  } from '@/api/gameChannel'
  import { toSQLLine } from '@/utils/stringFun'
  import warningBar from '@/components/warningBar/warningBar.vue'
  import { ref } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
import { isNumber } from 'lodash'
  
  const methodFiletr = (value) => {
    const target = methodOptions.value.filter(item => item.value === value)[0]
    return target && `${target.label}`
  }
  
  const apis = ref([])
  const form = ref({
    channelName: '',
    channelDesc: '',
    gameCounts: 0,
  })
  const methodOptions = ref([
    {
      value: 'channel_name',
      label: '厂商名称',
      type: ''
    },
  ])
  
  const type = ref('')
  const rules = ref({
    channelName: [{ required: true, message: '厂商名称不能为空', trigger: 'blur' }],
    channelDesc: [{ required: true, message: '厂商描述不能为空', trigger: 'blur' }]
  })
  
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const tableData = ref([])
  const searchInfo = ref({
    searchBox:'channel_name'
  })
  
  const onReset = () => {
    searchInfo.value = {
      searchBox:'channel_name'
    }
    getTableData()
  }
  // 搜索
  
  const onSubmit = () => {
    page.value = 1
    pageSize.value = 10
    getTableData()
  }
  
  // 分页
  const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
  }
  
  const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
  }
  
  // 排序
  const sortChange = ({ prop, order }) => {
    if (prop) {
      if (prop === 'ID') {
        prop = 'id'
      }
      searchInfo.value.orderKey = toSQLLine(prop)
      searchInfo.value.desc = order === 'descending'
    }
    getTableData()
  }
  
  // 查询
  const getTableData = async() => {
    const table = await getApiList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
    if (table.code === 0) {
      tableData.value = table.data.list
      total.value = table.data.total
      page.value = table.data.page
      pageSize.value = table.data.pageSize
    }
  }
  
  getTableData()
  
  // 批量操作
  const handleSelectionChange = (val) => {
    apis.value = val
  }
  
  const deleteVisible = ref(false)
  const onDelete = async() => {
    const ids = apis.value.map(item => item.id)
    const res = await deleteApisByIds({ ids })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg
      })
      if (tableData.value.length === ids.length && page.value > 1) {
        page.value--
      }
      deleteVisible.value = false
      getTableData()
    }
  }
  
  // 弹窗相关
  const apiForm = ref(null)
  const initForm = () => {
    apiForm.value.resetFields()
    form.value = {
    //   path: '',
    //   apiGroup: '',
    //   method: '',
    //   description: ''
    channelName: '',
    channelDesc: '',
    displaySequence: '',
    gameCounts: ''
    }
  }
  
  const dialogTitle = ref('新增Api')
  const dialogFormVisible = ref(false)
  const openDialog = (key) => {
    switch (key) {
      case 'addGameChannel':
        dialogTitle.value = '新增'
        break
      case 'editGameChannel':
        dialogTitle.value = '编辑'
        break
      default:
        break
    }
    type.value = key
    dialogFormVisible.value = true
  }
  const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
  }
  
  const editApiFunc = async(row) => {
    const res = await getApiById({ id: row.id })
    form.value = res.data.gameChannel
    console.log(form)
    openDialog('editGameChannel')
  }
  
  const enterDialog = async() => {
    apiForm.value.validate(async valid => {
      if (valid) {
        switch (type.value) {
          case 'addGameChannel':
            {
              const res = await createApi(form.value)
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '添加成功',
                  showClose: true
                })
              }
              getTableData()
              closeDialog()
            }
  
            break
          case 'editGameChannel':
            {
              const res = await updateApi(form.value)
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '编辑成功',
                  showClose: true
                })
              }
              getTableData()
              closeDialog()
            }
            break
          default:
            // eslint-disable-next-line no-lone-blocks
            {
              ElMessage({
                type: 'error',
                message: '未知操作',
                showClose: true
              })
            }
            break
        }
      }
    })
  }
  
  const deleteApiFunc = async(row) => {
    ElMessageBox.confirm('此操作将永久删除此渠道, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async() => {
        const res = await deleteApi(row)
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          if (tableData.value.length === 1 && page.value > 1) {
            page.value--
          }
          getTableData()
        }
      })
  }
  
  </script>
  
  <style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
  </style>
  