import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NCascader,
  NCol,
  NDataTable,
  NDatePicker,
  NFormItem,
  NInput,
  NModal,
  NRow,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage,
  NEmpty,
  NIcon
} from 'naive-ui'
import { defineComponent, inject, onMounted, reactive, ref, provide } from 'vue'
import styles from '../index.module.less'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import { fetchCategoryList } from '@/views/educational-manage/api'
import {
  knowledgePointMaterialRelationMaterialPage,
  knowledgePointMaterialRelationSave
} from '../../api'

const classType: { [_: string]: any } = {
  VIDEO: '视频',
  IMG: '图片',
  SONG: '曲目'
}
export default defineComponent({
  name: 'addMaterialKnowledge',
  props: {
    parentData: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    console.log('🚀 ~ props', props.parentData)
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      saveLoading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 10
      },
      dataList: [] as any,
      checkList: [] as string[]
    })
    const searchForm = reactive({
      keyword: '',
      materialCategoryId: null
    })

    // 获取分类列表
    const category = reactive({
      list: [] as any,
      index: -1,
      loading: false
    })
    const getCategoryList = async () => {
      category.loading = true
      try {
        const { data } = await fetchCategoryList({ page: 1 })
        category.list = data?.rows || []
      } catch {}
      category.loading = false
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection'
        },
        {
          title: '素材名称',
          key: 'name',
          fixed: 'left'
        },
        // {
        //   title: '编号',
        //   key: 'id'
        // },

        {
          title: '素材分类',
          key: 'materialCategoryName'
        },
        {
          title: '分段编号',
          key: 'sn'
        },
        {
          title: '素材类型',
          key: 'type',
          render(row: InternalRowData) {
            return classType[row.type as string]
          }
        },
        {
          title: '课程类型',
          key: 'courseTypeName'
        }
        // {
        //   title: '建议学习时长',
        //   key: 'adviseStudyTimeSecond',
        //   render(row: InternalRowData) {
        //     return row.adviseStudyTimeSecond ? row.adviseStudyTimeSecond + '秒' : ''
        //   }
        // }
      ]
    }

    const getData = async () => {
      const body = {
        knowledgePointId: props.parentData.id,
        ...searchForm,
        courseTypeCode: props.parentData.courseTypeCode,
        page: state.pagination.page,
        rows: state.pagination.rows
      }
      return (await knowledgePointMaterialRelationMaterialPage(body)) as any
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await getData()
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

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

    // 素材关联知识点
    const handleSave = async () => {
      state.saveLoading = true
      const body = {
        knowledgePointId: props.parentData.id,
        materialId: state.checkList.join(',')
      }
      await knowledgePointMaterialRelationSave(body)
      state.saveLoading = false
      message.success('保存成功')
      emit('close')
    }

    return () => (
      <>
        <SaveForm
          style={{ padding: 0, boxShadow: 'none' }}
          ref={saveForm}
          label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="addMaterialKnowledge-key"
        >
          <NRow gutter={14}>
            <NCol span={6}>
              <NFormItem label="素材名称/编号" path="keyword">
                <NInput
                  v-model:value={searchForm.keyword}
                  onKeydown={(e) => {
                    if (e.code === 'Enter') {
                      onSubmit()
                    }
                  }}
                  clearable
                />
              </NFormItem>
            </NCol>
            <NCol span={6}>
              <NFormItem label="素材分类" path="materialCategoryId">
                <NCascader
                  v-model:value={searchForm.materialCategoryId}
                  options={category.list}
                  checkStrategy="child"
                  childrenField="subMaterialCategoryList"
                  expandTrigger="hover"
                  valueField="id"
                  labelField="name"
                  clearable
                  v-slots={{
                    empty: () =>
                      category.loading ? (
                        <>
                          <NEmpty
                            description="加载中"
                            v-slots={{
                              icon: () => (
                                <NIcon size="30" class={styles.loading}>
                                  <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    xmlns:xlink="http://www.w3.org/1999/xlink"
                                    viewBox="0 0 1024 1024"
                                  >
                                    <path
                                      d="M988 548c-19.9 0-36-16.1-36-36c0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 0 0-94.3-139.9a437.71 437.71 0 0 0-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7c26.7 63.1 40.2 130.2 40.2 199.3c.1 19.9-16 36-35.9 36z"
                                      fill="currentColor"
                                    ></path>
                                  </svg>
                                </NIcon>
                              )
                            }}
                          ></NEmpty>
                        </>
                      ) : null
                  }}
                />
              </NFormItem>
            </NCol>
            {/* <NCol span={6}>
              <NFormItem label="课程类型" path="courseTypeCode">
                <NSelect clearable v-model:value={searchForm.courseTypeCode} options={lessonType} />
              </NFormItem>
            </NCol> */}
            <NCol span={6}>
              <NFormItem>
                <NSpace>
                  <NButton type="primary" onClick={onSearch}>
                    搜索
                  </NButton>
                  <NButton type="default" onClick={onBtnReset}>
                    重置
                  </NButton>
                </NSpace>
              </NFormItem>
            </NCol>
          </NRow>
        </SaveForm>
        <NDataTable
          loading={state.loading}
          maxHeight="calc(100vh - 270px)"
          rowKey={(row: any) => row.materialId}
          columns={columns()}
          data={state.dataList}
          v-model:checkedRowKeys={state.checkList}
        ></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageTotal={state.pagination.pageTotal}
          v-model:pageSize={state.pagination.rows}
          onList={getList}
        ></Pagination>
        <NButton
          type="primary"
          disabled={state.checkList.length ? false : true}
          loading={state.saveLoading}
          onClick={() => handleSave()}
        >
          保 存
        </NButton>
      </>
    )
  }
})
