<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 printJS from "print-js";

// #region (constant)
const TABLE_KEY = 'xkks_id'
const URL_CUT = '/xdjx/kcpzgl_kslb'
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;
  'xkks_xsxm': string; // 学生姓名
  'xkk_id': string; // 所属考试
  'grade_id': string; // 年级编号
  'grade_name': string; // 年级名称
  'class_id': string; // 班号
  'class_name': string; // 班级名称
  'cm_id': string; // 班级编号
  'xkks_kcmc': string; // 考场名称
  'xkks_kcmc_json': string; // 考场名称JSON
  'xkks_zkzh': string; // 准考证号
  'xkks_zc_x': string; // 坐次列X
  'xkks_zc_y': string; // 坐次行Y
}
// #endregion

// #region (props)
const props = defineProps<{
  aid: string,
}>()
// #endregion
const ksxx = JSON.parse(sessionStorage.getItem('ksxx') as string)

// #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 = '-KCPZGL-KCPZ-DETAIL-KSLB-DETAIL'
const DetailParam = 'bid'

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)
  xsData.value = {
    value: dialogForm_Data.value.xkks_zkzh,
    label: dialogForm_Data.value.xkks_xsxm
  }
  kcData.value = {
    value: dialogForm_Data.value.xkks_kcmc,
    label: dialogForm_Data.value.xkks_kcmc_json
  }
  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 }) => {
  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
  dialogVisible_audit.value = false
  xsData.value = {};
  kcData.value = {};
}
// #endregion

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

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'xkks_xsxm': { required: true, message: '学生姓名不能为空', trigger: 'submit' },
  'xkk_id': { 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' },
  'cm_id': { required: true, message: '班级编号不能为空', trigger: 'submit' },
  'xkks_kcmc': { required: true, message: '考场名称不能为空', trigger: 'submit' },
  'xkks_kcmc_json': { required: true, message: '考场名称JSON不能为空', trigger: 'submit' },
  'xkks_zkzh': { required: true, message: '准考证号不能为空', trigger: 'submit' },
  'xkks_zc_x': { required: true, message: '坐次列X不能为空', trigger: 'submit' },
  'xkks_zc_y': { required: true, message: '坐次行Y不能为空', trigger: 'submit' },
})
// #endregion

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

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

const dialogForm_Ref_audit = ref<FormInstance>()
const dialogForm_Rules_audit = reactive<FormRules>({
  'xkks_xsxm': { required: true, message: '学生姓名不能为空', trigger: 'submit' },
  'xkk_id': { 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' },
  'cm_id': { required: true, message: '班级编号不能为空', trigger: 'submit' },
  'xkks_kcmc': { required: true, message: '考场名称不能为空', trigger: 'submit' },
  'xkks_kcmc_json': { required: true, message: '考场名称JSON不能为空', trigger: 'submit' },
  'xkks_zkzh': { required: true, message: '准考证号不能为空', trigger: 'submit' },
  'xkks_zc_x': { required: true, message: '坐次列X不能为空', trigger: 'submit' },
  'xkks_zc_y': { required: true, message: '坐次行Y不能为空', 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, ['xkks_xsxm', 'xkk_id', 'grade_id', 'grade_name', 'class_id', 'class_name', 'cm_id', 'xkks_kcmc', 'xkks_kcmc_json', 'xkks_zkzh', 'xkks_zc_x', 'xkks_zc_y',]),
    }
  })
}

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

const xsData = ref({});
const kcData = ref({});


const handleXsChange = ($event: { value: string, label: string }) => {
  dialogForm_Data.value.xkks_zkzh = $event.value;
  dialogForm_Data.value.xkks_xsxm = $event.label;
}

const handleKcChange = ($event: { value: string, label: string }) => {
  dialogForm_Data.value.xkks_kcmc = $event.value;
  dialogForm_Data.value.xkks_kcmc_json = $event.label;
}


