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,
  NTooltip,
  useDialog,
  useMessage,
  NEmpty,
  NIcon
} from 'naive-ui'
import { defineComponent, inject, onMounted, reactive, ref, provide, nextTick } from 'vue'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { lessonType, getLessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import { fetchCategoryList } from '@/views/educational-manage/api'
import {
  lessonTrainingDetailBatchInsert,
  lessonTrainingDetailMaterialPage
} from '@/views/teaching-manage/api'
import { fetchKnowledgeList } from '@/views/knowledge-manage/api'

const classType: { [_: string]: any } = {
  VIDEO: '视频',
  IMG: '视频',
  SONG: '曲目'
}
export default defineComponent({
  name: 'addMaterialTraining',
  props: {
    parentData: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['close', 'handleSuccess'],
  setup(props, { emit }) {
    console.log('🚀 ~ props', props.parentData.id)
    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[],
      selectCheckList: [] as any
    })
    const searchForm = reactive({
      keyword: '',
      // materialCategoryId: null
      knowledgePointIds: 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 knowledge = reactive({
      list: [] as any,
      index: -1,
      loading: false
    })
    const getKnowledgeList = async () => {
      try {
        const { data } = await fetchKnowledgeList({
          courseTypeCode: props.parentData.courseTypeCode,
          page: 1,
          rows: 1000
        })
        console.log(data)
        const tempList = data.rows || []
        // if (!searchForm.knowledgePointId) {
        //   searchForm.knowledgePointId = tempList.length > 0 ? tempList[0].id : null
        // }
        knowledge.list = tempList
      } catch {}
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection',
          disabled(row) {
            return row.knowledgePointId ? false : true
          }
        },
        {
          title: '素材名称',
          key: 'materialName',
          fixed: 'left'
        },
        {
          title: '素材类型',
          key: 'materialCategoryName',
          render(row) {
            return classType[row.type as any]
          }
        },
        {
          title: '分段编号',
          key: 'sn'
        },

        {
          title: '课程类型',
          key: 'courseTypeName',
          width: 200,
          ellipsis: true,
          render(row: InternalRowData) {
            return (
              <NTooltip placement="left-start">
                {{
                  default: () => row.courseTypeName,
                  trigger: () => row.courseTypeName
                }}
              </NTooltip>
            )
          }
        },
        {
          title: '知识点分类',
          key: 'knowledgePointName'
        }
      ]
    }

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

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      // saveForm.value?.reset()
      // 默认选中第一个
      searchForm.knowledgePointIds = null
      searchForm.keyword = ''
      onSearch()
    }

    const getList = async () => {
      try {
        state.loading = true
        const tranbody = {
          lessonTrainingId: props.parentData.id,
          ...searchForm,
          courseTypeCode: props.parentData.courseTypeCode,
          page: state.pagination.page,
          rows: state.pagination.rows,
          knowledgePointId: null
        }
        const { data } = await lessonTrainingDetailMaterialPage(tranbody)
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        // state.dataList = data.rows || []
        const tempRows = data.rows || []
        tempRows.forEach((row: any) => {
          row.tempIndex = new Date().getTime() + '' + Math.random()
          // state.dataList.push({
          //   ...row
          // })
        })
        console.log(tempRows, 'rows')
        state.dataList = tempRows
      } catch {
        state.loading = false
      }
    }

    onMounted(async () => {
      await getKnowledgeList()
      // getCategoryList()
      nextTick(async () => {
        await getList()
      })
    })

    // 素材关联知识点
    const handleSave = async () => {
      // state.saveLoading = true
      // const list = state.checkList.map((n: any) => {
      //   const item = state.selectCheckList.find((item: any) => item.tempIndex === n)
      //   return {
      //     materialId: item.materialId,
      //     knowledgePointId: item.knowledgePointId,
      //     lessonTrainingId: props.parentData.id
      //   }
      // })
      // try {
      //   const res: any = await lessonTrainingDetailBatchInsert(list)
      //   message.success('保存成功')
      //   emit('handleSuccess')
      // } catch (error) {}
      // state.saveLoading = false
      dialog.warning({
        title: '提示',
        content: '请确保作业曲目已添加到业务系统',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          state.saveLoading = true
          const list = state.checkList.map((n: any) => {
            const item = state.selectCheckList.find((item: any) => item.tempIndex === n)
            return {
              materialId: item.materialId,
              knowledgePointId: item.knowledgePointId,
              lessonTrainingId: props.parentData.id
            }
          })
          try {
            const res: any = await lessonTrainingDetailBatchInsert(list)
            message.success('保存成功')
            emit('handleSuccess')
          } catch (error) {}
          state.saveLoading = false
        },
        onNegativeClick: () => {}
      })
    }

    return () => (
      <>
        <SaveForm
          style={{ padding: 0, boxShadow: 'none' }}
          ref={saveForm}
          label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="addMaterialTraining-abc-key-class"
        >
          <NFormItem label="知识点分类" path="knowledgePointIds">
            <NCascader
              v-model:value={searchForm.knowledgePointIds}
              options={knowledge.list}
              multiple
              clearable
              filterable
              childrenField="children"
              expandTrigger="hover"
              valueField="id"
              labelField="name"
              checkStrategy="all"
              cascade
              showPath
              maxTagCount={'responsive'}
              v-slots={{
                empty: () =>
                  knowledge.loading ? (
                    <>
                      <NEmpty
                        description="加载中"
                        v-slots={{
                          icon: () => (
                            <NIcon size="30">
                              <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>
          <NFormItem label="素材名称/编号" path="keyword">
            <NInput
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>
        <NDataTable
          loading={state.loading}
          maxHeight="calc(100vh - 270px)"
          rowKey={(row: any) => row.tempIndex}
          columns={columns()}
          data={state.dataList}
          v-model:checkedRowKeys={state.checkList}
          onUpdate:checkedRowKeys={(keys: any, rows: any, meta: any) => {
            // state.selectCheckList
            // 处理删除的数据
            const tempList: any = []
            state.selectCheckList.forEach((item: any) => {
              if (state.checkList.includes(item.tempIndex)) {
                tempList.push(item)
              }
            })

            // 添加新增的数据
            state.checkList.forEach((key: string) => {
              const item = state.dataList.find((item: any) => item.tempIndex === key)
              const index = state.selectCheckList.findIndex((item: any) => item.tempIndex === key)
              if (index <= -1) {
                tempList.push(item)
              }
            })

            state.selectCheckList = [...tempList]
          }}
        ></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageTotal={state.pagination.pageTotal}
          v-model:pageSize={state.pagination.rows}
          onList={getList}
          sync
          saveKey="addMaterialTraining-abc-key-class"
        ></Pagination>
        <NButton
          type="primary"
          disabled={state.checkList.length ? false : true}
          loading={state.saveLoading}
          onClick={() => handleSave()}
        >
          确认
        </NButton>
      </>
    )
  }
})
