<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'

// #region (constant)
const TABLE_KEY = 'xqz_id'
const URL_CUT = '/xdjy/qjygl_zyxxlb'
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;
  'xqz_zymc': string; // 资源名称
  'xqz_zylx': string; // 资源类型
  'xqz_zydx': string; // 资源大小
  'xqz_scr': string; // 上传人
  'xqz_scsj': string; // 上传时间
  'xqz_zypf': string; // 资源评分
  'xqz_pfbz': string; // 评分备注
  'xqz_nr': string; // 内容
  'xqz_qtfj': string; // 其他附件
  'grade_id': string; // 年级编号
  'grade_name': string; // 年级名称
  'subject_id': string; // 学科编号
  'subject_name': string; // 学科名称
  'sub_cate_id': string; // 章节编号
  'sub_cate_name': 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 = '-QJYGL-ZYXXLB-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_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()
}
const handleTableColBtn_download = (scope: { row: TYPE_TABLE_FIELD }) => {
  download(scope.row['xqz_qtfj'])
}
const handleTableColBtn_comment = async (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  dialogForm_Data.value = pick(scope.row, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_comment)])
  dialogVisible_comment.value = true
}
// #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
  dialogVisible_comment.value = false
}
// #endregion

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

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'xqz_zymc': { required: true, message: '资源名称不能为空', trigger: 'submit' },
  'xqz_zylx': { required: true, message: '资源类型不能为空', trigger: 'submit' },
  'xqz_zydx': { required: true, message: '资源大小不能为空', trigger: 'submit' },
  'xqz_scr': { required: true, message: '上传人不能为空', trigger: 'submit' },
  'xqz_scsj': { required: true, message: '上传时间不能为空', trigger: 'submit' },
  'xqz_zypf': { required: true, message: '资源评分不能为空', trigger: 'submit' },
  'xqz_pfbz': { required: true, message: '评分备注不能为空', trigger: 'submit' },
  'xqz_nr': { required: true, message: '内容不能为空', trigger: 'submit' },
  'xqz_qtfj': { required: true, message: '其他附件不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'subject_id': { required: true, message: '学科编号不能为空', trigger: 'submit' },
  'subject_name': { required: true, message: '学科名称不能为空', trigger: 'submit' },
  // 'sub_cate_id': { required: true, message: '章节名称不能为空', trigger: 'submit' },
  'sub_cate_name': { 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: 'xqz_id',
  // REASON:'xqz_id'
})