const handlePrint = () => {
  printJS({
    printable: "print-part",
    type: "html",
    style: `
#print-part {
      print-color-adjust: exact
}
.flex_center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.flex-row {
  flex-direction: row;
}

.py-3 {
  padding-top: 0.75rem;
  padding-bottom: 0.75rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.py-8 {
  padding-top: 2rem;
  padding-bottom: 2rem;
}

.px-3 {
  padding-left: 0.75rem;
  padding-right: 0.75rem;
}

.px-6 {
  padding-left: 2rem;
  padding-right: 2rem;
}

.text-2xl {
  font-size: 1.5rem;
  line-height: 2rem;
}

.pre::before {
  background-color: rgba(96, 165, 250, 1);
  display: inline-block;
  height: 100%;
  margin-right: 6px;
  color: #60A5FA;
  content: "|";
  width: 4px;
}

.table-item {
  width: 400px;margin: auto;border: 1px solid #aaa;padding: 20px;font-size: 20px;line-height: 30px;margin-bottom: 30px;
}
.justify-between {
  justify-content: space-between;
}
.font30 {
  font-size: 30px;
}
.font12 {
  font-size: 12px;
}
`,
  });
};
</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.xkks_xsxm" clearable />
      </el-form-item>
      <!-- <el-form-item label="所属考试"><el-input v-model="queryForm_Data.xkk_id" 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.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.cm_id" clearable /></el-form-item> -->
      <!-- <el-form-item label="考场名称"><el-input v-model="queryForm_Data.xkks_kcmc" clearable /></el-form-item> -->
      <!-- <el-form-item label="考场名称JSON"><el-input v-model="queryForm_Data.xkks_kcmc_json" type="textarea" /></el-form-item> -->
      <!-- <el-form-item label="准考证号"><el-input v-model="queryForm_Data.xkks_zkzh" clearable /></el-form-item> -->
      <!-- <el-form-item label="坐次列X"><el-input v-model="queryForm_Data.xkks_zc_x" clearable /></el-form-item> -->
      <!-- <el-form-item label="坐次行Y"><el-input v-model="queryForm_Data.xkks_zc_y" 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"></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>
      <el-button @click="zkdDialog=true" type="success">准考证打印</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="xkks_xsxm" label="学生姓名" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="xkk_id" 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="cm_id" label="班级编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <!-- <el-table-column prop="xkks_kcmc" label="考场名称" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="xkks_kcmc_json" label="考场名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xkks_zkzh" label="准考证号" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xkks_zc_x" label="坐次列" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xkks_zc_y" 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_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>
  <!-- {{ ksxx.ks }} -->
  <el-dialog v-model="dialogVisible_addOrEdit" append-to-body destroy-on-close @close="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')">
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
      label-width="120px">
      <el-form-item label="学生姓名" prop="xkks_xsxm">
        <!-- <el-input v-model="dialogForm_Data.xkks_xsxm" clearable /> -->
        <el-select value-key="value" v-model="xsData" @change="handleXsChange">
          <el-option v-for="_ in ksxx.ks" :value="_" :label="_.label"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属考试" prop="xkk_id"><el-input v-model="dialogForm_Data.xkk_id" 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="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="cm_id"><el-input v-model="dialogForm_Data.cm_id" clearable /></el-form-item> -->
      <el-form-item label="考场名称" prop="xkks_kcmc">
        <!-- <el-input v-model="dialogForm_Data.xkks_kcmc" clearable /> -->
        <el-select value-key="value" v-model="kcData" @change="handleKcChange">
          <el-option v-for="_ in ksxx.kc" :value="_" :label="_.label"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="考场名称JSON" prop="xkks_kcmc_json"><el-input v-model="dialogForm_Data.xkks_kcmc_json" type="textarea" /></el-form-item> -->
      <el-form-item label="准考证号" prop="xkks_zkzh"><el-input v-model="dialogForm_Data.xkks_zkzh" clearable /></el-form-item>
      <el-form-item label="坐次列" prop="xkks_zc_x">
        <el-input v-model="dialogForm_Data.xkks_zc_x" clearable />
      </el-form-item>
      <el-form-item label="坐次行" prop="xkks_zc_y">
        <el-input v-model="dialogForm_Data.xkks_zc_y" clearable />
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit', { xkk_id: props.aid })"
          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>


  <el-dialog v-model="zkdDialog" append-to-body destroy-on-close>
    <div id="print-part" style="height: 500px;color: #000;overflow: auto;">
      <div v-for="(item, index) in tableData" :key="index" class="table-item">
        <div class="flex justify-between">
          <div>
            <div>{{ item.xkks_xsxm }}</div>
            <div>准考证号：{{ item.xkks_zkzh }}</div>
            <div>{{ item.xkks_kcmc_json }}</div>
          </div>
          <div class="flex_center">
            <div>
              <div class="text-center font30">{{ item.xkks_zc_x }}排{{ item.xkks_zc_y }}座</div>
              <div class="text-center font12">座位号</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="flex justify-center">
      <el-button @click="handlePrint" type="primary">打印</el-button>
      <el-button @click="zkdDialog=false" type="default">取消</el-button>
    </div>
  </el-dialog>
</template>


<style lang="scss" scoped>
.table-item {
  width: 400px;margin: auto;border: 1px solid #aaa;padding: 20px;font-size: 20px;line-height: 30px;margin-bottom: 30px;
}
.font30 {
  font-size: 30px;
}
.font12 {
  font-size: 12px;
}
</style>