import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import { filterTimes, getTimes } from '@/utils/dateUtil'
import {
  DataTableColumn,
  NBadge,
  NButton,
  NDataTable,
  NDatePicker,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref, provide } from 'vue'
import { employeeArray } from '@/utils/searchArray'
import dayjs from 'dayjs'
import { lessonTrainingPage, lessonTrainingRemove, lessonTrainingUpdateEnableFlag } from '../api'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { useRoute, useRouter } from 'vue-router'
import { knowledgeTypeData, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import AddTraining from './model/AddTraining'

export default defineComponent({
  name: 'after-class-training-manage',
  setup() {
    const router = useRouter()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      visiableKnowledge: false,
      modalType: 'add',
      materail: null
    })

    const searchForm = reactive({
      keyword: '',
      time: null,
      courseType: null,
      operatorId: null,
      enableFlag: null
    })
    const dialog = useDialog()
    const message = useMessage()
    const route = useRoute()

    // 获取知识点列表
    const knowledge = reactive({
      list: [] as any,
      index: -1
    })

    const getList = async () => {
      try {
        state.loading = true
        const { time, ...reset } = searchForm
        const { data } = await lessonTrainingPage({
          ...reset,
          ...filterTimes(time, ['startUpdateTime', 'endUpdateTime']),
          page: state.pagination.page,
          rows: state.pagination.rows
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    onMounted(() => {
      if (route.query.id) {
        searchForm.keyword = route.query.id as string
      }
      getList()
    })

    // 打开详情
    const openDetail = (row?: any) => {
      router.push({
        path: '/afterClassTrainingDetail',
        query: {
          id: row?.id,
          name: row?.name,
          courseTypeCode: row?.courseTypeCode
        }
      })
    }

    //启用停用
    const handleChange = (row: any) => {
      dialog.warning({
        title: '警告',
        content: row.enableFlag ? '是否停用课后作业?' : '是否启用课后作业',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const res = await lessonTrainingUpdateEnableFlag(row.id)
            if (res.data) {
              onSubmit()
              message.success(`${row.enableFlag ? '停用' : '启用  '}成功`)
            }
          } catch (error) {}
        }
      })
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '训练信息',
          key: 'name',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="训练名称">{row.name}</NDescriptionsItem>
                <NDescriptionsItem label="训练编号">{row.id}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '编号',
        //   key: 'id'
        // },

        {
          title: '课程信息',
          key: 'courseTypeName',
          width: 200,
          ellipsis: true,
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="课程类型">{row.courseTypeName}</NDescriptionsItem>
                <NDescriptionsItem label="训练条数">{row.trainingNum}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '训练条数',
        //   key: 'trainingNum'
        // },
        {
          title: '更新信息',
          key: 'updateTime',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="更新人">{row.operatorName}</NDescriptionsItem>
                <NDescriptionsItem label="更新时间">{row.updateTime}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '启用状态',
          key: 'enableFlag',
          render(row: InternalRowData) {
            return row.enableFlag ? (
              <NSpace size="small" align="center">
                <NBadge dot type="success" />
                <span>已启用</span>
              </NSpace>
            ) : (
              <NSpace size="small" align="center">
                <NBadge dot type="error" />
                <span>未启用</span>
              </NSpace>
            )
          }
        },
        // {
        //   title: '更新人',
        //   key: 'operatorName'
        // },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type={row.enableFlag ? 'error' : 'success'}
                  size="small"
                  text
                  onClick={() => handleChange(row)}
                >
                  {row.enableFlag ? '停用' : '启用'}
                </NButton>
                <NButton type="primary" size="small" text onClick={() => openDetail(row)}>
                  详情
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    state.modalType = 'update'
                    state.visiableKnowledge = true
                    state.materail = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  disabled={row.enableFlag}
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    handleDelete(row)
                  }}
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    // 删除
    const handleDelete = async (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此训练?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          console.log('row', row)
          const res = await lessonTrainingRemove(row.id)
          if (res.data) {
            onSubmit()
            message.success('删除成功')
          }
        }
      })
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    return () => (
      <div class="system-menu-container">
        <h2>课后作业</h2>
        <div class={['section-container']}>
          <SaveForm
            ref={saveForm}
            model={searchForm}
            onSubmit={onSubmit}
            onSetModel={(val: any) => Object.assign(searchForm, val)}
            saveKey="after-class-training-manage-key"
          >
            <NFormItem path="search" label="关键词">
              <NInput v-model:value={searchForm.keyword} placeholder="训练名称/编号" clearable />
            </NFormItem>
            <NFormItem label="课程类型" path="courseType">
              <NSelect
                clearable
                placeholder="请选择课程类型"
                v-model:value={searchForm.courseType}
                options={lessonType}
              />
            </NFormItem>
            <NFormItem label="启用状态" path="enableFlag">
              <NSelect
                placeholder="请选择启用状态"
                clearable
                v-model:value={searchForm.enableFlag}
                options={
                  [
                    { label: '已启用', value: true },
                    { label: '未启用', value: false }
                  ] as any
                }
              />
            </NFormItem>
            <NFormItem path="time" label="时间">
              <NDatePicker
                value-format="yyyy-MM-dd HH:mm:dd"
                v-model:value={searchForm.time}
                type="daterange"
                clearable
              ></NDatePicker>
            </NFormItem>
            {/* <NFormItem path="status">
            <NSelect
              v-model:value={searchForm.operatorId}
              placeholder="上传人"
              options={employeeArray}
              clearable
            />
          </NFormItem> */}
            <NFormItem>
              <NSpace>
                <NButton type="primary" onClick={onSearch}>
                  搜索
                </NButton>
                <NButton type="default" onClick={onBtnReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </SaveForm>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              onClick={() => {
                state.modalType = 'add'
                state.materail = null
                state.visiableKnowledge = true
              }}
            >
              新增训练
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            saveKey="after-class-training-manage-key"
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>

          <NModal
            v-model:show={state.visiableKnowledge}
            preset="dialog"
            showIcon={false}
            title={state.modalType === 'add' ? '新增训练' : '修改训练'}
            style={{ width: '400px' }}
            onClose={() => {
              state.materail = null
            }}
          >
            <AddTraining
              item={state.materail}
              onHandleSuccess={() => {
                state.visiableKnowledge = false
                getList()
              }}
              onClose={() => (state.visiableKnowledge = false)}
            />
          </NModal>
        </div>
      </div>
    )
  }
})
