import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NDatePicker,
  NDescriptions,
  NDescriptionsItem,
  NDropdown,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NSpace,
  NSpin,
  NUpload,
  UploadCustomRequestOptions,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import {
  lessonCoursewarePage,
  lessonCoursewareUpdateEnableFlag,
  lessonCoursewareDelete,
  api_openFileImportInfoSave
} from '../api'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { useRouter } from 'vue-router'
import { knowledgeTypeData, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import { orchestraTypes } from '../teachingData'
import { sysEmployeePage } from '@/views/system-manage/api'
import { api_uploadFile } from '@/plugins/uploadFile'

export default defineComponent({
  name: 'courseware-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,
      staffList: [] as any,
      orchestraTypeList: [] as any
    })

    const searchForm = reactive<any>({
      orchestraType: null, //乐团类型
      name: '', // 课件名称
      keyword: '', // 关键字匹配
      enableFlag: null, // 是否启用
      operatorId: null, // 更新人
      courseTypeCode: null // 课程类型
    })
    const dialog = useDialog()
    const message = useMessage()

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

    const getList = async () => {
      try {
        state.loading = true
        const body = {
          page: state.pagination.page,
          rows: state.pagination.rows,
          ...searchForm
        }
        const { data } = await lessonCoursewarePage(body)
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    // 获取操作人
    const getOperationList = async () => {
      try {
        const { data } = await sysEmployeePage({
          page: 1,
          rows: 999
          // jobType: 'STAFF'
        })

        if (Array.isArray(data.rows)) {
          state.staffList = data.rows.map((n: any) => ({ label: n.nickname, value: n.id }))
        }
      } catch {}
    }

    onMounted(() => {
      getOperationList()
      getList()

      for (let i in orchestraTypes) {
        state.orchestraTypeList.push({
          label: orchestraTypes[i],
          value: i
        })
      }
    })

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

    //启用停用
    const handleChangeState = (row: any, type: boolean) => {
      dialog.warning({
        title: '警告',
        content: type ? '是否确认启用课件?' : '是否确认停用课件?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await lessonCoursewareUpdateEnableFlag({
            id: row.id,
            enableFlag: type
          })
          if (res.data) {
            onSubmit()
            message.success('操作成功')
          }
        }
      })
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '课件信息',
          key: 'id',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="课程名称">{row.name}</NDescriptionsItem>
                <NDescriptionsItem label="课件编号">{row.id}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '课件封面',
          key: 'coverImg',
          render(row) {
            return <NImage width={80} height={80} objectFit="contain" src={row.coverImg as any} />
          }
        },
        // {
        //   title: '课件名称',
        //   key: 'name'
        // },
        {
          title: '类型',
          key: 'orchestraType',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="乐团类型">
                  {orchestraTypes[row.orchestraType as any]}
                </NDescriptionsItem>
                <NDescriptionsItem label="课程类型">
                  {row.courseTypeCode ? knowledgeTypeData[row.courseTypeCode as string] : '--'}
                </NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '课程类型',
        //   key: 'courseTypeCode',
        //   render(row: InternalRowData) {
        //     return row.courseTypeCode ? knowledgeTypeData[row.courseTypeCode as string] : ''
        //   }
        // },
        {
          title: '课件内容',
          key: 'courseNum',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="课时数">{row.courseNum}</NDescriptionsItem>
                <NDescriptionsItem label="阶段自测">{row.unitTestNum}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '阶段自测',
        //   key: 'unitTestNum'
        // },
        {
          title: '更新信息',
          key: 'updateTime',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="更新人">{row.operatorName}</NDescriptionsItem>
                <NDescriptionsItem label="更新时间">{row.updateTime}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '更新人',
        //   key: 'operatorName'
        // },
        {
          title: '状态',
          key: 'enableFlag',
          render(row) {
            return row.enableFlag ? '已启用' : '未启用'
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                {row.enableFlag ? (
                  <NButton
                    type="error"
                    size="small"
                    text
                    v-auth="lessonCourseware/updateEnableFlag1608067923699892226"
                    onClick={() => handleChangeState(row, false)}
                  >
                    停用
                  </NButton>
                ) : (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    v-auth="lessonCourseware/updateEnableFlag1608067923699892226"
                    onClick={() => handleChangeState(row, true)}
                  >
                    启用
                  </NButton>
                )}
                {/* <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    router.push({
                      path: '/coursewareDetail',
                      query: {
                        id: row.id,
                        isLook: 1
                      }
                    })
                  }}
                >
                  查看
                </NButton> */}
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="coursewareDetail1607207526805606402"
                  onClick={() => {
                    router.push({
                      path: '/coursewareDetail',
                      query: {
                        id: row.id
                      }
                    })
                  }}
                >
                  详情
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => handleDelete(row)}
                  v-auth="lessonCourseware/delete1610257235044466690"
                >
                  删除
                </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 lessonCoursewareDelete(row.id)
          if (res.data) {
            onSubmit()
            message.success('删除成功')
          }
        }
      })
    }

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

    const customRequest_importData = reactive({
      loading: false,
      dataType: 'COURSEWARE',
      importRef: null as any
    })
    const customRequest_importFile = async (data: UploadCustomRequestOptions) => {
      console.log(data.file)
      customRequest_importData.loading = true
      try {
        const fileUrl = await api_uploadFile(data.file.file, () => {})
        const res = await api_openFileImportInfoSave({
          dataType: customRequest_importData.dataType,
          fileName: data.file.name,
          importUrl: fileUrl
        })
        customRequest_importData.loading = false
        if (res.data) {
          // 空表格
          if (res.data.insertRow === 0 && res.data.invalidRow === 0) {
            message.error('导入失败，表格为空')
            return
          }
          if (res.data.respUrl) {
            dialog.error({
              title: '信息',
              content: () => (
                <NSpace>
                  <div>导入失败，点击下载错误信息</div>
                  <a href={res.data.respUrl} download>
                    下载
                  </a>
                </NSpace>
              )
            })
            return
          }
          message.success('导入成功')
        }
      } catch {}
      customRequest_importData.loading = false
    }

    return () => (
      <div class="system-menu-container">
        <NSpin show={customRequest_importData.loading}>
          <div class={['section-container']}>
            <SaveForm
              ref={saveForm}
              model={searchForm}
              onSubmit={onSubmit}
              onSetModel={(val: any) => Object.assign(searchForm, val)}
              saveKey="courseware-manage-ad-key"
            >
              <NFormItem path="keyword" label="关键字">
                <NInput
                  v-model:value={searchForm.keyword}
                  placeholder="请输入课件名称/编号"
                  clearable
                />
              </NFormItem>
              <NFormItem path="courseTypeCode" label="课程类型">
                <NSelect
                  placeholder="请选择课程类型"
                  clearable
                  v-model:value={searchForm.courseTypeCode}
                  options={lessonType}
                />
              </NFormItem>
              <NFormItem path="enableFlag" label="是否启用">
                <NSelect
                  placeholder="是否启用"
                  clearable
                  v-model:value={searchForm.enableFlag}
                  options={[
                    { label: '是', value: 1 },
                    { label: '否', value: 0 }
                  ]}
                />
              </NFormItem>
              <NFormItem path="orchestraType" label="乐团类型">
                <NSelect
                  placeholder="请输入乐团类型"
                  clearable
                  v-model:value={searchForm.orchestraType}
                  options={state.orchestraTypeList}
                />
              </NFormItem>
              <NFormItem path="operatorId" label="更新人">
                <NSelect
                  placeholder="请输入更新人"
                  clearable
                  v-model:value={searchForm.operatorId}
                  options={state.staffList}
                  filterable
                />
              </NFormItem>
              <NFormItem>
                <NSpace>
                  <NButton type="primary" onClick={onSearch}>
                    搜索
                  </NButton>
                  <NButton type="default" onClick={onBtnReset}>
                    重置
                  </NButton>
                </NSpace>
              </NFormItem>
            </SaveForm>
            <NSpace style={{ paddingBottom: '12px' }} justify="space-between">
              <NButton
                type="primary"
                v-auth="coursewareDetail1607207526805606402"
                onClick={() => {
                  state.visiableKnowledge = true
                  router.push({
                    path: '/coursewareDetail'
                  })
                }}
              >
                新增课件
              </NButton>
              <NSpace>
                <NButton
                  v-auth="downloadCoursewareTemplate1793540443017875457"
                  type="primary"
                  tag="a"
                  //@ts-ignore
                  href="https://oss.dayaedu.com/daya-docs/%E8%AF%BE%E4%BB%B6%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
                  download
                >
                  下载课件模板
                </NButton>
                <div v-auth="Importcourseware1793540542561292290">
                  <NUpload
                    multiple={false}
                    ref={(el: any) => (customRequest_importData.importRef = el)}
                    showFileList={false}
                    accept=".xlsx"
                    customRequest={customRequest_importFile}
                  >
                    <NDropdown
                      size="huge"
                      trigger="hover"
                      options={[
                        { label: '课件', key: 'COURSEWARE' },
                        { label: '素材关联曲目', key: 'COURSEWARE_REF_MATERIAL' }
                      ]}
                      onSelect={(key: string) => {
                        customRequest_importData.dataType = key
                        console.log(customRequest_importData.importRef)
                        customRequest_importData.importRef?.clear()
                        customRequest_importData.importRef?.openOpenFileDialog()
                      }}
                    >
                      <NButton type="primary" onClick={(e: Event) => e.stopPropagation()}>
                        导入数据
                      </NButton>
                    </NDropdown>
                  </NUpload>
                </div>
              </NSpace>
            </NSpace>

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