<script setup lang="ts">
import type { MjEditFormProps, MjGridProps } from '#/components/mj/mj-table'

import { useUserStore } from '@vben/stores'

import { paperRecordService } from '#/api/service/question-bank/paper-record'
import {
  mj_form_date,
  mj_form_input,
  mj_form_target,
  mj_form_text,
  mj_form_textarea,
} from '#/components/mj/mj-table'
import { router } from '#/router'
import obj from '#/utils/obj'

import { useSearchSchoolAndBookAndPaper } from '../hooks/search'

defineOptions({ name: 'TaskMgr' })

const emit = defineEmits<{
  (e: 'visibleChange', visible: boolean): void
  (e: 'success'): void
}>()
const gridRef = ref()
const isClassTest = ref(false)
const TYPE_CLASS_TEST = 4
const { userInfo } = storeToRefs(useUserStore())

function syncTimeFieldVisibility() {
  if (isClassTest.value) {
    gridRef.value?.hideEditFormItems(['startTime', 'endTime'])
    gridRef.value?.showEditFormItems(['duration'])
  } else {
    gridRef.value?.showEditFormItems(['startTime', 'endTime'])
    gridRef.value?.hideEditFormItems(['duration'])
  }
}

const { schoolRender, bookRender, paperRender } =
  useSearchSchoolAndBookAndPaper(
    {
      prepare: { gridRef },
    },
    {
      prepare: { gridRef },
    },
    {
      prepare: { gridRef },
    },
  )

