<script setup>
// 引入依赖
// import api from '@/api/course'
// import com_api from '@/api/common'
// import WarningBar from '@/components/warningBar/warningBar.vue'
import _ from "lodash"
import api from '@/api/examination'
import { ref, onMounted, watch, inject, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// import chapterCom from '../components/chapter.vue'
const props = defineProps(['exam_types','exam_id'])
const emit = defineEmits(['addFunc'])
// const history_num = ref('')
// import { clients, getNowDate } from '@/utils'
import custom from '@/utils/custom'
// import { getToken } from '@/utils/auth'
// 监听
watch(props,(val1,val2) => {
  has_exam_types.value = _.cloneDeep(val1.exam_types) || []
  queryParams.value.examId = val1.exam_id
})
// 变量
const has_exam_types = ref(_.cloneDeep(props.exam_types) || [])

const drawer = ref(false)
const queryParams =ref({
  page:1,
  pageSize:10,
  term:'',
  persons:'',
  examId:''
})
const tableData =ref([])
const total = ref(0)
const dfVisible = ref(false)
const type_list = ref([])
// 生命周期
onMounted(() => {
  queryParams.value.examId = props.exam_id
  getExamGroupList()
})
// 方法
async function getExamGroupList() {
  const res = await api.getExamGroupList(queryParams.value)
  if(res.code === 0) {
    type_list.value = res.data.records
    total.value = res.data.total
    console.log('子组件获取行为')

    // if(type_list.value.length==0 && has_exam_types.value.length > 0) {
    //    type_list.value = _.cloneDeep(has_exam_types.value)
    // }
    // else{
    //
    // }
  }
}
function chooseChapterChildExercises() {
  has_exam_types.value = _.cloneDeep(props.exam_types) || []
  drawer.value = true
  onSubmit()
}
function onSubmit() {
  queryParams.value.page = 1
  getExamGroupList()
}
function onReset() {
  queryParams.value = {
    page:1,
    pageSize:10,
    term:'',
    persons:'',
    examId:props.exam_id
  }
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getExamGroupList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getExamGroupList()
}

const multipleTableRef = ref(null)
function closeDf() {
  gform.value = {}
  dfVisible.value = false
}
// 新增组别
const rules = ref({
  persons: [{ required: true, message: '请输入报名人数', trigger: 'blur' }]
})
const gform = ref({})
const times = ref(1)
const dlTitle = ref('新增组别')
function addWindow() {
  edit_flag.value = false
  openWindow()
}
function openWindow() {
  dfVisible.value = true
}
function oFunc(val) {
  if(times.value+val<1 || times.value+val>9) {
    return
  }
  else{
    times.value+=val
  }
}
function checkFunc(row) { // 检查合法性
  let flag = false
  // for(let item of has_exam_types.value) {
  //     if(item.persons == row.persons) { // 相同人数（级别）
  //       if( item.expiry_date > Date.parse(new Date())) { // 没有过期
  //         flag = false
  //       }
  //     }
  // }
  return flag
}
function assigntTermFunc() { // 赋值期数
  let term = 1
  for(let item of has_exam_types.value) {
      if(item.persons == gform.value.persons) { // 相同人数（级别）
        term++
      }
  }
  return term
}
function enterDb() { // 确认新增/编辑
  // if(edit_flag.value) { // 编辑
  //
  // }
  // else{ // 新增
  //   // let f = checkFunc(gform.value)
  //   // if(!f) { // 有相同人数且没有过期,无法再次创建
  //   //   ElMessage.error('该级别组数已存在!')
  //   //   return
  //   // }
  // }
  if(!edit_flag.value) { // 新增
    gform.value.term = assigntTermFunc()
    // 添加临时id
    gform.value.temp_id = Date.parse(new Date())
    has_exam_types.value.push(_.cloneDeep(gform.value))
    type_list.value.push(_.cloneDeep(gform.value))
  }
  else{ // 编辑
    if(gform.value.temp_id) { // 临时数据编辑
      for(let i=0; i<has_exam_types.value.length;i++ ) {
        if(has_exam_types.value[i].temp_id && has_exam_types.value[i].temp_id === gform.value.temp_id) {
            has_exam_types.value[i] = _.cloneDeep(gform.value)
            break;
        }
      }
      for(let i=0; i<type_list.value.length;i++ ) {
        if(type_list.value[i].temp_id && type_list.value[i].temp_id === gform.value.temp_id) {
            type_list.value[i] = _.cloneDeep(gform.value)
            break;
        }
      }
    }
    else{ // 根据id编辑
      for(let i=0; i<has_exam_types.value.length;i++ ) {
        if(has_exam_types.value[i].exam_id === gform.value.exam_id) {
            has_exam_types.value[i] = _.cloneDeep(gform.value)
            break;
        }
      }
      for(let i=0; i<type_list.value.length;i++ ) {
        if(type_list.value[i].exam_id === gform.value.exam_id) {
            type_list.value[i] = _.cloneDeep(gform.value)
            break;
        }
      }
    }
  }
  closeDf()
}
function addFunc() { // 确认提交
  emit('addFunc',has_exam_types.value)
  drawer.value = false
}
function changeFunc() {
  gform.value.first = gform.value.persons
  gform.value.second = gform.value.persons*0.04
  gform.value.third = gform.value.persons*0.01
}
const edit_flag = ref(false)
function editGroupFunc(row) {
  dlTitle.value = '编辑组别'
  edit_flag.value = true
  gform.value = _.cloneDeep(row)
  openWindow()
}
function delGroupFunc(row) { // 删除组别
  let del_index = -1
  for(let i=0;i<has_exam_types.value.length;i++) {
    if(has_exam_types.value[i].exam_type_id === row.exam_type_id) {
      del_index = i;
      break;
    }
  }
  has_exam_types.value.splice(del_index,1)
  // 当前展示列表==
  let del_index2 = -1
  for(let i=0;i<type_list.value.length;i++) {
    if(type_list.value[i].exam_type_id === row.exam_type_id) {
        del_index2 = i;
        break;
    }
  }
  type_list.value.splice(del_index2,1)
}
function close_draw() {
  has_exam_types.value = _.cloneDeep(props.exam_types) || []
}
</script>
<template>
  <div>
    <el-button v-if="has_exam_types.length==0" size="small" @click="chooseChapterChildExercises">添加组别</el-button>
    <el-button v-else size="small" @click="chooseChapterChildExercises" type="plain">点击查看（已发布{{has_exam_types.length}}组）</el-button>
    <el-drawer v-model="drawer" @close="close_draw" title="组别库" size="60%">
      <div class="drawer-section">
        <!-- 搜索框-->
        <div class="search-box gva-btn-list">
          <el-form ref="searchForm" :inline="true" :model="queryParams">
            <el-form-item label="分组历史">
              <el-input type="number" v-model="queryParams.term" placeholder="请输入分组历史期数" />
            </el-form-item>
            <el-form-item label="组别分类">
              <el-select v-model="queryParams.persons" clearable placeholder="请选择">
                <el-option
                  v-for="item in custom.getExamGroupType()"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </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-button size="small" type="primary" icon="plus" @click="addWindow">新增</el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <!--      数据列表-->
        <div class="list-box">
          <el-table ref="multipleTableRef"  :data="type_list">
            <el-table-column align="left" label="人数级别" min-width="150" prop="persons">
              <template #default="scope">{{custom.getSTdPerson(scope.row.persons)}}</template>
            </el-table-column>
            <el-table-column align="left" label="开始时间" min-width="150" prop="expiry_date">
              <template #default="scope">{{custom.timestampToDate2(scope.row.start_date)}}</template>
            </el-table-column>
            <el-table-column align="left" label="截止时间" min-width="150" prop="expiry_date">
              <template #default="scope">{{custom.timestampToDate2(scope.row.expiry_date)}}</template>
            </el-table-column>
            <el-table-column align="left" label="公开时间" min-width="150" prop="public_date">
              <template #default="scope">{{custom.timestampToDate2(scope.row.public_date)}}</template>
            </el-table-column>
            <el-table-column align="left" label="版本" min-width="150" prop="status">
              <template #default="scope">
                第{{scope.row.term}}期
              </template>
            </el-table-column>
            <el-table-column align="left" label="报名人数" min-width="150" prop="enroll_num" />
            <el-table-column align="left" label="提交人数" min-width="150" prop="finish_num" />
<!--            <el-table-column align="left" fixed="right" label="操作" width="200">-->
<!--              <template #default="scope">-->
<!--                <el-button-->
<!--                  icon="edit"-->
<!--                  size="small"-->
<!--                  type="primary"-->
<!--                  link-->
<!--                  @click="editGroupFunc(scope.row)"-->
<!--                >编辑</el-button>-->
<!--                <el-button-->
<!--                  icon="delete"-->
<!--                  size="small"-->
<!--                  type="danger"-->
<!--                  link-->
<!--                  v-if="!checkFunc(scope.row)"-->
<!--                  @click="delGroupFunc(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>
        <!--  按钮-->
        <div class="btn-box" style="text-align: right">
          <el-button size="small" type="primary" @click="addFunc">确 认</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog v-model="dfVisible" :before-close="closeDf" :title="dlTitle">
      <el-form ref="apiForm" :model="gform" :rules="rules" label-width="80px">
        <el-form-item label="报名人数" >
          <el-select @change="changeFunc" v-model="gform.persons" clearable placeholder="请选择">
            <el-option
              v-for="item in custom.getExamGroupType()"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          <div class="more-info-text" v-if="gform.persons">
            第一名：{{gform.first}}元；第二名：{{gform.second}}元；第三名：{{gform.third}}元。（*满员参加的情况下）
          </div>
<!--          <div class="operator-box" >-->
<!--            <div class="ob-btn ob-reduce" @click="oFunc(-1)">-->
<!--              <el-icon color="#000"><Minus /></el-icon>-->
<!--            </div>-->
<!--            <div class="ob-input">-->
<!--              {{times}}-->
<!--            </div>-->
<!--            <div class="ob-btn ob-add" @click="oFunc(1)">-->
<!--              <el-icon color="#000"><Plus /></el-icon>-->
<!--            </div>-->
<!--          </div>-->
        </el-form-item>
        <el-form-item label="截止时间" >
<!--          <el-date-picker class="oi-item" style="margin-left:5px"-->
<!--            v-model="gform.expiry_date"-->
<!--            type="date"-->
<!--            placeholder="截至日期"-->
<!--            format="YYYY-MM-DD"-->
<!--            value-format="x"-->
<!--          />-->
          <el-date-picker
            v-model="gform.expiry_date"
            type="datetime"
            placeholder="截至日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
          />
        </el-form-item>

        <el-form-item label="公开时间" >
<!--          <el-date-picker class="oi-item" style="margin-left:5px"-->
<!--            v-model="gform.public_date"-->
<!--            type="date"-->
<!--            placeholder="截至日期"-->
<!--            format="YYYY-MM-DD"-->
<!--            value-format="x"-->
<!--          />-->
          <el-date-picker
            v-model="gform.public_date"
            type="datetime"
            placeholder="公开时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDf">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDb">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.el-form-item{
    margin-bottom: 18px !important;
  }
</style>
<style lang="scss" scoped>
  .more-info-text{
    color: gray;
    font-size: 12px;
    margin: 0 10px;
  }
  .operator-box{
    display: flex;
    align-items: center;
    border: 1px solid #dfdfdf;
    border-radius: 5px;
    margin-left: 10px;
    .ob-btn{
      padding: 0 5px;
      background: #dfdfdf;
      cursor: pointer;
    }
    .ob-input{
      padding: 0 10px;
    }
  }
  .drawer-section{
    padding: 10px;
  }
</style>
