<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 { ElMessage, ElMessageBox } from 'element-plus'
// 变量
const queryParams = ref({
  page:1,
  pageSize:10,
  keyword:''
})
const total = ref(0)
// const dataList = ref([])
const subjectList = ref([])
const dialogFormVisible = ref(false)
const tableData =ref([])
const dialogTitle = ref('')
const type = ref('')
const form = ref({
    name: '',
    parent_id: 0,
    level: 1,
    sort: 0,
    is_elite:-1
  })

const rules = ref({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})
const categoryForm = ref({})
const tree_val = ref(null)
// 生命周期
// getSubject()
onMounted(() => {
  getSubjectList()
})
// 方法
const origin_list = ref([])
async function getSubjectList() {
  const res = await api.getSubjectList(queryParams.value)
  subjectList.value = res.data.records
  if(res.code === 0) {
    subjectList.value = res.data.records
    total.value = res.data.total
    origin_list.value = res.data.records
    subjectList.value = addTreeFormatSubject(subjectList.value)
    // console.log(subjectList.value)
  }
}
const current_categral_id = ref(0) // 当前编辑id
function addTreeFormatSubject(data) {
  if(!data) {
    return []
  }
  data.map( item => {
      item.label = item.name
      item.value = item.id

      if(current_categral_id.value && (item.id === current_categral_id.value || item.parent_id === current_categral_id.value)) {
        item.disabled = true
      }
      else{
        item.disabled = false
      }
      if(item.level === 3) {
        item.disabled = true
      }
      if(item.children) {
        addTreeFormatSubject(item.children)
      }
  })
  return data
}
function onSubmit() {
  getSubjectList()
}
// 排序
// const sortChange = ({ prop, order }) => {
//   if (prop) {
//     if (prop === 'ID') {
//       prop = 'id'
//     }
//     queryParams.value.orderKey = toSQLLine(prop)
//     queryParams.value.desc = order === 'descending'
//   }
//   getSubjectList()
// }
// 批量操作
const handleSelectionChange = (val) => {
  apis.value = val
}
function editApiFunc(row) {
  // 深拷贝？
  for(let prop in form.value) {
    if(row[prop]){
      form.value[prop] = row[prop]
    }
  }
  form.value.id = row.id
  current_categral_id.value = row.id
  subjectList.value = addTreeFormatSubject(origin_list.value)
  // return
  openDialog('edit')
}
function deleteFunc(row) {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    const res = await api.delSubject({
          ids:[row.id]
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      // if (tableData.value.length === 1 && page.value > 1) {
      //   page.value--
      // }
      getSubjectList()
    }
  },() => {
  })
}
function openDialog(key) {
  switch (key) {
    case 'add':
      dialogTitle.value = '新增类型'
      current_categral_id.value = 0
      subjectList.value = addTreeFormatSubject(origin_list.value)
      break
    case 'edit':
      dialogTitle.value = '编辑类型'
      break
    default:
      break
  }
  type.value = key
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const initForm = () => {
  categoryForm.value.resetFields()
  form.value = {
    name: '',
    parent_id: 0,
    level: 1,
    sort: 0,
    is_elite:-1
  }
}
function tree_select_func(e) {
  form.value.level = findLevel(subjectList.value,e)
}
function findLevel(data,val){
  let l_id = 0
  for(let i =0;i<data.length;i++) {
    if(data[i].id === val) {
        l_id = parseInt(data[i].level)+1
        break;
    }
    else{
        if(data[i].children && l_id == 0) {
          l_id = findLevel(data[i].children,val)
        }
    }
  }
  return l_id
}
async function enterDialog() { // 确认创建或修改
  let func_name = ''
  if(type.value === 'add') {
    func_name = 'addSubject'
  }
  else{
    func_name = 'editSubject'
  }
  form.value.sort = parseInt(form.value.sort)
  // return
  const res = await api[func_name](form.value)
  if(res.code === 0 ){
    ElMessage({
      type: 'success',
      message: '操作成功!'
    })
    getSubjectList()
    closeDialog()
  }
}
const onReset = () => {
  queryParams.value = {
    page:1,
    pageSize:10,
    keyword:''
  }
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getSubjectList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getSubjectList()
}
</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.keyword" placeholder="类型名称" />
        </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>
      </div>
      <el-table
        :data="subjectList"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
      >
        <el-table-column prop="name" label="类型名称" />
        <el-table-column prop="level" label="等级" />
        <el-table-column prop="parent_id" label="父级id" />
        <el-table-column label="首页推荐" >
          <template #default="scope">
            {{scope.row.is_elite == 1?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <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="danger"
              link
              @click="deleteFunc(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">
      <!-- <warning-bar title="新增API，需要在角色管理内配置权限才可使用" />-->
      <el-form ref="categoryForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级类型" prop="path">
          <el-tree-select @change="tree_select_func" check-strictly v-model="form.parent_id" :data="subjectList" :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="名称" prop="path">
          <el-input v-model="form.name" placeholder="请输入类型名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="排序" prop="path">
          <el-input type="number" v-model="form.sort" placeholder="排序越小，展示越靠前" autocomplete="off" />
        </el-form-item>
        <el-form-item label="首页推荐" prop="method">
          <el-switch v-model="form.is_elite" :active-value="1" :inactive-value="-1" />
        </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>
<style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