const dialogForm_Ref_audit = ref<FormInstance>()
const dialogForm_Rules_audit = reactive<FormRules>({
  'xqz_zymc': { required: true, message: '资源名称不能为空', trigger: 'submit' },
  'xqz_zylx': { required: true, message: '资源类型不能为空', trigger: 'submit' },
  'xqz_zydx': { required: true, message: '资源大小不能为空', trigger: 'submit' },
  'xqz_scr': { required: true, message: '上传人不能为空', trigger: 'submit' },
  'xqz_scsj': { required: true, message: '上传时间不能为空', trigger: 'submit' },
  'xqz_zypf': { required: true, message: '资源评分不能为空', trigger: 'submit' },
  'xqz_pfbz': { required: true, message: '评分备注不能为空', trigger: 'submit' },
  'xqz_nr': { required: true, message: '内容不能为空', trigger: 'submit' },
  'xqz_qtfj': { required: true, message: '其他附件不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'subject_id': { required: true, message: '学科编号不能为空', trigger: 'submit' },
  'subject_name': { required: true, message: '学科名称不能为空', trigger: 'submit' },
})

// #endregion

// #region (dialog comment)
const dialogVisible_comment = ref<boolean>(false)

const dialogForm_Ref_comment = ref<FormInstance>()
const dialogForm_Rules_comment = reactive({
  'xqz_zypf': { required: true, message: '资源评分不能为空', trigger: 'submit' },
  'xqz_pfbz': { 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
    }
  }).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, ['xqz_zymc', 'xqz_zylx', 'xqz_zydx', 'xqz_scr', 'xqz_scsj', 'xqz_zypf', 'xqz_pfbz', 'xqz_nr', 'xqz_qtfj', 'grade_id', 'grade_name', 'subject_id', 'subject_name', 'sub_cate_id', 'sub_cate_name']),
    }
  })
}

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 xqz_nm = ref()
</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.xqz_zymc" clearable /></el-form-item> -->
      <el-form-item label="资源类型">
        <el-select v-model="queryForm_Data.xqz_zylx" filterable clearable>
          <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-option label="达标检测" value="6" />
          <el-option label="说课课件" value="7" />
          <el-option label="图片" value="8" />
          <el-option label="视频" value="9" />
          <el-option label="资料" value="10" />
          <el-option label="动画" value="11" />
          <el-option label="录音" value="12" />
          <el-option label="论文" value="13" />
          <el-option label="案例" value="14" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="资源大小"><el-input v-model="queryForm_Data.xqz_zydx" clearable /></el-form-item>
      <el-form-item label="上传人"><el-input v-model="queryForm_Data.xqz_scr" clearable /></el-form-item>
      <el-form-item label="上传时间"><el-input v-model="queryForm_Data.xqz_scsj" clearable /></el-form-item>
      <el-form-item label="资源评分"><el-input v-model="queryForm_Data.xqz_zypf" clearable /></el-form-item>
      <el-form-item label="评分备注"><el-input v-model="queryForm_Data.xqz_pfbz" clearable /></el-form-item>
      <el-form-item label="内容"><el-input v-model="queryForm_Data.xqz_nr" type="textarea" /></el-form-item>
      <el-form-item label="其他附件"><file-upload v-model:part="queryForm_Data.xqz_qtfj" /></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 /> -->
        <remote-select to="grade" v-model="queryForm_Data.grade_id"></remote-select>
      </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.subject_name" clearable /> -->
        <remote-select to="subject" v-model="queryForm_Data.subject_id"></remote-select>
      </el-form-item>
      <el-form-item label="章节">
        <remote-cascader url="/book/store/tree" v-model="queryForm_Data.sub_cate_id"></remote-cascader>
      </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="xqz_zymc" label="资源名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_zylx" 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="subject_id" label="学科编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="subject_name" label="学科名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sub_cate_name" label="章节" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_zydx" label="资源大小" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_scr" label="上传人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_scsj" label="上传时间" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="xqz_zypf" label="资源评分" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_pfbz" label="评分备注" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_nr" label="内容" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xqz_qtfj" label="其他附件" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" width="260" 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>
            <!-- <el-button link :auto-insert-space="false" @click="handleTableColBtn_download(scope)" type="primary">下载
            </el-button> -->
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_comment(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="xqz_zymc">
        <el-input v-model="dialogForm_Data.xqz_zymc" clearable />
      </el-form-item>
      <el-form-item label="资源类型" prop="xqz_zylx">
        <el-select v-model="dialogForm_Data.xqz_zylx" filterable clearable>
          <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-option label="达标检测" value="6" />
          <el-option label="说课课件" value="7" />
          <el-option label="图片" value="8" />
          <el-option label="视频" value="9" />
          <el-option label="资料" value="10" />
          <el-option label="动画" value="11" />
          <el-option label="录音" value="12" />
          <el-option label="论文" value="13" />
          <el-option label="案例" value="14" />
        </el-select>
      </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 /> -->
        <remote-select to="grade" v-model="dialogForm_Data.grade_id" v-model:modelName="dialogForm_Data.grade_name">
        </remote-select>
      </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="subject_name">
        <!-- <el-input v-model="dialogForm_Data.subject_name" clearable /> -->
        <remote-select to="subject" v-model="dialogForm_Data.subject_id"
          v-model:modelName="dialogForm_Data.subject_name">
        </remote-select>
      </el-form-item>
      <el-form-item label="章节" prop="sub_cate_name">
        <remote-cascader url="/book/store/tree" v-model="dialogForm_Data.sub_cate_id"
          v-model:modelName="dialogForm_Data.sub_cate_name"></remote-cascader>
      </el-form-item>
      <!-- <el-form-item label="资源大小" prop="xqz_zydx">
        <el-input v-model="dialogForm_Data.xqz_zydx" clearable />
      </el-form-item> -->
      <el-form-item label="上传人" prop="xqz_scr">
        <el-input v-model="dialogForm_Data.xqz_scr" clearable />
      </el-form-item>
      <!-- <el-form-item label="上传时间" prop="xqz_scsj">
        <el-input v-model="dialogForm_Data.xqz_scsj" clearable />
      </el-form-item> -->
      <el-form-item label="其他附件" prop="xqz_qtfj">
        <file-upload v-model:full="dialogForm_Data.xqz_qtfj" v-model:size="dialogForm_Data.xqz_zydx"
          v-model:time="dialogForm_Data.xqz_scsj" :limit="1" />
      </el-form-item>
      <!-- <el-form-item label="资源评分" prop="xqz_zypf">
        <el-input v-model="dialogForm_Data.xqz_zypf" clearable />
      </el-form-item>
      <el-form-item label="评分备注" prop="xqz_pfbz">
        <el-input v-model="dialogForm_Data.xqz_pfbz" clearable />
      </el-form-item> -->
      <el-form-item label="内容" prop="xqz_nr">
        <el-input v-model="dialogForm_Data.xqz_nr" type="textarea" />
      </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>

  <el-dialog v-model="dialogVisible_comment" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_comment" :rules="dialogForm_Rules_comment"
      label-width="120px">

      <el-form-item label="资源评分" prop="xqz_zypf">
        <str-to-num v-model="dialogForm_Data.xqz_zypf">
          <template #default="{ value, change }">
            <el-rate :model-value="value" @change="change" />
          </template>
        </str-to-num>
      </el-form-item>
      <el-form-item label="评分备注" prop="xqz_pfbz">
        <el-input v-model="dialogForm_Data.xqz_pfbz" clearable type="textarea" />
      </el-form-item>

      <div class="flex justify-center">
        <span class="mr-10">
          <el-checkbox v-model="xqz_nm" label="匿名" size="large" />
        </span>

        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_comment')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_comment')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
