<script setup lang="ts">
// import { ref } from "vue";
// import request, { download } from '~/utils/request';
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'

// #region (constant)
// const TABLE_KEY_D = 'xsk_id'
// const URL_CUT_D = '/xdjx/stxkgl_kcpj'
// #endregion

// #region (type)
// type TYPE_TABLE_FIELD_D = {
//   [TABLE_KEY_D]: string;
//   'xsk_kcpjmc': string; // 课程评价名称
//   'xsk_kcpjlx': string; // 评价类型
//   'xsk_cjr': string; // 创建人
//   'xsk_cjsj': string; // 创建时间
//   'xsxk_id': string; // 所属课程编号
// }
// #endregion

// #region (variable)
const loading = ref(true)
// #endregion

// #region (props)
const props = defineProps<{
  aid: string,
  bid: string,
}>()
// #endregion

// function detailApi_D(_id: string) {
//   return request({
//     url: URL_CUT_D + '/detail',
//     data: {
//       [TABLE_KEY_D]: _id,
//     }
//   })
// }

// const detail_Data = ref<TYPE_TABLE_FIELD_D>()





// #region (constant)
const TABLE_KEY = 'xskp_id'
const URL_CUT = '/xdjx/stxkgl_kcpj_pjjl'
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;
  'xskp_xsxm': string; // 学生姓名
  'xskp_xsxh': string
  'xskp_pf': string; // 评分
  'xskp_py': string; // 评语
  'grade_id': string; // 年级编号
  'grade_name': string; // 年级名称
  'class_id': string; // 班级编号
  'class_name': string; // 班级名称
  'xsxk_id': string; // 所属课程编号
  'xsk_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 = () => {
  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 = {
    xsk_id: props.bid,
    xsxk_id: props.aid
  }
  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 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()
}
// #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
}
// #endregion

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

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'xskp_xsxm': { required: true, message: '学生姓名不能为空', trigger: 'submit' },
  'xskp_pf': { required: true, message: '评分不能为空', trigger: 'submit' },
  'xskp_py': { required: true, message: '评语不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'class_id': { required: true, message: '班级编号不能为空', trigger: 'submit' },
  'class_name': { required: true, message: '班级名称不能为空', trigger: 'submit' },
  'xsxk_id': { required: true, message: '所属课程编号不能为空', trigger: 'submit' },
  'xsk_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,
      xsxk_id: props.aid,
      xsk_id: props.bid,
    }
  }).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, ['xskp_xsxm', 'xskp_xsxh', 'xskp_pf', 'xskp_py', 'grade_id', 'grade_name', 'class_id', 'class_name', 'xsxk_id', 'xsk_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(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)
async function init() {
  // const res = await detailApi_D(props.bid)
  // detail_Data.value = (res.data.one_info)
  queryApi()

  // loading.value = false
}
init()
// #endregion

</script>

<template>
  <!-- <div :loading="loading">
    <template v-if="detail_Data">
      <div class="flex">
        <div>课程评价名称</div><div>{{detail_Data.xsk_kcpjmc}}</div>
      </div>
      <div class="flex">
        <div>评价类型</div><div>{{detail_Data.xsk_kcpjlx}}</div>
      </div>
      <div class="flex">
        <div>创建人</div><div>{{detail_Data.xsk_cjr}}</div>
      </div>
      <div class="flex">
        <div>创建时间</div><div>{{detail_Data.xsk_cjsj}}</div>
      </div>
      <div class="flex">
        <div>所属课程编号</div><div>{{detail_Data.xsxk_id}}</div>
      </div>
    </template>
  </div> -->

  <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.xskp_xsxm" clearable />
      </el-form-item>
      <!-- <el-form-item label="学生学号">
        <el-input v-model="queryForm_Data.xskp_xsxh" clearable />
      </el-form-item> -->
      <!-- <el-form-item label="评分">
        <el-input v-model="queryForm_Data.xskp_pf" clearable />
      </el-form-item>
      <el-form-item label="评语">
        <el-input v-model="queryForm_Data.xskp_py" type="textarea" />
      </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.grade_name" clearable />
      </el-form-item>
      <el-form-item label="班级编号">
        <el-input v-model="queryForm_Data.class_id" clearable />
      </el-form-item>
      <el-form-item label="班级名称">
        <el-input v-model="queryForm_Data.class_name" clearable />
      </el-form-item>
      <el-form-item label="所属课程编号">
        <el-input v-model="queryForm_Data.xsxk_id" clearable />
      </el-form-item>
      <el-form-item label="所属评价编号">
        <el-input v-model="queryForm_Data.xsk_id" clearable />
      </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" :importKey="('xsxk_id='+aid+'&xsk_id='+bid)"></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="xskp_xsxm" label="学生姓名" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="xskp_xsxh" 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="grade_name" label="年级名称" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="class_id" label="班级编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="class_name" label="班级名称" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="xskp_pf" label="评分" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xskp_py" label="评语" width="auto" show-overflow-tooltip></el-table-column>

        <!-- <el-table-column prop="xsxk_id" label="所属课程编号" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xsk_id" 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_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="xskp_xsxm">
        <!-- <el-input v-model="dialogForm_Data.xskp_xsxm" clearable /> -->
        <remote-select v-model="dialogForm_Data.xskp_xsxh" v-model:model-name="dialogForm_Data.xskp_xsxm"
          :fields="['xsxx_xsxh', 'xsxx_xsxm']" url="/xdjx/stxkgl_xktj_xkqk/index" :d="{
            xsxk_id: props.aid,
            xsk_id: props.bid,
          }" :change="(item: any) => {
  dialogForm_Data.grade_id = item.grade_id
  dialogForm_Data.grade_name = item.grade_name
  dialogForm_Data.class_id = item.class_id
  dialogForm_Data.class_name = item.class_name
}"></remote-select>
      </el-form-item>
      <el-form-item label="评分" prop="xskp_pf">
        <el-input v-model="dialogForm_Data.xskp_pf" clearable />
      </el-form-item>
      <el-form-item label="评语" prop="xskp_py">
        <el-input v-model="dialogForm_Data.xskp_py" type="textarea" />
      </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="grade_name">
        <el-input v-model="dialogForm_Data.grade_name" clearable />
      </el-form-item>
      <el-form-item label="班级编号" prop="class_id">
        <el-input v-model="dialogForm_Data.class_id" clearable />
      </el-form-item>
      <el-form-item label="班级名称" prop="class_name">
        <el-input v-model="dialogForm_Data.class_name" clearable />
      </el-form-item>
      <el-form-item label="所属课程编号" prop="xsxk_id">
        <el-input v-model="dialogForm_Data.xsxk_id" clearable />
      </el-form-item>
      <el-form-item label="所属评价编号" prop="xsk_id">
        <el-input v-model="dialogForm_Data.xsk_id" clearable />
      </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>

</template>