if (userInfo.value.isOnlyStaff) {
  schoolRender.props.disabled = true
  schoolRender.props.selectedItems = {
    id: userInfo.value.schoolId,
    name: userInfo.value.schoolName,
  }
  bookRender.props.disabled = false
  bookRender.props.cmpProps = {
    ...bookRender.props.cmpProps,
    fixedSchool: true,
  }
}
// 表单
const editForm = {
  modal: {
    width: 1200,
  },
  form: {
    titleWidth: 100,
    items: obj.joinObjs<any>(
      {
        required: true,
        field: 'schoolName',
        title: '学校',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: schoolRender,
          },
        },
      },
      {
        required: true,
        field: 'textBookName',
        title: '教材',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: bookRender,
          },
        },
      },
      {
        required: true,
        field: 'paperName',
        title: '试卷',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: paperRender,
            click() {
              const data = gridRef.value?.getEditFormData()
              if (data) {
                paperRender.props.cmpProps = {
                  ...paperRender.props.cmpProps,
                  schoolId: data.schoolId,
                  schoolName: data.schoolName,
                  textBookId: data.textBookId,
                  textBookName: data.textBookName,
                }
              }
              paperRender.props._methods?.show?.()
            },
          },
        },
      },
      // {
      //   required: true,
      //   field: 'name',
      //   title: '名称',
      //   span: 12,
      //   itemRender: {
      //     name: mj_form_input,
      //   },
      // },
      {
        required: true,
        field: 'startTime',
        title: '开始时间',
        span: 12,
        itemRender: {
          name: mj_form_date,
          props: {
            type: 'datetime',
          },
        },
      },
      {
        required: true,
        field: 'endTime',
        title: '结束时间',
        span: 12,
        itemRender: {
          name: mj_form_date,
          props: {
            type: 'datetime',
          },
        },
      },
      {
        required: true,
        field: 'duration',
        title: '答题时间（分钟）',
        span: 12,
        itemRender: {
          name: mj_form_input,
          props: {
            placeholder: '请输入答题时间（分钟）',
          },
        },
      },
      {
        field: 'remark',
        title: '备注',
        span: 12,
        itemRender: {
          name: mj_form_textarea,
        },
      },
      {
        required: true,
        field: 'target',
        title: '目标',
        span: 24,
        itemRender: {
          name: mj_form_target,
        },
      },
    ),
    data: userInfo.value.isOnlyStaff
      ? {
          schoolId: userInfo.value.schoolId,
          schoolName: userInfo.value.schoolName,
        }
      : {},
  },
  updateFields: [
    'id',
    'name',
    'paperId',
    'remark',
    'startTime',
    'endTime',
    'duration',
    'target',
    'targetType',
    'typeIds',
  ],
  beforeEditFormShow(data, edit) {
    if (!edit) {
      nextTick().then(() => {
        syncTimeFieldVisibility()
      })
    }
    return data
  },
  beforeSaveOrUpdate(data) {
    if (isClassTest.value && data.duration) {
      const now = new Date()
      const end = new Date(now.getTime() + Number(data.duration) * 60 * 1000)
      const pad = (n: number) => String(n).padStart(2, '0')
      const fmt = (d: Date) =>
        `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
      data.startTime = fmt(now)
      data.endTime = fmt(end)
    }
    data.duration = undefined
    data.paperType = undefined
    data.targetType = data.target?.targetType
    data.typeIds = data.target?.typeIds
    data.target = undefined
    return data
  },
} as MjEditFormProps

// 搜索表单
const searchForm = {
  items: obj.joinObjs<any>(
    {
      title: '学校',
      field: 'schoolId',
      span: 6,
      itemRender: schoolRender,
    },
    {
      title: '教材',
      field: 'textBookId',
      span: 6,
      itemRender: bookRender,
    },
    {
      title: '试卷',
      field: 'paperId',
      span: 6,
      itemRender: paperRender,
    },
  ),
  data: userInfo.value.isOnlyStaff
    ? {
        //     id: userInfo.value.schoolId,
        // name: userInfo.value.schoolName,
      }
    : {},
} as any

// 表格
const grid = {
  columns: [
    {
      title: '学校',
      field: 'schoolName',
    },
    {
      title: '年级',
      field: 'gradeName',
    },
    {
      title: '班级',
      field: 'classNames',
      width: 200,
      showOverflow: true,
    },
    {
      title: '老师',
      field: 'teacherName',
    },
    {
      title: '学科',
      field: 'subjectName',
    },
    {
      title: '试卷',
      field: 'paperName',
      width: 300,
      showOverflow: true,
    },
    {
      title: '名称',
      field: 'name',
    },
    {
      title: '开始时间',
      field: 'startTime',
    },
    {
      title: '结束时间',
      field: 'endTime',
    },
    {
      title: '状态',
      field: 'status',
      slots: {
        default: 'status',
      },
    },
    {
      title: '备注',
      field: 'remark',
      width: 200,
      showOverflow: true,
    },
    {
      title: '操作',
      slots: {
        default: 'operation',
      },
    },
  ],
  beforeLoadData(params) {
    if (userInfo.value.isOnlyStaff) {
      params.schoolId = userInfo.value.schoolId
    }
    return params
  },
} as MjGridProps

// 详情
const view = (row: any) => {
  router.push({
    path: '/question-bank/task-mgr/task-mgr-detail',
    query: {
      resourceId: row.id,
    },
  })
}
const refresh = () => {
  gridRef.value.reload()
}

// 取消作业
const cancelTask = (row: any) => {
  ElMessageBox.confirm('确定取消作业吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    paperRecordService.cancel(row.id).then(() => {
      ElMessage.success('取消作业成功')
      refresh()
    })
  })
}

function editFormVisibleChanged(visible: boolean) {
  if (!visible) {
    isClassTest.value = false
    syncTimeFieldVisibility()
  }
  emit('visibleChange', visible)
}

function onDataModified() {
  emit('success')
}

defineExpose({
  async openAddTask(data: any) {
    isClassTest.value = data.paperType === TYPE_CLASS_TEST
    gridRef.value?.add?.()
    await nextTick()
    gridRef.value?.update?.(data)
  },
})
</script>

<template>
  <div class="task-mgr g-container">
    <MjTable
      ref="gridRef"
      hide-remove
      hide-edit
      :edit-form="editForm"
      :grid="grid"
      :service="paperRecordService"
      :search-form="searchForm"
      @edit-form-visible-changed="editFormVisibleChanged"
      @data-modified="onDataModified"
    >
      <template #status="{ row }">
        <el-tag :type="row.status === 0 ? 'success' : 'danger'">
          {{ row.status === 0 ? '正常' : '取消' }}
        </el-tag>
      </template>
      <template #operation="{ row }">
        <el-button type="primary" @click="view(row)"> 详情 </el-button>
        <el-button
          type="danger"
          v-if="row.status === 0"
          @click="cancelTask(row)"
        >
          取消作业
        </el-button>
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped>
.task-mgr {
  height: 100% !important;
}
</style>
