<template>
  <div>
    <div class="gva-search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item>
            <el-select v-model="searchInfo.searchKey"  >
              <el-option
                v-for="item in searchOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchInfo.name" 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-btn-list">
          <el-button size="small" icon="refresh" @click="onReset">刷新</el-button>
          <el-button size="small" type="primary" icon="plus" @click="openDialog('addResponsiblePerson')">新增</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>
    <div class="gva-table-box">
      <el-table
        :data="tableData"
        @sort-change="sortChange" 
        @selection-change="handleSelectionChange"
      >
      <el-table-column
            type="selection"
            width="55"
          />
        <el-table-column align="center" label="头像" min-width="100">
          <template #default="scope">
            <CustomPic style="margin-top:8px" :pic-src="scope.row.img" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="姓名" min-width="150" prop="name" />
        <el-table-column align="left" label="昵称" min-width="150" prop="nickname" />
        <el-table-column align="left" label="部门名称" min-width="150" prop="department_name" />
        <el-table-column align="left" label="手机号码" min-width="150" prop="mobile_phone_number" />
        <el-table-column align="left" label="游戏数量" min-width="150" prop="game_counts" />
        <el-table-column align="left" label="备注" min-width="150" prop="remark" />
        <el-table-column align="center" label="状态" min-width="150" prop="state" >
          <template #default="scope">
            <el-button size="small"
            :type="scope.row.state == 2 ? 'danger' : 'success'">
            {{scope.row.state == 2? '禁用' : '启用'}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间" min-width="200" prop="createTime" 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"
      
      custom-class="user-dialog"
      :before-close="closeDialog"
      :title="dialogTitle"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div style="height:60vh;overflow:auto;padding:0 12px;">
        <el-form ref="userForm" :rules="rules" :model="userInfo" label-width="80px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userInfo.name" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
          <el-form-item label="部门" prop="department_name">
            <el-input v-model="userInfo.department_name" />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile_phone_number">
            <el-input v-model="userInfo.mobile_phone_number" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="userInfo.remark" />
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-radio-group v-model="userInfo.state" class="ml-4">
              <el-radio :label="1"  size="large">开启</el-radio>
              <el-radio :label="2"  size="large">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="头像" label-width="80px">
            <div style="display:inline-block" @click="openHeaderChange">
              <img v-if="userInfo.img" class="header-img-box" :src="(userInfo.img && userInfo.img.slice(0, 4) !== 'http')?path+userInfo.img:userInfo.img">
              <div v-else class="header-img-box">从媒体库选择</div>
            </div>
          </el-form-item>

        </el-form>

      </div>

      <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>
    <ChooseImg ref="chooseImg" :target="userInfo" :target-key="`img`" />
  </div>
</template>

<script>
export default {
  // name: 'User',
  // state: 0,
}
</script>

<script setup>

import {
  getApiById,
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  deleteApisByIds
} from '@/api/responsiblePerson'
import { toSQLLine } from '@/utils/stringFun'
import CustomPic from '@/components/customPic/customIndex.vue'
import ChooseImg from '@/components/chooseImg/index.vue'
import warningBar from '@/components/warningBar/warningBar.vue'

import { nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import User from '../superAdmin/user/user.vue'


  const form = ref({

  })
  const     searchOptions = ref([
    {
      value: 'name',
      label: '姓名',

    },
  ])
  const type = ref('')
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const tableData = ref([])
  const searchInfo = ref({
    searchKey:"name",
  })
  
  const onReset = () => {
    searchInfo.value = {}
  }



 // 搜索
  
 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 apis = ref([])
  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 userInfo = ref({
    name: '',
    nickname: '',
    department_name: '',
    mobile_phone_number: '',
    remark: '',
    state: 0,
    img: '',
  })
  const path = ref(import.meta.env.VITE_BASE_API + '/')



  const userForm = ref(null)
  const initForm = () => {
    userForm.value.resetFields()
    userInfo.value = {
      name: '',
      nickname: '',
      department_name: '',
      mobile_phone_number: '',
      remark: '',
      state: 0,
      img: '',
    }
  }
  
  const dialogTitle = ref('新增Api')
  const dialogFormVisible = ref(false)
  const openDialog = (key) => {
    switch (key) {
      case 'addResponsiblePerson':
        dialogTitle.value = '新增'
        break
      case 'editResponsiblePerson':
        dialogTitle.value = '编辑'
        break
      default:
        break
    }

    type.value = key
    dialogFormVisible.value = true
  }
  const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
    userInfo.value.img = ''
  }
  
  const editApiFunc = async(row) => {
    const res = await getApiById({ id: row.id })
    userInfo.value = res.data.responsible_person
    openDialog('editResponsiblePerson')
  }
  
  const enterDialog = async() => {
    userForm.value.validate(async valid => {
      if (valid) {
        switch (type.value) {
          case 'addResponsiblePerson':
            {
              const res = await createApi(userInfo.value)
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '添加成功',
                  showClose: true
                })
              }
              getTableData()
              closeDialog()
            }
  
            break
          case 'editResponsiblePerson':
            {
              const res = await updateApi(userInfo.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 chooseImg = ref(null)
  const openHeaderChange = () => {
    chooseImg.value.open()
  } 

  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 lang="scss">
.user-dialog {
  .header-img-box {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  border-radius: 20px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
}
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.nickName{
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.pointer{
  cursor: pointer;
  font-size: 16px;
  margin-left: 2px;
}
</style>
