import { knowledgeTypeData } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NDrawerContent,
  NInput,
  NModal,
  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 {
  lessonCoursewareDetailPageKnowledgePoint,
  lessonCoursewareDetailRemoveKnowledgePoint,
  lessonCoursewareDetailUpOrDownKnowledgePoint
} from '../../api'
import AddseKnowledge from './AddseKnowledge'
import TheLink from '@/components/TheLink'

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

    const columns = [
      {
        type: 'selection'
      },
      {
        title: '知识点名称',
        key: 'name',
        render(row: any) {
          return row.children ? (
            <>
              {row.name}({row.knowledgePointId})
            </>
          ) : (
            <TheLink
              to={{
                path: '/educationalManage/knowledgeManage',
                query: { keyword: row.knowledgePointId }
              }}
            >
              {row.name}({row.knowledgePointId})
            </TheLink>
          )
        }
      },
      {
        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: any) {
          return row.totalMaterialTimeSecond + 's'
        }
      },
      {
        title: '操作',
        key: 'operation',
        fixed: 'right',
        render(row: InternalRowData, rowIndex: number) {
          return (
            <NSpace>
              <NButton
                text
                type="primary"
                disabled={row.relOrder === 1}
                onClick={() => handleRowMove('up', row)}
              >
                上移
              </NButton>
              <NButton
                text
                type="primary"
                disabled={checkLastItem(row)}
                onClick={() => handleRowMove('down', row)}
              >
                下移
              </NButton>
            </NSpace>
          )
        }
      }
    ]

    const getList = async () => {
      state.loading = true
      try {
        const { data } = await lessonCoursewareDetailPageKnowledgePoint({
          ...state.searchForm,
          lessonCoursewareDetailId: props.item?.id,
          page: state.pagination.page,
          rows: state.pagination.rows
        })
        if (Array.isArray(data?.rows)) {
          state.dataList = data.rows.map((n: any, i: number) => ({
            ...n,
            relOrder: i + 1,
            parentId: 0
          }))

          state.dataList.forEach((item: any) => {
            if (item.children && item.children.length > 0) {
              item.children.forEach((child: any, i: number) => {
                child.relOrder = i + 1
                child.parentId = item.id
              })
            }
          })

          console.log(state.dataList, 'dataList')
        }
      } catch {}
      state.loading = false
    }

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

    // 批量删除
    const hanldeDelete = () => {
      const d = dialog.warning({
        title: '警告',
        content: '是否确认删除知识点关联?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          d.loading = true
          console.log(props.item)
          try {
            const res = await lessonCoursewareDetailRemoveKnowledgePoint({
              id: props.item?.id,
              knowledgePointIds: state.checkList.join(',')
            })
            message.success('删除成功')
            state.checkList = []
            getList()
            emit('handleSuccess')
          } catch (error) {}
          d.loading = false
        }
      })
    }

    // 判断是否是最后一个
    const checkLastItem = (row: any) => {
      const dataList = state.dataList || []
      if (row.parentId > 0) {
        const childList = dataList.find((n: any) => n.id === row.parentId)
        return row.relOrder === childList.children.length
      } else {
        return row.relOrder === dataList.length
      }
    }

    // 表格行移动
    const handleRowMove = (type: 'up' | 'down', row: any) => {
      if (state.loading) return
      const moveData = []
      const index = row.relOrder - 1
      const tempList =
        row.parentId > 0 ? state.dataList : state.dataList.find((n: any) => n.id === row.parentId)
      if (type === 'up') {
        if (row.parentId <= 0) {
          state.dataList[index] = state.dataList.splice(index - 1, 1, state.dataList[index])[0]
        } else {
          state.dataList.forEach((item: any) => {
            if (item.id === row.parentId) {
              item.children[index] = item.children.splice(index - 1, 1, item.children[index])[0]
            }
          })
        }
      } else {
        if (row.parentId <= 0) {
          state.dataList[index] = state.dataList.splice(index + 1, 1, state.dataList[index])[0]
        } else {
          state.dataList.forEach((item: any) => {
            if (item.id === row.parentId) {
              item.children[index] = item.children.splice(index + 1, 1, item.children[index])[0]
            }
          })
        }
      }

      const moveList: any = []
      let sort: number = 0
      state.dataList.forEach((item: any, index: number) => {
        item.relOrder = index + 1

        if (item.children && item.children.length > 0) {
          item.children.forEach((child: any, i: number) => {
            child.relOrder = i + 1
            child.parentId = item.id

            sort = sort + 1
            moveList.push({
              sortNo: sort,
              id: child.id
            })
          })
        } else {
          sort = sort + 1
          moveList.push({
            sortNo: sort,
            id: item.id
          })
        }
      })

      console.log(moveList)
      handleSaveRow(moveList)
    }
    // 记录排序后的位置
    const handleSaveRow = async (moveData: any) => {
      try {
        await lessonCoursewareDetailUpOrDownKnowledgePoint(moveData)
        // getList()
      } catch {}
    }

    return () => (
      <div>
        <NSpace style={{ paddingBottom: '12px' }}>
          <NButton type="primary" onClick={() => (state.visiableKnowledge = true)}>
            关联知识点
          </NButton>
          <NButton
            type="error"
            disabled={state.checkList.length ? false : true}
            onClick={() => hanldeDelete()}
          >
            批量删除
          </NButton>
        </NSpace>
        <NSpace style={{ paddingBottom: '12px' }}>
          <NInput placeholder="知识点名称" v-model:value={state.searchForm.keyword}></NInput>
          <NButton
            type="primary"
            onClick={() => {
              state.pagination.page = 1
              getList()
            }}
          >
            搜索
          </NButton>
          <NButton
            onClick={() => {
              state.searchForm.keyword = ''
              state.pagination.page = 1
              getList()
            }}
          >
            重置
          </NButton>
        </NSpace>
        <NDataTable
          loading={state.loading}
          rowKey={(row: any) => row.id}
          v-model: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>

        <NModal
          preset="dialog"
          v-model:show={state.visiableKnowledge}
          title="添加知识点"
          showIcon={false}
          style={{ width: '1000px' }}
        >
          <AddseKnowledge
            courseTypeCode={props.courseTypeCode as any}
            item={props.item}
            onClose={() => {
              state.visiableKnowledge = false
            }}
            onHandleSuccess={() => {
              state.visiableKnowledge = false
              getList()
              emit('handleSuccess')
            }}
          />
        </NModal>
      </div>
    )
  }
})
