<script setup lang="ts">
import { ref, getCurrentInstance, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import request, { download } from '~/utils/request';
import { pick } from 'lodash-es';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { AxiosRequestConfig } from 'axios'

// #region (constant)
const TABLE_KEY = 'ym_id'
const URL_CUT = '/yk/main'
const URL_CUT_REF = ref(URL_CUT)
const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
const instance = getCurrentInstance()
const router = useRouter()
const route = useRoute()
// #endregion

// #region (variable)
const loading_table = ref(true)
let whichDialogSubmit: 'add' | 'edit'
// #endregion

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'ym_name': string; // 名称
  'ym_img': string; // 封面
  'ym_brief': string; // 简介
  'ym_sm_id': string; // 学校编号
  'ym_sm_name': string; // 学校名称
  'grade_id': string; // 年级编号
  'subject_id': string; // 学科编号
  'grade_name': string; // 年级名称
  'subject_name': string; // 学科名称
  'ym_cm_id': string; // 班级编号
  'ym_cm_name': string; // 班级名称
  'ym_student_num': string; // 学生数
  'ym_timetable_json': string; // 课表JSON
  'ym_part_teacher': string; // 兼职教师
  'ym_date': string; // 约课日期
  'ym_weekday': string; // 周天
  'ym_lesson_no': string; // 课节次
  'ym_status': string; // 审核状态
  'team_id': string; // 分册
}
// #endregion

// #region (props)
// #endregion

// #region (query row)
const queryForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleQueryFormBtn_search = () => {
  queryApi()
}
const handleQueryFormBtn_clear = () => {
  queryForm_Data.value = {}
}
// #endregion

// #region (table selection)
const multipleSelection = ref<TYPE_TABLE_FIELD[]>([])
const handleSelectionChange = (val: TYPE_TABLE_FIELD[]) => {
  multipleSelection.value = val
}
// #endregion

// #region (table row)
const handleTableRowBtn_import = async ({ file }: { file: File }) => {
  const res = await API_MAP['import']({ file })
  if (res.code === '1') {
    queryApi()
    ElMessage.success(res.msg)
  }
}
const handleTableRowBtn_export = () => {
  exportApi()
}
const handleTableRowBtn_add = () => {
  whichDialogSubmit = 'add'
  dialogForm_Data.value = {}
  dialogVisible_addOrEdit.value = true
}
const handleTableRowBtn_delete = async () => {
  await deleteApi(multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY]))
  queryApi()
}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])
const DetailName = '-SHGL-YKSQ-DSH'
const DetailParam = 'aid'

const handleTableColBtn_edit = async (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  const res = await detailApi(scope.row[TABLE_KEY])
  dialogForm_Data.value = (res.data.one_info)
  dialogVisible_addOrEdit.value = true
}
const handleTableColBtn_audit = (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  dialogForm_Data.value = pick(scope.row, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_audit)])
  dialogVisible_audit.value = true
}
const handleTableColBtn_detail = (scope: { row: TYPE_TABLE_FIELD }) => {
  router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] } })
}
const handleTableColBtn_delete = async (scope: { row: TYPE_TABLE_FIELD }) => {
  await deleteApi(scope.row[TABLE_KEY])
  queryApi()
}
// #endregion

// #region (pagination)
const total = ref(0)
const limit = ref(10)

const currentPage = ref(1)
function handleCurrentChange() {
  queryApi()
}
// #endregion

// #region (dialog base)
const dialogForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleDialogFormBtn_submit = async (formRefKey: string, extendData?: Partial<TYPE_TABLE_FIELD>) => {
  const isValid = await (instance?.refs[formRefKey] as FormInstance).validate((valid: boolean) => valid)
  if (isValid) {
    await API_MAP[whichDialogSubmit](<TYPE_TABLE_FIELD>({ ...dialogForm_Data.value, ...extendData }))
    handleDialogFormBtn_cancel()
    queryApi()
  }
}
const handleDialogFormBtn_cancel = (formRefKey?: string) => {
  dialogVisible_addOrEdit.value = false
  dialogVisible_audit.value = false
}
// #endregion

