import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NDatePicker,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NSpace,
  useDialog,
  useMessage,
  NModal
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import {  lessonPlanPage, lessonPlanRemove, lessonPlanUpdateEnableFlag } from '../api'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import { useRouter } from 'vue-router'
import { knowledgeTypeData, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import EidtPlan from './eidt-plan'
import { orchestraTypes } from '../teachingData'

export default defineComponent({
  name: 'teaching-plan',
  setup() {
    const router = useRouter()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      visiablePlan: false,
      modalType: 'add',
      materail: null,
      actvieRow: null as any
    })

    const searchForm = reactive<any>({
      name: '', // 计划名称
      keyword: '', // 关键字匹配
      enableFlag: null // 是否启用
    })
    const dialog = useDialog()
    const message = useMessage()

    const getList = async () => {
      try {
        state.loading = true
        const body = {
          page: state.pagination.page,
          rows: state.pagination.rows,
          ...searchForm
        }
        const { data } = await lessonPlanPage(body)
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

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

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

    //启用停用
    const handleChangeState = (row: any, type: boolean) => {
      dialog.warning({
        title: '警告',
        content: type ? '是否确认启用计划?' : '是否确认停用计划?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await lessonPlanUpdateEnableFlag({
            id: row.id,
            enableFlag: type
          })
          if (res.data) {
            onSubmit()
            message.success('操作成功')
          }
        }
      })
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '教学计划编号',
          key: 'id'
        },
        {
          title: '教学计划名称',
          key: 'name'
        },

        {
          title: '学期数',
          key: 'name',
          render(row) {
            return `第${row.sortNo}学期`
          }
        },
        {
          title: '课件数',
          key: 'coursewareNum'
        },
        {
          title: '状态',
          key: 'enableFlag',
          render(row) {
            return row.enableFlag ? '已启用' : '未启用'
          }
        },
        {
          title: '更新时间',
          key: 'updateTime'
        },
        {
          title: '更新人',
          key: 'operatorName'
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                {row.enableFlag ? (
                  <NButton
                    type="error"
                    size="small"
                    text
                    onClick={() => handleChangeState(row, false)}
                  >
                    停用
                  </NButton>
                ) : (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => handleChangeState(row, true)}
                  >
                    启用
                  </NButton>
                )}
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    gotoDetail(row)
                  }}
                >
                  详情
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    resetPlan(row)
                  }}
                >
                  修改
                </NButton>
                <NButton type="primary" size="small" text onClick={() => handleDelete(row)}>
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

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

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

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }
    // 修改
    const resetPlan = (row: any) => {
      state.actvieRow = row
      state.visiablePlan = true
    }

    // 详情
    const gotoDetail = (row: any) => {
      console.log(row)
      router.push({ path: '/planDetail', query: { name: row.name, id: row.id } })
    }
    return () => (
      <div class="system-menu-container">
        <div class={['section-container']}>
          <SaveForm
            ref={saveForm}
            model={searchForm}
            onSubmit={onSubmit}
            onSetModel={(val: any) => Object.assign(searchForm, val)}
            saveKey="courseware-manage-key"
          >
            <NFormItem path="keyword" label="关键词">
              <NInput v-model:value={searchForm.keyword} placeholder="计划名称/编号" clearable />
            </NFormItem>
            <NFormItem path="enableFlag" label="是否启用">
              <NSelect
                placeholder="是否启用"
                clearable
                v-model:value={searchForm.enableFlag}
                options={[
                  { label: '是', value: 1 },
                  { label: '否', value: 0 }
                ]}
              />
            </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"
              onClick={() => {
                state.actvieRow = null
                state.visiablePlan = true
              }}
            >
              新增教学计划
            </NButton>
          </NSpace>

          <NDataTable
            scrollX={1000}
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            saveKey="after-class-training-manage-key"
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiablePlan}
          preset="dialog"
          showIcon={false}
          title={state.actvieRow ? '修改教学计划' : '新增教学计划'}
          style={{ width: '550px' }}
        >
          <EidtPlan
            actvieRow={state.actvieRow}
            onClose={() => {
              state.visiablePlan = false
            }}
            onGetList={() => {
              state.visiablePlan = false
              getList()
            }}
          ></EidtPlan>
        </NModal>
      </div>
    )
  }
})
