import {
  NPageHeader,
  NSteps,
  NTabPane,
  NTabs,
  useMessage,
  NDataTable,
  NSpace,
  DataTableColumn,
  NButton,
  DataTableRowKey,
  NModal,
  useDialog
} from 'naive-ui'
import { defineComponent, onMounted, reactive, Ref, ref, provide } from 'vue'
import { RouterView, useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import { filterGroupType, filterCourseEmnu } from '@/utils/filters'
import { getPlanDetail, removeLessonPlanDetail } from '../api'
import AddPlan from './add-plan'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { knowledgeTypeData } from '@/views/knowledge-manage/knowledgeTypeData'
import { useTabsViewStore } from '@/store/modules/tabsView'
import TheLink from '@/components/TheLink'
export default defineComponent({
  name: 'group-detail',
  setup(props, { emit }) {
    const router = useRouter()
    const route = useRoute()
    const message = useMessage()
    const dialog = useDialog()
    const groupName: Ref<string> = ref((route.query.name as string) || '计划详情')
    const checkedRowKeysRef = ref<DataTableRowKey[]>([])
    const handleCheck = (rowKeys: DataTableRowKey[]) => {
      console.log('🚀 ~ rowKeys', rowKeys)
      checkedRowKeysRef.value = rowKeys
    }
    const tabsViewStore = useTabsViewStore()
    const state = reactive({
      loading: false,
      id: route.query.id,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      visiablePlan: false
    })
    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection'
        },
        {
          title: '课件名称',
          key: 'name',
          render: (row: any) => (
            <>
              <TheLink
                authLink="coursewareManage1606856890826199041"
                to={{ path: '/coursewareDetail', query: { id: row.lessonCoursewareId } }}
              >
                {row.name}
              </TheLink>
            </>
          )
        },
        {
          title: '乐团类型',
          key: 'orchestraType',
          render: (row: any) => <div>{filterGroupType(row.orchestraType)}</div>
        },
        {
          title: '课程类型',
          key: 'courseTypeCode',
          render(row: InternalRowData) {
            return row.courseTypeCode ? knowledgeTypeData[row.courseTypeCode as string] : ''
          }
        },
        {
          title: '添加时间',
          key: 'createTime'
        },
        {
          title: '添加人',
          key: 'operatorName'
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton type="primary" size="small" text onClick={() => handleDelete(row)}>
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }
    const gotoBack = () => {
      router.push({
        path: '/teachingPlan'
      })
      tabsViewStore.closeCurrentTab(route)
    }

    const getList = async () => {
      state.loading = true
      try {
        const { data } = await getPlanDetail({ ...state.pagination, lessonPlanId: state.id })
        state.dataList = data.rows
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch (e) {
        state.loading = false
        console.log(e)
      }
    }
    // 删除
    const handleDelete = (row: any) => {
      dialog.warning({
        title: '警告',
        content: `是否确认删除课件${row.name}?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const res = await removeLessonPlanDetail([row.id])
            message.success('删除成功')
            getList()
          } catch (e: any) {}
        }
      })
    }
    const handleDeletes = () => {
      dialog.warning({
        title: '警告',
        content: `是否确认批量删除${checkedRowKeysRef.value.length}个课件?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const res = await removeLessonPlanDetail(checkedRowKeysRef.value)
            message.success('删除成功')
            checkedRowKeysRef.value = []
            getList()
          } catch (e: any) {}
        }
      })
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <NPageHeader on-back={() => gotoBack()} title={groupName.value}></NPageHeader>
        <div class={['section-container', styles.wrap]}>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              onClick={() => {
                state.visiablePlan = true
              }}
            >
              新增课件
            </NButton>
            <NButton
              type="error"
              disabled={checkedRowKeysRef.value.length < 1}
              onClick={() => {
                handleDeletes()
              }}
            >
              批量删除
            </NButton>
          </NSpace>
          <NDataTable
            rowKey={(row: any) => row.id}
            v-model:checkedRowKeys={checkedRowKeysRef.value}
            onUpdate:checked-row-keys={handleCheck}
            scrollX={1000}
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiablePlan}
          preset="dialog"
          showIcon={false}
          title={'新增课件'}
          style={{ width: '1000px' }}
        >
          <AddPlan
            onClose={() => {
              state.visiablePlan = false
            }}
            onGetList={() => {
              state.visiablePlan = false
              getList()
            }}
          ></AddPlan>
        </NModal>
      </div>
    )
  }
})