// #region (dialog add/edit)
const dialogVisible_addOrEdit = ref<boolean>(false)

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'ym_name': { required: true, message: '名称不能为空', trigger: 'submit' },
  'ym_img': { required: true, message: '封面不能为空', trigger: 'submit' },
  'ym_brief': { required: true, message: '简介不能为空', trigger: 'submit' },
  'ym_sm_id': { required: true, message: '学校编号不能为空', trigger: 'submit' },
  'ym_sm_name': { required: true, message: '学校名称不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'subject_id': { required: true, message: '学科编号不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'subject_name': { required: true, message: '学科名称不能为空', trigger: 'submit' },
  'ym_cm_id': { required: true, message: '班级编号不能为空', trigger: 'submit' },
  'ym_cm_name': { required: true, message: '班级名称不能为空', trigger: 'submit' },
  'ym_student_num': { required: true, message: '学生数不能为空', trigger: 'submit' },
  'ym_timetable_json': { required: true, message: '课表JSON不能为空', trigger: 'submit' },
  'ym_part_teacher': { required: true, message: '兼职教师不能为空', trigger: 'submit' },
  'ym_date': { required: true, message: '约课日期不能为空', trigger: 'submit' },
  'ym_weekday': { required: true, message: '周天不能为空', trigger: 'submit' },
  'ym_lesson_no': { required: true, message: '课节次不能为空', trigger: 'submit' },
  'ym_status': { required: true, message: '审核状态不能为空', trigger: 'submit' },
  'team_id': { required: true, message: '分册不能为空', trigger: 'submit' },
})
// #endregion

// #region (dialog audit)
const dialogVisible_audit = ref<boolean>(false)

const dialogForm_Field_audit = reactive<{
  FLAG: keyof TYPE_TABLE_FIELD,
  REASON?: keyof TYPE_TABLE_FIELD
}>({
  FLAG: 'ym_status',
  // REASON:'ym_id'
})

