<script setup lang="ts">
import { ref, getCurrentInstance, reactive } from "vue";
import { useRouter } 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'
import { user } from "~/store/user";

// #region (constant)
const TABLE_KEY = 'xkj_id'
const URL_CUT = '/xdjx/kbgl_jskb'
const URL_CUT_REF = ref(URL_CUT)
const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
const instance = getCurrentInstance()
const router = useRouter()
// #endregion

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

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'xkj_jsmc': string; // 教师名称
  'xkj_kbmc': string; // 课表名称
  'team_id': string; // 学期编号
  'team_name': string; // 学期名称
  'xkj_scr': string; // 上传人
  'xkj_kbxq_json': string; // 课表详情JSON
  'xxk_kblx': string; // 课表类型
  'xkj_xls': string; // 课表文件
  'xkj_jsbh': string; // 教师编号
  'xkj_img': string; // 课表图片
  'xjj_zgbh':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 = () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选导出文件');exportApi({[TABLE_KEY]:multipleSelection.value.map((item: TYPE_TABLE_FIELD)=>item[TABLE_KEY])?.join()})
}
const handleTableRowBtn_add = () => {
  whichDialogSubmit = 'add'
  dialogForm_Data.value = {}
  dialogVisible_addOrEdit.value = true
}
const handleTableRowBtn_delete = async () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选文件');const resp = await deleteApi(multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY]));if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])
const DetailName = '-KBGL-JSKB-DETAIL'
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_delete = async (scope: { row: TYPE_TABLE_FIELD }) => {
  const resp = await deleteApi(scope.row[TABLE_KEY]);if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}
const handleTableColBtn_detail = (scope: { row: TYPE_TABLE_FIELD }) => {
  router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] } })
}
// #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) {
    const resp = await API_MAP[whichDialogSubmit](<TYPE_TABLE_FIELD>({ ...dialogForm_Data.value, ...extendData }))
    if(resp.code!=='1')return;ElMessage.success('操作成功');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({
  'xkj_jsmc': { required: true, message: '教师名称不能为空', trigger: 'submit' },
  'xkj_kbmc': { required: true, message: '课表名称不能为空', trigger: 'submit' },
  'team_id': { required: true, message: '学期编号不能为空', trigger: 'submit' },
  'team_name': { required: true, message: '学期名称不能为空', trigger: 'submit' },
  'xkj_scr': { required: true, message: '上传人不能为空', trigger: 'submit' },
  'xkj_kbxq_json': { required: true, message: '课表详情JSON不能为空', trigger: 'submit' },
  'xxk_kblx': { required: true, message: '课表类型不能为空', trigger: 'submit' },
  'xkj_xls': { required: true, message: '课表文件不能为空', trigger: 'submit' },
  'xkj_jsbh': { required: true, message: '教师编号不能为空', trigger: 'submit' },
  'xkj_img': { required: false, 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
    }
  }).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, ['xkj_jsmc', 'xkj_kbmc', 'team_id', 'team_name', 'xkj_scr', 'xkj_kbxq_json', 'xxk_kblx', 'xkj_xls', 'xkj_jsbh', 'xkj_img','xjj_zgbh']),
    }
  })
}

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(d) {
  return download(URL_CUT + '/index', {...queryForm_Data.value,...d})
}

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.xkj_jsmc" clearable /></el-form-item>
      <el-form-item label="课表名称"><el-input v-model="queryForm_Data.xkj_kbmc" clearable /></el-form-item>
      <el-form-item label="学期编号"><el-input v-model="queryForm_Data.team_id" clearable /></el-form-item>
      <el-form-item label="学期名称"><el-input v-model="queryForm_Data.team_name" clearable /></el-form-item>
      <el-form-item label="上传人"><el-input v-model="queryForm_Data.xkj_scr" clearable /></el-form-item>
      <el-form-item label="课表详情JSON"><el-input v-model="queryForm_Data.xkj_kbxq_json" clearable /></el-form-item>
      <el-form-item label="课表类型"><el-select v-model="queryForm_Data.xxk_kblx" 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="课表文件"><file-upload v-model:part="queryForm_Data.xkj_xls" /></el-form-item>
      <el-form-item label="教师编号"><el-input v-model="queryForm_Data.xkj_jsbh" clearable /></el-form-item>
      <el-form-item label="课表图片"><file-upload v-model:part="queryForm_Data.xkj_img" /></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 @success="queryApi" :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 type="index" label="序号" width="60" :index="(i: number) => (currentPage - 1) * limit + i + 1" />
        <el-table-column prop="xkj_jsmc" label="教师名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xkj_kbmc" label="课表名称" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="team_id" label="学期编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="team_name" label="学期名称" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="xkj_scr" label="上传人" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="xkj_kbxq_json" label="课表详情JSON" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="xxk_kblx" label="课表类型" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="xkj_xls" label="课表文件" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="xkj_jsbh" label="教师编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="xkj_img" label="课表图片" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" fixed="right">
          <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_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="xkj_jsbh">
        <el-input v-model="dialogForm_Data.xkj_jsbh" clearable />
      </el-form-item> -->
      <el-form-item label="教师名称" prop="xkj_jsmc">
        <!-- <el-input v-model="dialogForm_Data.xkj_jsmc" clearable /> -->
        <remote-select url="/user/main/index" :fields="['user_no','user_realname']"  :d="{user_role_id:'7' ,dept_id:user.dept_id}"   v-model="dialogForm_Data.xjj_zgbh"  v-model:model-name="dialogForm_Data.xkj_jsmc" ></remote-select>
      </el-form-item>
      <el-form-item label="课表名称" prop="xkj_kbmc">
        <el-input v-model="dialogForm_Data.xkj_kbmc" clearable />
      </el-form-item>
      <!-- <el-form-item label="学期编号" prop="team_id">
        <el-input v-model="dialogForm_Data.team_id" clearable />
      </el-form-item> -->
      <el-form-item label="学期名称" prop="team_name">
        <!-- <el-input v-model="dialogForm_Data.team_name" clearable /> -->
        <remote-select to="team" v-model="dialogForm_Data.team_id" v-model:modelName="dialogForm_Data.team_name">
        </remote-select>
      </el-form-item>
      <el-form-item label="上传人" prop="xkj_scr">
        <el-input v-model="dialogForm_Data.xkj_scr" clearable />
      </el-form-item>
      <!-- <el-form-item label="课表详情JSON" prop="xkj_kbxq_json">
        <el-input v-model="dialogForm_Data.xkj_kbxq_json" clearable />
      </el-form-item> -->
      <!-- <el-form-item label="课表类型" prop="xxk_kblx">
        <el-select v-model="dialogForm_Data.xxk_kblx" 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="xkj_xls">
        <file-upload accept=".xlsx,.xls" v-model:part="dialogForm_Data.xkj_xls" >
          <template #tip>
            <div>支持.xlsx,.xls类型文件</div>
          </template>
        </file-upload>
      </el-form-item>

      <el-form-item label="课表图片" prop="xkj_img">
        <file-upload v-model:part="dialogForm_Data.xkj_img" />
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit', { xxk_kblx: '4' })" type="primary">提交
        </el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
