import {
  NPageHeader,
  NSteps,
  NModal,
  NCheckboxGroup,
  NCheckbox,
  NSpace,
  NDataTable,
  NButton,
  NForm,
  NFormItem,
  NSelect,
  NInput,
  NRow,
  useMessage
} from 'naive-ui'
import type { DataTableRowKey, DataTableColumns } from 'naive-ui'
import { defineComponent, onMounted, reactive, Ref, ref, resolveComponent, h, PropType } from 'vue'
import { filterGroupType, filterCourseEmnu } from '@/utils/filters'
import { courseEmnuArray, musicTypeArray, orchestraTypesArray } from '@/utils/searchArray'
import Pagination from '@/components/pagination'
import styles from './index.module.less'
import { getNotMinePlanDetail, addLessonPlanDetail } from '../api'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'add-plan',
  props: {
    list: {
      type: Object as PropType<any>,
      default: () => {}
    }
  },
  emits: ['getList', 'close'],
  setup(props, { emit }) {
    const route = useRoute()
    const state = reactive({
      loading: false,
      dataList: [],
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      }
    })
    const message = useMessage()
    const searchForm = reactive<any>({
      keyword: '', // 关键字匹配
      orchestraType: null,
      lessonPlanId: route.query.id,
      courseTypeCode: null
    })
    const checkedRowKeysRef = ref<DataTableRowKey[]>([])
    const handleCheck = (rowKeys: DataTableRowKey[]) => {
      checkedRowKeysRef.value = rowKeys
    }

    const columns = (): DataTableColumns => [
      {
        type: 'selection',
        disabled(row: any) {
          return row.checked
        }
      },
      {
        title: '编号',
        key: 'id'
      },
      {
        title: '课件名称',
        key: 'name'
      },
      {
        title: '乐团类型',
        key: 'orchestraType',
        render: (row: any) => <div>{filterGroupType(row.orchestraType)}</div>
      },
      {
        title: '课程类型',
        key: 'courseType',
        render: (row: any) => <div>{filterCourseEmnu(row.courseType)}</div>
      }
    ]
    onMounted(() => {
      getList()
    })
    const getList = async () => {
      state.loading = true
      try {
        state.loading = false
        const { data } = await getNotMinePlanDetail({ ...searchForm, ...state.pagination })
        state.dataList = data.rows || []
        state.pagination.pageTotal = Number(data.total)
      } catch (e) {
        state.loading = false
        console.log(e)
      }
    }
    const handleSave = async () => {
      console.log(checkedRowKeysRef.value)
      state.loading = true
      try {
        const { data } = await addLessonPlanDetail({
          lessonPlanId: searchForm.lessonPlanId,
          lessonCoursewareIds: checkedRowKeysRef.value
        })
        message.success('新增成功')
        emit('getList')
        state.loading = false
      } catch (e) {
        state.loading = false
        console.log(e)
      }
    }

    const search = () => {
      state.pagination.page = 1
      getList()
    }

    const onReset = () => {
      searchForm.keyword = ''
      searchForm.orchestraType = null
      searchForm.lessonPlanId = route.query.id
      searchForm.courseTypeCode = null
      search()
    }

    return () => (
      <div class={styles.addSubject}>
        <div class={styles.searchWrap}>
          <NForm label-width="120" label-placement="left">
            <NFormItem label="课件名称/编号">
              <NInput v-model:value={searchForm.keyword} placeholder="课件名称/编号"></NInput>
            </NFormItem>

            <NFormItem label="乐团类型">
              <NSelect
                placeholder="请选择乐团类型"
                options={orchestraTypesArray}
                clearable
                v-model:value={searchForm.orchestraType}
              ></NSelect>
            </NFormItem>
            <NFormItem label="课程类型">
              <NSelect
                placeholder="请选择课程类型"
                options={courseEmnuArray}
                clearable
                v-model:value={searchForm.courseTypeCode}
              ></NSelect>
            </NFormItem>
            <NFormItem>
              <NSpace style={{ paddingTop: '12px' }} justify="end">
                <NButton type="success" onClick={search}>
                  搜索
                </NButton>
                <NButton onClick={onReset}>重置</NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>

        <NDataTable
          columns={columns()}
          data={state.dataList}
          rowKey={(row: any) => row.id}
          v-model:checkedRowKeys={checkedRowKeysRef.value}
          onUpdate:checked-row-keys={handleCheck}
        ></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pagination.pageTotal}
          onList={getList}
        ></Pagination>
        <NSpace style={{ paddingTop: '12px' }} justify="end">
          <NButton onClick={() => emit('close')}>取消</NButton>
          <NButton
            type="success"
            disabled={!checkedRowKeysRef.value.length || state.loading}
            onClick={handleSave}
          >
            保存
          </NButton>
        </NSpace>
      </div>
    )
  }
})