const dialogForm_Ref_audit = ref<FormInstance>()
const dialogForm_Rules_audit = reactive<FormRules>({
  'ym_name': { required: true, message: '名称不能为空', trigger: 'submit' },
  'ym_img': { required: true, message: '封面不能为空', trigger: 'submit' },
  'ym_brief': { required: true, message: '简介不能为空', trigger: 'submit' },
  'ym_sm_id': { required: true, message: '学校编号不能为空', trigger: 'submit' },
  'ym_sm_name': { required: true, message: '学校名称不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'subject_id': { required: true, message: '学科编号不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'subject_name': { required: true, message: '学科名称不能为空', trigger: 'submit' },
  'ym_cm_id': { required: true, message: '班级编号不能为空', trigger: 'submit' },
  'ym_cm_name': { required: true, message: '班级名称不能为空', trigger: 'submit' },
  'ym_student_num': { required: true, message: '学生数不能为空', trigger: 'submit' },
  'ym_timetable_json': { required: true, message: '课表JSON不能为空', trigger: 'submit' },
  'ym_part_teacher': { required: true, message: '兼职教师不能为空', trigger: 'submit' },
  'ym_date': { required: true, message: '约课日期不能为空', trigger: 'submit' },
  'ym_weekday': { required: true, message: '周天不能为空', trigger: 'submit' },
  'ym_lesson_no': { required: true, message: '课节次不能为空', trigger: 'submit' },
  'ym_status': { required: true, message: '审核状态不能为空', trigger: 'submit' },
  'team_id': { required: true, message: '分册不能为空', trigger: 'submit' },
})

// #endregion

// #region (request api):
function queryApi() {
  loading_table.value = true
  return request({
    url: URL_CUT + '/index',
    data: {
      ...queryForm_Data.value,
      limit: limit.value,
      page: currentPage.value,
      ym_status: 3
    }
  }).then((response: { data: { total_rows: string, page_data: TYPE_TABLE_FIELD[] } }) => {
    const { data } = response
    total.value = parseInt(data.total_rows)
    tableData.value = data.page_data
    return response
  }).then(() => {
    loading_table.value = false
  })
}

function addApi(data: TYPE_TABLE_FIELD) {
  return request({
    url: URL_CUT + '/add',
    data: {
      [URL_SUBMIT_KEY]: data,
    }
  })
}

function editApi(data: Partial<TYPE_TABLE_FIELD>) {
  return request({
    url: URL_CUT + '/edit',
    data: {
      [TABLE_KEY]: data[TABLE_KEY],
      [URL_SUBMIT_KEY]: pick(data, ['ym_name', 'ym_img', 'ym_brief', 'ym_sm_id', 'ym_sm_name', 'grade_id', 'subject_id', 'grade_name', 'subject_name', 'ym_cm_id', 'ym_cm_name', 'ym_student_num', 'ym_timetable_json', 'ym_part_teacher', 'ym_date', 'ym_weekday', 'ym_lesson_no', 'ym_status', 'team_id',]),
    }
  })
}

function deleteApi(id: string | string[]) {
  return request({
    url: URL_CUT + '/delete',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function detailApi(id: string) {
  return request({
    url: URL_CUT + '/detail',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function importApi(data: { file: File }) {
  return request({
    $type: 'import',
    url: URL_CUT + '/import',
    data
  } as AxiosRequestConfig)
}

function exportApi() {
  return download(URL_CUT + '/index', queryForm_Data.value)
}

const API_MAP = {
  query: queryApi,
  add: addApi,
  edit: editApi,
  delete: deleteApi,
  detail: detailApi,
  import: importApi,
  export: exportApi,
}
// #endregion

// #region (page init)
function init() {
  queryApi()
}
init()
// #endregion

</script>

<template>
  <div class="card flex-grow flex flex-col">
    <el-form inline :model="queryForm_Data">
      <!-- <el-form-item label="关键字"><el-input v-model="queryForm_Data.keyword" ></el-input></el-form-item> -->
      <el-form-item label="名称">
        <el-input v-model="queryForm_Data.ym_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="封面"><file-upload v-model:part="queryForm_Data.ym_img" /></el-form-item>
      <el-form-item label="简介"><el-input v-model="queryForm_Data.ym_brief" clearable /></el-form-item>
      <el-form-item label="学校编号"><el-input v-model="queryForm_Data.ym_sm_id" clearable /></el-form-item> -->
      <el-form-item label="学校名称">
        <el-input v-model="queryForm_Data.ym_sm_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="年级编号"><el-input v-model="queryForm_Data.grade_id" clearable /></el-form-item> -->
      <!-- <el-form-item label="学科编号"><el-input v-model="queryForm_Data.subject_id" clearable /></el-form-item> -->
      <el-form-item label="年级名称">
        <el-input v-model="queryForm_Data.grade_name" clearable />
      </el-form-item>
      <el-form-item label="学科名称">
        <el-input v-model="queryForm_Data.subject_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="班级编号"><el-input v-model="queryForm_Data.ym_cm_id" clearable /></el-form-item> -->
      <el-form-item label="班级名称">
        <el-input v-model="queryForm_Data.ym_cm_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="学生数"><el-input v-model="queryForm_Data.ym_student_num" clearable /></el-form-item> -->
      <!-- <el-form-item label="课表JSON"><el-input v-model="queryForm_Data.ym_timetable_json" type="textarea" /></el-form-item> -->
      <!-- <el-form-item label="兼职教师"><el-input v-model="queryForm_Data.ym_part_teacher" clearable /></el-form-item> -->
      <el-form-item label="约课日期">
        <el-date-picker v-model="queryForm_Data.ym_date" type="date" value-format="YYYY-MM-DD" clearable />
      </el-form-item>
      <!-- <el-form-item label="周天"><el-select v-model="queryForm_Data.ym_weekday" clearable filterable ><el-option label="星期一" value="1" /><el-option label="星期二" value="2" /><el-option label="星期三" value="3" /><el-option label="星期四" value="4" /><el-option label="星期五" value="5" /></el-select></el-form-item>
      <el-form-item label="课节次"><el-select v-model="queryForm_Data.ym_lesson_no" clearable filterable ><el-option label="第一节(9:00~9:40)" value="1" /><el-option label="第二节(9:50~10:30)" value="2" /><el-option label="第三节(10:45~11:25)" value="3" /><el-option label="第四节(13:40~14:20)" value="4" /><el-option label="第五节(14:35~15:15)" value="5" /><el-option label="第六节(15:25~16:05)" value="6" /></el-select></el-form-item> -->
      <!-- <el-form-item label="审核状态"><el-select v-model="queryForm_Data.ym_status" clearable filterable ><el-option label="待审核" value="1" /><el-option label="已审核" value="2" /><el-option label="不通过" value="3" /></el-select></el-form-item> -->
      <!-- <el-form-item label="分册"><el-select v-model="queryForm_Data.team_id" clearable filterable ><el-option label="上册" value="1" /><el-option label="下册" value="2" /></el-select></el-form-item> -->
      <el-form-item>
        <el-button @click="handleQueryFormBtn_search" type="primary">搜索</el-button>
        <el-button @click="handleQueryFormBtn_clear" type="warning">清空</el-button>
      </el-form-item>
    </el-form>
    <div class="divider"></div>
    <div>
      <!-- <import-button :url="URL_CUT_REF"></import-button> -->
      <el-button @click="handleTableRowBtn_export" type="success">导出</el-button>
      <!-- <el-button @click="handleTableRowBtn_add" type="primary">新增</el-button>
        <el-button @click="handleTableRowBtn_delete" type="danger">删除</el-button> -->
    </div>

    <div class="divider"></div>
    <div class="flex-auto">
      <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading_table"
        element-loading-background="#ffffff70">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="ym_name" label="名称" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="ym_img" label="封面" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="ym_brief" label="简介" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="ym_sm_id" label="学校编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="ym_sm_name" label="学校名称" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="grade_id" label="年级编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="subject_id" label="学科编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="grade_name" label="年级名称" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="subject_name" label="学科名称" width="100" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="ym_cm_id" label="班级编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="ym_cm_name" label="班级名称" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ym_student_num" label="学生数" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ym_timetable_json" label="约课日期" width="360" show-overflow-tooltip>
          <template #default="{row}">
            {{row.ym_timetable_json.replace(',',' ~ ')}}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="ym_part_teacher" label="兼职教师" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="ym_date" label="约课日期" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="ym_weekday" label="周天" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="ym_lesson_no" label="课节次" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="ym_status" label="审核状态" width="100" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="team_id" label="分册" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column label="操作" fixed="right" width="100">
          <template #default="scope">
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_edit(scope)" type="primary">编辑
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_audit(scope)" type="primary">审核
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_detail(scope)" type="primary">详情
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_delete(scope)" type="primary">删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </div>

    <div class="flex justify-end mt-10 py-4">
      <el-pagination :page-size="limit" v-model:current-page="currentPage" @current-change="handleCurrentChange"
        background layout="total, prev, pager, next" :total="total" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible_addOrEdit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
      label-width="120px">
      <el-form-item label="名称" prop="ym_name">
        <el-input v-model="dialogForm_Data.ym_name" clearable />
      </el-form-item>
      <el-form-item label="封面" prop="ym_img">
        <file-upload v-model:part="dialogForm_Data.ym_img" />
      </el-form-item>
      <el-form-item label="简介" prop="ym_brief">
        <el-input v-model="dialogForm_Data.ym_brief" clearable />
      </el-form-item>
      <el-form-item label="学校编号" prop="ym_sm_id">
        <el-input v-model="dialogForm_Data.ym_sm_id" clearable />
      </el-form-item>
      <el-form-item label="学校名称" prop="ym_sm_name">
        <el-input v-model="dialogForm_Data.ym_sm_name" clearable />
      </el-form-item>
      <el-form-item label="年级编号" prop="grade_id">
        <el-input v-model="dialogForm_Data.grade_id" clearable />
      </el-form-item>
      <el-form-item label="学科编号" prop="subject_id">
        <el-input v-model="dialogForm_Data.subject_id" clearable />
      </el-form-item>
      <el-form-item label="年级名称" prop="grade_name">
        <el-input v-model="dialogForm_Data.grade_name" clearable />
      </el-form-item>
      <el-form-item label="学科名称" prop="subject_name">
        <el-input v-model="dialogForm_Data.subject_name" clearable />
      </el-form-item>
      <el-form-item label="班级编号" prop="ym_cm_id">
        <el-input v-model="dialogForm_Data.ym_cm_id" clearable />
      </el-form-item>
      <el-form-item label="班级名称" prop="ym_cm_name">
        <el-input v-model="dialogForm_Data.ym_cm_name" clearable />
      </el-form-item>
      <el-form-item label="学生数" prop="ym_student_num">
        <el-input v-model="dialogForm_Data.ym_student_num" clearable />
      </el-form-item>
      <el-form-item label="课表JSON" prop="ym_timetable_json">
        <el-input v-model="dialogForm_Data.ym_timetable_json" type="textarea" />
      </el-form-item>
      <el-form-item label="兼职教师" prop="ym_part_teacher">
        <el-input v-model="dialogForm_Data.ym_part_teacher" clearable />
      </el-form-item>
      <el-form-item label="约课日期" prop="ym_date">
        <el-input v-model="dialogForm_Data.ym_date" clearable />
      </el-form-item>
      <el-form-item label="周天" prop="ym_weekday">
        <el-select v-model="dialogForm_Data.ym_weekday" clearable filterable>
          <el-option label="星期一" value="1" />
          <el-option label="星期二" value="2" />
          <el-option label="星期三" value="3" />
          <el-option label="星期四" value="4" />
          <el-option label="星期五" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="课节次" prop="ym_lesson_no">
        <el-select v-model="dialogForm_Data.ym_lesson_no" clearable filterable>
          <el-option label="第一节(9:00~9:40)" value="1" />
          <el-option label="第二节(9:50~10:30)" value="2" />
          <el-option label="第三节(10:45~11:25)" value="3" />
          <el-option label="第四节(13:40~14:20)" value="4" />
          <el-option label="第五节(14:35~15:15)" value="5" />
          <el-option label="第六节(15:25~16:05)" value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="ym_status">
        <el-radio-group v-model="dialogForm_Data.ym_status">
          <el-radio label="1">待审核</el-radio>
          <el-radio label="2">已审核</el-radio>
          <el-radio label="3">不通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分册" prop="team_id">
        <el-radio-group v-model="dialogForm_Data.team_id">
          <el-radio label="1">上册</el-radio>
          <el-radio label="2">下册</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogVisible_audit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_audit" :rules="dialogForm_Rules_audit" label-width="120px">
      <el-form-item label="状态">
        <el-radio-group v-model="dialogForm_Data[dialogForm_Field_audit.FLAG]">
          <el-radio label="1">通过</el-radio>
          <el-radio label="2">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="原因" v-show="dialogForm_Data[dialogForm_Field_audit.FLAG] === '1'">
        <el-input type="textarea" v-model="dialogForm_Data[dialogForm_Field_audit.REASON]" :rows="5" />
      </el-form-item> -->
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_audit')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_audit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
