import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NDatePicker,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref, provide } from 'vue'
import { fetchKnowledgeList, fetchDelKnowledge, knowledgePointStatus } from '../api'
import { knowledgeTypeData, lessonType } from '../knowledgeTypeData'
import KnowledgeModel from './component/knowledgeModel'
import { useRoute, useRouter } from 'vue-router'
import { filterTimes, getTimes } from '@/utils/dateUtil'
export default defineComponent({
  name: 'knowledge-manage',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      visiableKnowledge: false,
      modalType: 'add',
      materail: null as any
    })

    const searchForm = reactive({
      keyword: null as any,
      time: null,
      courseTypeCode: null,
      operatorId: null,
      enableFlag: null
    })
    const dialog = useDialog()
    const message = useMessage()

    // 获取知识点列表
    const knowledge = reactive({
      list: [] as any,
      index: -1
    })

    const getList = async () => {
      try {
        state.loading = true
        const { time, ...resset } = searchForm
        const { data } = await fetchKnowledgeList({
          ...resset,
          ...filterTimes(time, ['startUpdateTime', 'endUpdateTime']),
          page: state.pagination.page,
          rows: state.pagination.rows
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    onMounted(() => {
      console.log(route.query)
      if (route.query.keyword) {
        searchForm.keyword = route.query.keyword
      }
      getList()
    })

    // 打开详情
    const openDetail = (row: any) => {
      router.push({
        path: '/knowledgeDetail',
        query: {
          id: row.id,
          name: row.name,
          courseTypeCode: row.courseTypeCode
        }
      })
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '知识点',
          key: 'id',
          render: (row: any) => (
            <div style="display: inline-flex;vertical-align: middle;">
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="知识点名称">{row.name}</NDescriptionsItem>
                <NDescriptionsItem label="知识点编号">{row.id}</NDescriptionsItem>
              </NDescriptions>
            </div>
          )
        },
        {
          title: '课程类型',
          key: 'courseTypeName',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="课程类型">{row.courseTypeName}</NDescriptionsItem>
                <NDescriptionsItem label="自动播放">
                  {row.autoPlayFlag == 1 ? '是' : '否'}
                </NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '学习信息',
          key: 'totalMaterialNum',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="素材数量">{row.totalMaterialNum}</NDescriptionsItem>
                <NDescriptionsItem label="建议时长">
                  {(row.totalMaterialTimeSecond || 0) + 's'}
                </NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '上传信息',
          key: 'updateTime',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="修改人">{row.operatorName}</NDescriptionsItem>
                <NDescriptionsItem label="修改时间">{row.updateTime}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '状态',
          key: 'enableFlag',
          render(row: any) {
            return (
              <NTag type={row.enableFlag ? 'success' : 'warning'}>
                {row.enableFlag ? '已启用' : '未启用'}
              </NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  v-auth="knowledgePoint/status1605123728664281090"
                  type={row.enableFlag ? 'error' : 'success'}
                  size="small"
                  text
                  onClick={() => changeState(row)}
                >
                  {row.enableFlag ? '停用' : '启用'}
                </NButton>
                {/* 一级分类下是否有子项 */}
                {!(row.children && row.children.length > 0) && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => openDetail(row)}
                    v-auth="knowledgePointListByLessonCDId1604717561400045569"
                  >
                    详情
                  </NButton>
                )}
                {/* 是否是一级分类，一级分类下面是否有素材 */}
                {row.parentId <= 0 && !row.materialFlag && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    v-auth="knowledgePoint/update1604688172914417665"
                    onClick={() => {
                      state.modalType = 'add-child'
                      state.visiableKnowledge = true
                      state.materail = {
                        parentId: row.id,
                        courseTypeCode: row.courseTypeCode
                      }
                    }}
                  >
                    添加子项
                  </NButton>
                )}

                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="knowledgePoint/update1604688172914417665"
                  onClick={() => {
                    state.modalType = 'update'
                    state.visiableKnowledge = true
                    state.materail = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  disabled={row.enableFlag ? true : false}
                  text
                  v-auth="knowledgePoint/remove1604688068350418946"
                  onClick={() => {
                    handleDelete(row)
                  }}
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

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

    // 启用停用
    const changeState = async (row: any, open = true) => {
      dialog.warning({
        title: '警告',
        content: `是否${row.enableFlag ? '停用' : '启用'}此知识点?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          console.log('row', row)
          const res = await knowledgePointStatus(row.id)
          if (res.data) {
            getList()
            message.success('修改成功')
          }
        }
      })
    }

    // 删除
    const handleDelete = async (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此知识点?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          console.log('row', row)
          const res = await fetchDelKnowledge(row.id)
          if (res.data) {
            onSubmit()
            message.success('删除成功')
          }
        }
      })
    }

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

    return () => (
      <div class="system-menu-container">
        <div class={['section-container']}>
          <SaveForm
            ref={saveForm}
            model={searchForm}
            onSubmit={onSubmit}
            onSetModel={(val: any) => Object.assign(searchForm, val)}
          >
            <NFormItem path="search" label="关键字">
              <NInput v-model:value={searchForm.keyword} placeholder="知识组名称/编号" clearable />
            </NFormItem>
            <NFormItem label="课程类型" path="courseTypeCode">
              <NSelect clearable v-model:value={searchForm.courseTypeCode} options={lessonType} />
            </NFormItem>
            <NFormItem path="time" label="时间">
              <NDatePicker v-model:value={searchForm.time} type="daterange" clearable></NDatePicker>
            </NFormItem>
            <NFormItem label="状态" path="enableFlag">
              <NSelect
                placeholder="请选择状态"
                clearable
                v-model:value={searchForm.enableFlag}
                options={
                  [
                    { label: '已启用', value: 1 },
                    { label: '未启用', value: 0 }
                  ] as any
                }
              />
            </NFormItem>
            {/* <NFormItem path="status">
            <NSelect
              v-model:value={searchForm.operatorId}
              placeholder="上传人"
              options={employeeArray}
              clearable
            />
          </NFormItem> */}
            <NFormItem>
              <NSpace>
                <NButton type="primary" onClick={onSearch}>
                  搜索
                </NButton>
                <NButton type="default" onClick={onBtnReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </SaveForm>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              v-auth="knowledgePoint/save1604687872153460738"
              onClick={() => {
                state.visiableKnowledge = true
                state.modalType = 'add'
                state.materail = null
              }}
            >
              新增知识点
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
            children-key="children"
            default-expand-all={false}
            row-key={(row: any) => row.id}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>

          <NModal
            v-model:show={state.visiableKnowledge}
            preset="dialog"
            showIcon={false}
            title={state.modalType !== 'update' ? '新增知识点' : '修改知识点'}
            style={{ width: '500px' }}
            onClose={() => {
              state.materail = null
            }}
          >
            <KnowledgeModel
              item={state.materail}
              onHandleSuccess={(val: any) => {
                if (val) {
                  openDetail(val)
                  return
                }
                console.log(val)
                state.visiableKnowledge = false
                getList()
              }}
              onClose={() => {
                state.visiableKnowledge = false
                state.materail = null
              }}
            ></KnowledgeModel>
          </NModal>
        </div>
      </div>
    )
  }
})
