<script setup>
// 引入依赖
import api from '@/api/course'
import custom from '@/utils/custom'
// import { toSQLLine } from '@/utils/stringFun'
import WarningBar from '@/components/warningBar/warningBar.vue'
import {ref,onMounted } from 'vue'
import {formatDate} from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 变量
const queryParams = ref({
  page:1,
  pageSize:10,
  name:'',
  status:'',
  subject:'',
  teacherId:0
})
const subjectParams = ref({
    page:1,
    pageSize:100,
})
const tableData = ref([])
const subjectList = ref([])
const deleteVisible = ref(false)
const course_ids = ref([])
const total = ref(0)
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const form =ref({})
const rules = ref({
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
})
const course_id = ref(0)
// 生命周期
onMounted(() => {
  queryParams.value.teacherId = route.params.user_id
  getCourseList()
  getSubject()
})
// 方法
async function getCourseList() {
  const res = await api.getTeacherCourseList(queryParams.value)
  if(res.code === 0) {
    tableData.value = res.data.records
  }
}
async function getSubject(){ // 获取课程分类
  const res = await api.getSubjectList(subjectParams.value)
  if(res.code === 0) {
    // subjectList.value = custom.getStdSubject(res.data.records)
    subjectList.value = custom.addTreeFormatSubject(res.data.records,'id')
    // console.log(subjectList.value)
  }
}
function onSubmit() {
  getCourseList()
}
const onReset = () => {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    status:'',
    subject:''
  }
}
function openDialog(type) {
  let params = {}
  switch (type){
    case 'add':
      dialogTitle.value = '新增课程'
      break;
    case 'edit':
      params.course_id = course_id.value
      dialogTitle.value = '编辑课程'
      break;
  }
  router.push({name:'addCourse',params})
}
async function onDelete() {
  console.log(course_ids.value)
  const ids = course_ids.value.map(item => item.course_id)
  const res = await api.delCourse({ 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
    getCourseList()
  }
}
const handleSelectionChange = (val) => {
  // console.log(val)
  course_ids.value = val
}
function editCourseFunc(row) {
  course_id.value = row.course_id
  openDialog('edit')
}
function deleteCourseFunc(row) {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    const res = await api.delCourse({
          ids:[row.course_id]
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      // if (tableData.value.length === 1 && page.value > 1) {
      //   page.value--
      // }
      getCourseList()
    }
  },() => {
  })
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getCourseList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getCourseList()
}
function closeDialog(){
  dialogFormVisible.value = false
}
function enterDialog() {

}
function viewCourseFunc(row) { // 查看课程
  router.push({name:'viewCourse',params:{course_id:row.course_id}})
}
// 审核相关
// 审核相关
const verifyVisible = ref(false)
const verifyForm = ref({})
const verifyCourse = ref(null)

function checkCourseFunc(row) { // 审核
  // console.log(row)
  verifyCourse.value = row
  if(row.status == 2 || row.status == 4 ) { // 未审核 或 未通过
    verifyForm.value.is_pass = -1
  }
  else{
    verifyForm.value.is_pass = 1
  }
  verifyForm.is_pass = row.status
  verifyVisible.value = true
}
function transferStateFromVerify(v_state) {
  let state = 0
  if(v_state == 1) { // 审核通过
    // state = verifyCourse.value.status
    state = 3
  }
  else{ // 审核拒绝
    state = 4
  }
  return state
}
function closeVerifyVisibleDialog() {
  verifyVisible.value = false
}
async function enterVerifyDialog() { // 审核提交
  const status = transferStateFromVerify(verifyForm.value.is_pass)
  console.log(verifyForm.value)
  const res = await api.verifyCourse({
    course_id:verifyCourse.value .course_id,
    status
  })
  if(res.code === 0) {
    ElMessage({
        type: 'success',
        message: '操作成功!'
    })
    closeVerifyVisibleDialog()
    getCourseList()
  }
  // else{
  //   ElMessage({
  //     type: 'warning',
  //     message: res.msg
  //   })
  // }

}
</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.name" placeholder="根据课程名称进行查询" />
        </el-form-item>
        <el-form-item label="课程分类">
<!--          <el-select v-model="queryParams.subject" clearable placeholder="请选择">-->
<!--            <el-option-->
<!--              v-for="item in subjectList"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            />-->
<!--          </el-select>-->
          <el-tree-select v-model="queryParams.subject" :data="subjectList" :render-after-expand="false" />
        </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('add')">新增</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="!course_ids.length" style="margin-left: 10px;" @click="deleteVisible = true">删除</el-button>-->
<!--          </template>-->
<!--        </el-popover>-->
      </div>
      <!--      数据列表-->
      <el-table :data="tableData" border @selection-change="handleSelectionChange">
<!--        <el-table-column-->
<!--          type="selection"-->
<!--          width="55"-->
<!--        />-->
        <el-table-column align="left" label="id" min-width="60" prop="course_id" sortable="custom" />
        <el-table-column align="left" label="名称" min-width="150" prop="name" />
        <el-table-column align="left" label="科目" min-width="150" prop="subject" />
        <el-table-column align="left" label="价格" min-width="150">
          <template #default="scope">{{scope.row.price/100}}</template>
        </el-table-column>
        <el-table-column align="left" label="状态" min-width="150" prop="status">
          <template #default="scope">
            {{scope.row.status == 1?'上架':scope.row.status == 2?'待审核':scope.row.status == 3?'通过':scope.row.status == 4?'未通过':'下架'}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="是否精品" min-width="150" prop="is_boutique">
          <template #default="scope">
            {{scope.row.is_sift === 1? '是':'否'}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间" min-width="150">
          <template #default="scope">
            {{formatDate(scope.row.CreatedAt)}}
          </template>
        </el-table-column>

<!--        <el-table-column align="left" fixed="right" label="操作" width="200">-->
<!--          <template #default="scope">-->
<!--            <el-button-->
<!--              icon="view"-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="viewCourseFunc(scope.row)"-->
<!--            >预览</el-button>-->
<!--            <el-button-->
<!--              icon="edit"-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="editCourseFunc(scope.row)"-->
<!--            >查看</el-button>-->
<!--            <el-button-->
<!--               v-if="scope.row.status === 2"-->
<!--              icon="check"-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="checkCourseFunc(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="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
      <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="课程简介" prop="introduction">
          <el-input v-model="form.introduction" autocomplete="off" />
        </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>
    <!-- 审核窗口-->
    <el-dialog v-model="verifyVisible" :before-close="closeVerifyVisibleDialog" title="审核课程">
      <el-form :model="verifyForm" label-width="80px">
        <el-form-item label="是否通过" prop="is_free">
          <el-switch v-model="verifyForm.is_pass" active-text="通过" inactive-text="拒绝" :active-value="1" :inactive-value="-1"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeVerifyVisibleDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterVerifyDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
