import TheLink from '@/components/TheLink'
import {
  DataTableColumn,
  NButton,
  NCard,
  NDataTable,
  NDrawer,
  NDrawerContent,
  NModal,
  NPageHeader,
  NSpace,
  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 {
  knowledgePointMaterialRelationPage,
  knowledgePointMaterialRelationRemove,
  knowledgePointMaterialRelationUpdate
} from '../api'
import AddMaterialKnowledge from './model/addMaterialKnowledge'

export default defineComponent({
  name: 'knowledgeDetail',
  setup() {
    const message = useMessage()
    const dialog = useDialog()
    const route = useRoute()
    const router = useRouter()
    const parentData = reactive<{ name: string; id: any; courseTypeCode: any }>({
      name: route.query.name as string,
      id: route.query.id,
      courseTypeCode: route.query.courseTypeCode as any
    })
    const state = reactive({
      loading: false,
      dataList: [] as any,
      checkList: [] as string[],
      isMover: false,
      visiableKnowledge: false,
      modalType: 'add',
      materail: null
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection'
        },
        // {
        //   title: '排序',
        //   key: 'relOrder'
        // },
        {
          title: '素材名称',
          key: 'materialName',
          render(row: any) {
            return (
              <TheLink
                authLink="material/page1750897012676493314"
                to={{ path: '/educationalManage/educationalManage', query: { id: row.materialId } }}
              >
                {row.materialName}
              </TheLink>
            )
          }
        },
        {
          title: '素材分类',
          key: 'materialCategoryName'
        },
        // {
        //   title: '分段编号',
        //   key: 'sn',
        //   render(row: any) {
        //     return (
        //       <TheLink
        //         authLink="material/page1599589713102299138"
        //         to={{ path: '/educationalManage/educationalManage' }}
        //       >
        //         {row.sn}
        //       </TheLink>
        //     )
        //   }
        // },
        {
          title: '分段编号',
          key: 'sn',
        },
        {
          title: '课程类型',
          key: 'courseTypeName'
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: InternalRowData, rowIndex: number) {
            return (
              <NSpace>
                <NButton
                  text
                  type="primary"
                  disabled={rowIndex === 0}
                  v-auth="knowledgePointMaterialRelation/update1750906809085853697"
                  onClick={() => handleRowMove('up', rowIndex)}
                >
                  上移
                </NButton>
                <NButton
                  text
                  type="primary"
                  v-auth="knowledgePointMaterialRelation/update1750906809085853697"
                  disabled={rowIndex === state.dataList.length - 1}
                  onClick={() => handleRowMove('down', rowIndex)}
                >
                  下移
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }
    const getList = async () => {
      state.loading = true
      try {
        const { data } = await knowledgePointMaterialRelationPage({
          knowledgePointId: parentData.id,
          page: 1,
          rows: 9999
        })
        if (Array.isArray(data?.rows)) {
          state.dataList = data.rows.map((n: any, i: number) => ({ ...n, relOrder: i + 1 }))
        }
      } catch {}
      state.loading = false
    }

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

    // 批量删除
    const hanldeDelete = () => {
      const d = dialog.warning({
        title: '警告',
        content: '是否确认删除这些素材知识点关联?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          d.loading = true
          const res: any = await knowledgePointMaterialRelationRemove(state.checkList)
          d.loading = false
          if (res?.code == 200) {
            state.checkList = []
            message.success('删除成功')
            getList()
          }
        }
      })
    }

    // 表格行移动
    const handleRowMove = (type: 'up' | 'down', index: number) => {
      if (type === 'up') {
        if (index != 0) {
          state.dataList[index] = state.dataList.splice(index - 1, 1, state.dataList[index])[0]
        } else {
          state.dataList.push(state.dataList.shift())
        }
      } else {
        if (index != state.dataList.length - 1) {
          state.dataList[index] = state.dataList.splice(index + 1, 1, state.dataList[index])[0]
        } else {
          state.dataList.unshift(state.dataList.splice(index, 1)[0])
        }
      }
      state.isMover = true
      handleSaveRow()
    }
    // 记录排序后的位置
    const handleSaveRow = () => {
      const body = state.dataList.map((n: any, i: number) => {
        return {
          knowledgePointId: parentData.id,
          materialId: n.materialId,
          relOrder: i + 1,
          id: n.id
        }
      })
      knowledgePointMaterialRelationUpdate(body)
    }
    return () => (
      <div class="section-container">
        <NPageHeader
          on-back={() => router.push('/educationalManage/knowledgeManage')}
          title={parentData.name}
        ></NPageHeader>
        <NSpace style={{ padding: '15px 0' }}>
          <NButton
            v-auth="knowledgePointMaterialRelation/save1604770193787420673"
            type="primary"
            onClick={() => (state.visiableKnowledge = true)}
          >
            新增素材
          </NButton>
          <NButton
            v-auth="knowledgePointMaterialRelation/remove1604770313480273922"
            type="error"
            disabled={state.checkList.length ? false : true}
            onClick={() => hanldeDelete()}
          >
            批量删除
          </NButton>
          {/* <NButton>保存移动的排序</NButton> */}
        </NSpace>
        <NDataTable
          loading={state.loading}
          maxHeight="calc(100vh - 290px)"
          rowKey={(row: any) => row.id}
          columns={columns()}
          data={state.dataList}
          onUpdateCheckedRowKeys={(value: any) => {
            state.checkList = value
          }}
        ></NDataTable>

        <NDrawer width="80vw" v-model:show={state.visiableKnowledge}>
          <NDrawerContent title="新增素材关联" closable>
            <AddMaterialKnowledge
              parentData={parentData}
              onClose={() => {
                state.visiableKnowledge = false
                getList()
              }}
            />
          </NDrawerContent>
        </NDrawer>
      </div>
    )
  }
})
