import Pagination from '@/components/pagination'
import { knowledgeTypeData } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NInput,
  NSpace,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  lessonCoursewareDetailAddKnowledgePoint,
  lessonCoursewareDetailPageKnowledgePointNotMine
} from '../../api'

export default defineComponent({
  name: 'AddseKnowledge',
  emits: ['close', 'handleSuccess'],
  props: {
    item: {
      type: Object,
      default: () => {}
    },
    courseTypeCode: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const message = useMessage()
    const route = useRoute()
    const state = reactive({
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        lessonCoursewareDetailId: '',
        keyword: ''
      },
      loading: false,
      dataList: [] as any,
      checkList: [] as string[],
      addLoading: false
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection',
          disabled(row: any) {
            return row.totalMaterialNum <= 0 ? true : false
          }
        },
        {
          title: '知识点名称',
          key: 'name'
        },
        {
          title: '课程类型',
          key: 'courseTypeName',
          width: 200,
          ellipsis: true,
          render(row: InternalRowData) {
            return (
              <NTooltip placement="top-start">
                {{
                  default: () => row.courseTypeName,
                  trigger: () => row.courseTypeName
                }}
              </NTooltip>
            )
          }
        },
        {
          title: '素材数量',
          key: 'totalMaterialNum'
        },
        {
          title: '建议学习时长',
          key: 'totalMaterialTimeSecond',
          render(row) {
            return row.totalMaterialTimeSecond + 's'
          }
        }
      ]
    }
    const getList = async () => {
      state.loading = true
      try {
        const { data } = await lessonCoursewareDetailPageKnowledgePointNotMine({
          ...state.searchForm,
          lessonCoursewareDetailId: props.item.id,
          courseTypeCode: props.courseTypeCode,
          page: state.pagination.page,
          rows: state.pagination.rows
        })
        if (Array.isArray(data?.rows)) {
          state.dataList = data.rows
          state.pagination.pageTotal = data.total
        }
      } catch {}
      state.loading = false
    }

    onMounted(() => {
      getList()
    })

    // 记录排序后的位置
    const handleSaveRow = async () => {
      state.addLoading = true
      const res: any = await lessonCoursewareDetailAddKnowledgePoint({
        id: props.item.id,
        knowledgePointIds: state.checkList.join(',')
      })
      if (res?.code === 200) {
        message.success('保存成功')
        emit('handleSuccess')
      }
      state.addLoading = false
    }
    return () => (
      <div>
        <NSpace style={{ paddingBottom: '12px' }}>
          <NInput placeholder="知识点名称" v-model:value={state.searchForm.keyword} />
          <NButton
            type="primary"
            onClick={() => {
              state.pagination.page = 1
              getList()
            }}
          >
            搜索
          </NButton>
          <NButton
            onClick={() => {
              state.searchForm.keyword = ''
            }}
          >
            重置
          </NButton>
        </NSpace>
        <NDataTable
          loading={state.loading}
          rowKey={(row: any) => row.id}
          columns={columns()}
          data={state.dataList}
          onUpdateCheckedRowKeys={(value: any, rows: any) => {
            let tempIds: any = []
            rows.forEach((row: any) => {
              if (!(row.children && row.children.length > 0)) {
                tempIds.push(row.id)
              }
            })
            state.checkList = tempIds
          }}
        ></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pagination.pageTotal}
          onList={getList}
          sync
        ></Pagination>
        <NSpace justify="end" style={{ paddingTop: '12px' }}>
          <NButton onClick={() => emit('close')}>取消</NButton>
          <NButton
            type="primary"
            disabled={state.checkList.length ? false : true}
            loading={state.addLoading}
            onClick={() => handleSaveRow()}
          >
            确认
          </NButton>
        </NSpace>
      </div>
    )
  }
})
