import {
  NAlert,
  NButton,
  NCard,
  NDialog,
  NDrawer,
  NDrawerContent,
  NEmpty,
  NForm,
  NFormItem,
  NGi,
  NGrid,
  NIcon,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import {
  lessonCoursewareDetailPage,
  lessonCoursewareDetailSave,
  lessonCoursewareDetailUpdate,
  lessonTrainingPage,
  lessonCoursewareDetailRemove,
  lessonCoursewareExaminationMapperQueryAll,
  lessonCoursewareDetailLock
} from '../../api'
import styles from '../index.module.less'
import { EditFilled, DeleteFilled, LockFilled, UnlockFilled } from '@vicons/antd'
import CourseKnowledgePoint from '../model/CourseKnowledgePoint'
import SelectAfterClassTraining from '../model/selectAfterClassTraining'
import AddUnitTest from '../model/AddUnitTest'
import TheLink from '@/components/TheLink'

export default defineComponent({
  name: 'courseConfiguration',
  props: {
    course: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, ctx) {
    const message = useMessage()
    const dialog = useDialog()
    const route = useRoute()
    const addFormRef = ref()
    const addForm = reactive({
      open: false,
      id: '',
      name: '', //课时名称
      lessonTargetDesc: '', //课时名称
      lessonTrainingId: '', //课后作业
      lockEnable: 'true'
    })
    // 课件添加课程
    const addCourseware = () => {
      addFormRef.value.validate(async (err: any) => {
        if (!err) {
          const body = {
            lessonCoursewareId: route.query.id,
            name: addForm.name,
            lessonTargetDesc: addForm.lessonTargetDesc,
            lockEnable: addForm.lockEnable
          }
          let res: any
          if (addForm.id) {
            try {
              res = await lessonCoursewareDetailUpdate({
                ...body,
                id: addForm.id
              })
            } catch (error) {}
          } else {
            try {
              res = await lessonCoursewareDetailSave(body)
            } catch (error) {}
          }
          if (res?.code == 200) {
            message.success('保存成功')
            addForm.open = false
            getDetail()
          }
        }
      })
    }

    const state = reactive({
      dataList: [] as any,
      mapperList: [] as any
    })
    const getDetail = async () => {
      try {
        const { data } = await lessonCoursewareDetailPage({
          lessonCoursewareId: route.query.id,
          page: 1,
          rows: 1000
        })
        if (Array.isArray(data?.rows)) {
          state.dataList = data.rows
        }
      } catch (error) {}
    }
    /** 查询课件下的所有阶段自测 */
    const getMapperAll = async () => {
      try {
        const { data } = await lessonCoursewareExaminationMapperQueryAll(route.query.id)
        if (Array.isArray(data)) {
          state.mapperList = data
        }
      } catch (error) {}
    }
    onMounted(() => {
      getDetail()
      getMapperAll()
    })
    //删除课时
    const hanldeDelete = (item: any) => {
      const d = dialog.warning({
        title: '警告',
        content: '是否确认删除此课时?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          d.loading = true
          try {
            const res: any = await lessonCoursewareDetailRemove(item.id)
            if (res?.code == 200) {
              message.success('删除成功')
              getDetail()
            }
          } catch (error) {}
          d.loading = false
        }
      })
    }

    //绑定课后作业
    const afterTrain = reactive({
      open: false,
      id: ''
    })
    const addAfterTrain = async (row: any) => {
      console.log('🚀 ~ row', row)
      const body = {
        id: addForm.id,
        lessonTrainingId: row.id,
        name: addForm.name,
        lessonTargetDesc: addForm.lessonTargetDesc
      }
      try {
        const res: any = await lessonCoursewareDetailUpdate(body)
        if (res?.code == 200) {
          message.success('保存成功')
          afterTrain.open = false
          getDetail()
        }
      } catch (error) {}
    }

    // 课程配置
    const courseData = reactive({
      open: false,
      title: '',
      item: null
    })

    //阶段自测
    const unitData = reactive({
      open: false,
      model: {}
    })

    /** 切换课件是否锁定 */
    const toggleLock = (item: any) => {
      const d = dialog.warning({
        title: '警告',
        content: `是否确认${item.lockFlag ? '解锁' : '锁定'}此课时?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          d.loading = true
          try {
            const res = await lessonCoursewareDetailLock({ id: item.id, lockFlag: !item.lockFlag })
            message.success('操作成功')
            getDetail()
          } catch (error) {}
          d.loading = false
        }
      })
    }
    return () => (
      <div class={styles.courseConfiguration}>
        <NSpace>
          <NButton
            disabled={route.query.isLook ? true : false}
            type="primary"
            onClick={() => {
              addForm.name = ''
              addForm.lessonTargetDesc = ''
              addForm.lessonTrainingId = ''
              addForm.id = ''
              addForm.lockEnable = ''
              addForm.open = true
            }}
          >
            添加课程
          </NButton>
          <NButton
            type="primary"
            disabled={route.query.isLook ? true : false}
            onClick={() => {
              unitData.open = true
              unitData.model = {}
            }}
          >
            添加阶段自测
          </NButton>
        </NSpace>
        <NAlert class={styles.title} title="教学内容" />
        <NGrid xGap={12} yGap={8} cols={3}>
          {state.dataList.map((item: any) => {
            const mapper = state.mapperList.find((n: any) => n.parentCoursewareDetailId == item.id)
            return (
              <>
                <NGi>
                  <NCard
                    title={item.name}
                    style={{
                      '--n-padding-top': '5px',
                      '--n-padding-bottom': '5px',
                      height: '100%'
                    }}
                  >
                    {{
                      default: () => (
                        <div>
                          <div style={{ paddingBottom: '12px' }}>{item.lessonTargetDesc}</div>
                          <table style={{ width: '100%' }}>
                            <tr>
                              <td>建议学习时长</td>
                              <td style={{ 'text-align': 'right' }}>
                                {item.lessonDurationSecond || '0'}s
                              </td>
                            </tr>
                            <tr>
                              <td>知识点</td>
                              <td style={{ 'text-align': 'right' }}>
                                {item.knowledgePointIds?.split(',').filter(Boolean).length || 0}个
                              </td>
                            </tr>
                            <tr>
                              <td>课后作业</td>
                              <td style={{ 'text-align': 'right' }}>
                                {item.lessonTrainingId ? (
                                  <TheLink
                                    // to={`/#/afterClassTrainingDetail?id=${item.lessonTrainingId}&name=${item.lessonTrainingName}&courseTypeCode=TRUMPET_SINGLE`}
                                    to={{
                                      path: '/afterClassTrainingManage',
                                      query: { id: item.lessonTrainingId }
                                    }}
                                  >
                                    {item.lessonTrainingName}
                                  </TheLink>
                                ) : (
                                  '无'
                                )}
                              </td>
                            </tr>
                          </table>
                        </div>
                      ),
                      'header-extra': () => (
                        <>
                          <NTooltip>
                            {{
                              default: () => (item.lockFlag ? '解锁' : '锁定'),
                              trigger: () => (
                                <NButton
                                  disabled={route.query.isLook ? true : false}
                                  quaternary
                                  circle
                                  onClick={() => toggleLock(item)}
                                >
                                  <NIcon
                                    component={item.lockFlag ? <LockFilled /> : <UnlockFilled />}
                                  />
                                </NButton>
                              )
                            }}
                          </NTooltip>

                          <NTooltip>
                            {{
                              default: () => '编辑',
                              trigger: () => (
                                <NButton
                                  disabled={route.query.isLook ? true : false}
                                  quaternary
                                  circle
                                  onClick={() => {
                                    addForm.name = item.name
                                    addForm.lessonTargetDesc = item.lessonTargetDesc
                                    addForm.id = item.id
                                    addForm.lockEnable = item.lockEnable + ''
                                    addForm.open = true
                                  }}
                                >
                                  <NIcon component={<EditFilled />} />
                                </NButton>
                              )
                            }}
                          </NTooltip>
                          <NTooltip>
                            {{
                              default: () => '删除',
                              trigger: () => (
                                <NButton
                                  disabled={route.query.isLook ? true : false}
                                  quaternary
                                  circle
                                  onClick={() => hanldeDelete(item)}
                                >
                                  <NIcon component={<DeleteFilled />} />
                                </NButton>
                              )
                            }}
                          </NTooltip>
                        </>
                      ),
                      action: () => (
                        <NSpace justify="space-around">
                          <NButton
                            text
                            disabled={route.query.isLook ? true : false}
                            onClick={() => {
                              courseData.title = item.name
                              courseData.open = true
                              courseData.item = item
                            }}
                          >
                            选择知识点
                          </NButton>
                          <NButton
                            text
                            disabled={route.query.isLook ? true : false}
                            onClick={() => {
                              addForm.id = item.id
                              addForm.lessonTargetDesc = item.lessonTargetDesc
                              addForm.name = item.name
                              afterTrain.open = true
                            }}
                          >
                            选择课后作业
                          </NButton>
                        </NSpace>
                      )
                    }}
                  </NCard>
                </NGi>
                {mapper && (
                  <NGi>
                    <NCard
                      title={mapper.name}
                      style={{
                        '--n-padding-top': '5px',
                        '--n-padding-bottom': '5px',
                        '--n-color': 'rgba(238,243,254,1)',
                        '--n-action-color': 'rgba(238,243,254,1)',
                        height: '100%'
                      }}
                    >
                      {{
                        default: () => (
                          <div>
                            <div style={{ paddingBottom: '12px' }}>{mapper.desc}</div>
                            <table style={{ width: '100%' }}>
                              <tr>
                                <td>单团学生</td>
                                <td style={{ 'text-align': 'right' }}>
                                  {mapper?.details?.[0]?.unitExaminationName || '无'}
                                </td>
                              </tr>
                              <tr>
                                <td>双团学生</td>
                                <td style={{ 'text-align': 'right' }}>
                                  {mapper?.details?.[1]?.unitExaminationName || '无'}
                                </td>
                              </tr>
                              <tr>
                                <td>多团学生</td>
                                <td style={{ 'text-align': 'right' }}>
                                  {mapper?.details?.[2]?.unitExaminationName || '无'}
                                </td>
                              </tr>
                            </table>
                          </div>
                        ),
                        action: () => (
                          <NSpace justify="space-around">
                            <NButton
                              text
                              disabled={route.query.isLook ? true : false}
                              onClick={() => {
                                unitData.open = true
                                unitData.model = mapper
                              }}
                            >
                              编辑阶段自测
                            </NButton>
                          </NSpace>
                        )
                      }}
                    </NCard>
                  </NGi>
                )}
              </>
            )
          })}
        </NGrid>
        {state.dataList.length ? null : <NEmpty />}

        {/* 课程编辑 */}
        <NModal
          preset="dialog"
          v-model:show={addForm.open}
          title={addForm.id ? '编辑课程' : '添加课程'}
          showIcon={false}
        >
          <NForm ref={addFormRef} model={addForm}>
            <NFormItem
              label="课程名称"
              required
              path="name"
              rule={[{ required: true, message: '请填写课程名称', trigger: ['blur', 'change'] }]}
            >
              <NInput v-model:value={addForm.name} />
            </NFormItem>
            <NFormItem
              label="是否需要解锁"
              required
              path="lockEnable"
              rule={[{ required: true, message: '请选择是否解锁', trigger: ['blur', 'change'] }]}
            >
              <NSelect
                v-model:value={addForm.lockEnable}
                options={
                  [
                    {
                      label: '是',
                      value: 'true'
                    },
                    {
                      label: '否',
                      value: 'false'
                    }
                  ] as any
                }
                clearable
              ></NSelect>
            </NFormItem>
            <NFormItem
              label="教学目标"
              required
              path="lessonTargetDesc"
              rule={[{ required: true, message: '请填写教学目标', trigger: ['blur', 'change'] }]}
            >
              <NInput
                type="textarea"
                rows={3}
                v-model:value={addForm.lessonTargetDesc}
                maxlength={500}
                showCount={true}
              />
            </NFormItem>
            <NSpace justify="end">
              <NButton onClick={() => (addForm.open = false)}>取消</NButton>
              <NButton type="primary" onClick={() => addCourseware()}>
                确认
              </NButton>
            </NSpace>
          </NForm>
        </NModal>

        {/* 课后作业 */}
        <NModal
          preset="dialog"
          v-model:show={afterTrain.open}
          title="选择课后作业"
          showIcon={false}
          style={{ width: '80vw' }}
        >
          <SelectAfterClassTraining
            courseTypeCode={props.course?.courseTypeCode}
            onHandleSuccess={addAfterTrain}
          />
        </NModal>

        {/* 课程详情编辑 */}
        <NDrawer v-model:show={courseData.open} width="80vw">
          <NDrawerContent title={courseData.title} closable>
            {{
              default: () => (
                <CourseKnowledgePoint
                  courseTypeCode={props.course?.courseTypeCode}
                  item={courseData.item as any}
                  onHandleSuccess={() => {
                    getDetail()
                  }}
                />
              ),
              footer: () => (
                <NSpace>
                  <NButton onClick={() => (courseData.open = false)}>取消</NButton>
                  <NButton type="primary" onClick={() => (courseData.open = false)}>
                    确认
                  </NButton>
                </NSpace>
              )
            }}
          </NDrawerContent>
        </NDrawer>

        {/* 阶段自测 */}
        <NModal
          preset="dialog"
          v-model:show={unitData.open}
          title={(unitData.model as any)?.id ? '编辑阶段自测' : '新增阶段自测'}
          showIcon={false}
          style={{ width: '500px' }}
        >
          <AddUnitTest
            courseTypeCode={props.course?.courseTypeCode}
            list={state.dataList}
            item={unitData.model}
            onClose={(result) => {
              if (result) {
                getDetail()
                getMapperAll()
              }
              unitData.open = false
            }}
          />
        </NModal>
      </div>
    )
  }
})
