
<script setup>
// 引入依赖
import api from '@/api/market'
import custom from '@/utils/custom'
import capi from '@/api/common'
import {formatDate} from '@/utils/format'
import {ref,onMounted,provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 地区
import cityList from '@/utils/city.json'
// store
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// 变量
// const path = ref(import.meta.env.VITE_BASE_API)
const queryParams = ref({
  page:1,
  pageSize:10,
  key:'',
  province:''
})
// const subjectParams = ref({
//     page:1,
//     pageSize:100,
// })
const state_arr = ref([
    {
      name:'申请中',
      id:1
    },
    {
      name:'拒绝',
      id:2
    },
    {
      name:'同意',
      id:3
    }
])
const tableData = ref([])
const deleteVisible = ref(false)
const total = ref(0)
// const dialogFormVisible = ref(false)
// const dialogTitle = ref('')
// const form =ref({})
// const rules = ref({
//   name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
// })
const question_id = ref(0)
const content = ref(null)
const manager_ids = ref([])
const user_list = ref([])
// 生命周期
onMounted(() => {
  getManagerList()
  // getUserList()
})
// provide('subjectList', subjectList)
// provide('current_subject', current_subject)
// 方法
// async function getUserList() {
//   const res = await capi.getUserList({
//     page:1,
//     pageSize:1000
//   })
//   if(res.code === 0) {
//     user_list.value = res.data.records
//   }
// }
async function getManagerList() {
  const res = await api.getManagerList(queryParams.value)
  if(res.code === 0) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
// async function getSubject(){ // 获取课程分类
//   const res = await capi.getSubjectList(subjectParams.value)
//   if(res.code === 0) {
//     subjectList.value = custom.getStdSubject(res.data.records)
//   }
// }
function onSubmit() {
  getManagerList()
}
const onReset = () => {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    status:'',
    subject:''
  }
}
async function onDelete() {
  const ids = manager_ids.value
  const res = await api.delManager({ manager_ids:ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    deleteVisible.value = false
    getManagerList()
  }
}
const handleSelectionChange = (val) => {
  manager_ids.value = val.map((item) => {
      return item.user_id
  })
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getManagerList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getManagerList()
}
function viewManagerFunc(row) { // 查看详情
  router.push({name:'managerDetail',params:{id:row.user_id}})
}
async function delFunc(row) {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    const res = await api.delManager({
          ids:[row.user_id]
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getManagerList()
    }
  },() => {
  })
}
// 新增 & 编辑 相关
const dialogVisible = ref(false)
const mForm = ref({province: 0})
const mFormRef = ref(null)
const mFormRules = ref({
  // province: [{ required: true, message: '请选择管辖区域', trigger: 'blur' }],
  user_id: [{ required: true, message: '请选择用户', trigger: 'blur' }]
})
function openDialog() {
  mForm.value = {province:0}
  dialogVisible.value = true
}
function addOk() { // 添加主管
  // console.log(mForm.value)
  submitForm(mFormRef.value)
}
async function submitForm(formEl) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) { // 验证通过
      // console.log('submit!')
      saveData()
    } else {
      // console.log('请填写完整信息!', fields)
    }
  })
}
async function saveData() {
  // console.log(mForm.value);return
  const res = await api.addManager(mForm.value)
  if(res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg
      })
      getManagerList()
      dialogVisible.value = false
  }
}
/*搜索用户相关*/
const selectLoading = ref(false)
async function remoteMethod(query) {
  selectLoading.value = true
  const res = await capi.searchUserList({
    key:query
  })
  selectLoading.value = false
  if(res.code === 0) {
    user_list.value = res.data
  }
}
</script>
<template>
  <div>
    <!--    搜索框-->
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="queryParams">
        <el-form-item label="主管名称">
          <el-input v-model="queryParams.key" placeholder="根据主管名称进行查询" />
        </el-form-item>
        <!-- <el-form-item label="管辖区域">
          <el-select v-model="queryParams.province" clearable placeholder="请选择">
            <el-option
              v-for="(item,index) in cityList"
              :key="item.province"
              :label="item.province"
              :value="index"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--    表格数据-->
    <div class="gva-table-box">
      <!--      批量操作-->
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="openDialog()">新增</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" size="small" type="danger" :disabled="!manager_ids.length" style="margin-left: 10px;" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>
      <!--      数据列表-->
      <el-table border :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="ID"  prop="user_id" sortable="custom" />
        <el-table-column align="center" min-width="150" label="姓名" prop="nickname" />
        <el-table-column align="center" label="开通时间" min-width="150" >
          <template #default="scope">
            {{formatDate(scope.row.CreatedAt)}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="手机号" min-width="150" prop="phone" />
        <!-- <el-table-column align="center" label="负责区域" min-width="150">
          <template #default="scope">
            {{scope.row.province>-1?cityList[scope.row.province].province:'无'}}
          </template>
        </el-table-column> -->
        <el-table-column align="center" min-width="150" label="域内市场助教" prop="assistant_num" />
        <el-table-column align="center" min-width="150" label="域内市场学员" prop="student_num" />
        <el-table-column align="center" label="课程订单" prop="course_num" />
        <el-table-column align="center" label="佣金" prop="course_income" />
        <el-table-column align="center" label="试卷订单" prop="exam_num" />
        <el-table-column align="center" label="佣金" prop="exam_income" />

        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              icon="view"
              size="small"
              type="primary"
              link
              @click="viewManagerFunc(scope.row)"
            >查看</el-button>
            <el-button
              icon="delete"
              size="small"
              type="danger"
              link
              @click="delFunc(scope.row)"
            >关闭</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.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="dialogVisible"
    title="添加主管"
    width="30%"
    >
      <el-form ref="mFormRef" class="form-box" :model="mForm" :rules="mFormRules" label-width="80px">
        <!-- <el-form-item label="选择区域" prop="province">
          <el-select v-model="mForm.province" clearable placeholder="请选择">
            <el-option
              v-for="(item,index) in cityList"
              :key="item.province"
              :label="item.province"
              :value="index"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="用户ID" prop="user_id">
          <el-select
            v-model="mForm.user_id"
            filterable
            remote
            reserve-keyword
            placeholder="搜索用户"
            remote-show-suffix
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in user_list"
              :key="item.user_id"
              :label="item.nickname"
              :value="item.user_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addOk">添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
  .avatar-box{
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 1px solid #dbdbdb;
  }
  .e-img{
    width: 150px;
    height: 100px;
  }
  .option-item{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
