import TheLink from '@/components/TheLink'
import { knowledgeTypeData } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NBadge,
  NButton,
  NCard,
  NDataTable,
  NDrawer,
  NDrawerContent,
  NModal,
  NPageHeader,
  NSpace,
  NTab,
  NTabPane,
  NTabs,
  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 { lessonTrainingDetailPage, lessonTrainingDetailRemove } from '../api'
import AddMaterialTraining from './model/addMaterialTrainingClass'
import AddTrainStandard from './model/addTrainStandard'
const classType: { [_: string]: any } = {
  VIDEO: '视频',
  IMG: '图片',
  SONG: '曲目'
}

export default defineComponent({
  name: 'after-class-training-detail',
  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
    })
    const state = reactive({
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      hasUpdate: false,
      loading: false,
      dataList: [] as any,
      checkList: [] as string[],
      isMover: false,
      visiableKnowledge: false,
      trainModel: false,
      trainItem: null as any,
      modalType: 'add',
      detailData: {}
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection'
        },
        {
          title: '素材名称',
          key: 'materialName',
          render(row: any) {
            return (
              <TheLink
                to={{ path: '/educationalManage/educationalManage', query: { id: row.materialId } }}
              >
                {row.materialName}
              </TheLink>
            )
          }
        },
        {
          title: '课程类型',
          key: 'courseTypeCode',
          render(row: InternalRowData) {
            return (
              (row?.courseTypeCode as string)
                ?.split(',')
                .map((n: string) => knowledgeTypeData[n as any])
                .join(',') || ''
            )
          }
        },

        {
          title: '素材类型',
          key: 'type',
          render(row: InternalRowData) {
            return classType[row.type as any]
          }
        },
        {
          title: '练习标准',
          key: 'standards',
          render(row: InternalRowData) {
            return Array.isArray(row.standards) && row.standards.length ? (
              <NSpace size="small" align="center">
                <NBadge dot type="success" />
                <span>已设置</span>
              </NSpace>
            ) : (
              <NSpace size="small" align="center">
                <NBadge dot type="error" />
                <span>未设置</span>
              </NSpace>
            )
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: InternalRowData, rowIndex: number) {
            return (
              <NSpace>
                <NButton
                  text
                  type="primary"
                  onClick={() => {
                    state.trainModel = true
                    state.trainItem = row as any
                  }}
                >
                  {Array.isArray(row.standards) && row.standards.length
                    ? '修改训练标准'
                    : '设置训练标准'}
                </NButton>
                <NButton text type="primary" onClick={() => hanldeDelete(row)}>
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    // 获取训练详情
    const getDetail = async () => {
      if (!parentData.id) return
      state.loading = true
      try {
        // const { data } = await lessonTrainingDetail(parentData.id)
        const { data } = await lessonTrainingDetailPage({
          lessonTrainingId: parentData.id,
          page: 1,
          rows: 1000
        })
        if (Array.isArray(data?.rows)) {
          state.dataList = data.rows
          state.pagination.pageTotal = data.total
        }
      } catch (error) {}
      state.loading = false
    }

    onMounted(() => {
      getDetail()
    })

    // 批量删除
    const hanldeDelete = (row?: any) => {
      if (state.hasUpdate) {
        message.error('还有没保存的内容,请先保存')
        return
      }
      const d = dialog.warning({
        title: '警告',
        content: '是否确认删除这些素材关联?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          d.loading = true
          const ids = row ? [row.id] : state.checkList
          try {
            const res: any = await lessonTrainingDetailRemove({
              ids: ids.join(','),
              trainingId: parentData.id
            })
            if (res?.code === 200) {
              state.checkList = []
              message.success('删除成功')
              getDetail()
            }
          } catch (error) {}
          d.loading = false
        }
      })
    }
    //退出之前检查下
    const handleBack = () => {
      const isOk = state.dataList.find((n: any) => !n.standards.length)
      console.log('🚀 ~ isOk', isOk)
      if (isOk) {
        dialog.warning({
          title: '警告',
          content: '还有素材没有设置训练标准,是否返回?',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            router.push('/afterClassTrainingManage')
          }
        })
      } else {
        router.push('/afterClassTrainingManage')
      }
    }
    return () => (
      <div class="section-container">
        <NPageHeader on-back={() => handleBack()} 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>
        </NSpace>
        <NDataTable
          loading={state.loading}
          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>
            <AddMaterialTraining
              parentData={parentData}
              onHandleSuccess={() => {
                state.visiableKnowledge = false
                getDetail()
              }}
              onClose={(list: any) => {
                state.visiableKnowledge = false
              }}
            />
          </NDrawerContent>
        </NDrawer>

        {/* 设置的训练标准 */}
        <NModal
          v-model:show={state.trainModel}
          preset="dialog"
          showIcon={false}
          title="训练标准设置"
          style={{ width: '723px' }}
        >
          <AddTrainStandard
            item={state.trainItem}
            onClose={() => (state.trainModel = false)}
            onHandleAdd={() => {
              state.trainModel = false
              getDetail()
            }}
          />
        </NModal>
      </div>
    )
  }
})
