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 { getMusicSheetCategories, musicSheetCategoriesSwitching } 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 EidtCategroy from './components/eidt-categroy'

type RowData = {
  id: string
  name: string
  coverImg: string
  musicSheetNum: string
  updateTime: string
  enable: boolean
  musicSheetCategoriesList?: RowData[]
}
export default defineComponent({
  emits: ['setTabName'],
  name: 'music-categrory',
  setup(props, { emit }) {
    const router = useRouter()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 999,
        pageTotal: 0
      },
      dataList: [] as any,
      visiablePlan: false,
      modalType: 'add',
      materail: null,
      actvieRow: null as any,
      isAdd: true
    })

    const searchForm = reactive<any>({
      name: '', // 计划名称
      keyword: '', // 关键字匹配
      enable: 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 getMusicSheetCategories(body)
        state.loading = false
        // state.pagination.pageTotal = Number(data.total)
        state.dataList = (data as RowData[]) || []
      } catch {
        state.loading = false
      }
    }

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

    //启用停用
    const handleChangeState = (row: any, type: boolean) => {
      dialog.warning({
        title: '警告',
        content: type ? `是否确认启用${row.name}?` : `是否确认停用${row.name}?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const res = await musicSheetCategoriesSwitching(row.id)
            message.success('操作成功')
            onSubmit()
          } catch (e) {}
        }
      })
    }

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '教材编号',
          key: 'id'
        },
        {
          title: '教材名称',
          key: 'name'
        },
        {
          title: '教材封面',
          key: 'coverImg',
          render: (row: any) => (
            <img src={row.coverImg} style={{ width: '175px', height: '70px' }} alt="" />
          )
        },
        {
          title: '曲目数量',
          key: 'musicSheetNum'
        },

        // {
        //   title: '使用音源',
        //   key: 'soundResource'
        //   //   render(row) {
        //   //     return `第${row.semesterNo}学期`
        //   //   }
        // },
        {
          title: '最后更新时间',
          key: 'updateTime'
        },
        {
          title: '教材状态',
          key: 'enable',
          render(row) {
            return row.enable ? '已启用' : '未启用'
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                {row.enable ? (
                  <NButton
                    //v-auth="musicSheetCategories/switching1608067671668359169"
                    type="error"
                    size="small"
                    text
                    onClick={() => handleChangeState(row, false)}
                  >
                    停用
                  </NButton>
                ) : (
                  <NButton
                    //v-auth="musicSheetCategories/switching1608067671668359169"
                    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)
                  }}
                  //v-auth="musicSheetCategories/update1608067835686617090"
                >
                  修改
                </NButton>
                {row.currentLevel < 4 ? (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => handleAdd(row)}
                    //v-auth="musicSheetCategories/save1608067543331045378"
                  >
                    添加
                  </NButton>
                ) : null}
              </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.isAdd = false
      state.visiablePlan = true
    }
    // 曲目新增
    const handleAdd = (row: any) => {
      state.actvieRow = row
      state.isAdd = true
      state.visiablePlan = true
    }
    // 详情
    const gotoDetail = (row: any) => {
      console.log('gotoDetail')
      emit('setTabName', {
        id: row.id,
        tabName: 'MusicList'
      })
      // 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="music-categrory"
          >
            {/* <NFormItem path="keyword" label="计划名称/编号">
              <NInput v-model:value={searchForm.keyword} placeholder="计划名称/编号" clearable />
            </NFormItem> */}

            <NFormItem path="enable" label="教材状态">
              <NSelect
                placeholder="教材状态"
                clearable
                v-model:value={searchForm.enable}
                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"
              //v-auth="musicSheetCategories/save1608067543331045378"
              onClick={() => {
                state.actvieRow = null
                state.visiablePlan = true
                state.isAdd = true
              }}
            >
              新增分类
            </NButton>
          </NSpace>

          <NDataTable
            scrollX={1000}
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
            rowKey={(row: any) => row.id}
            childrenKey="musicSheetCategoriesList"
          ></NDataTable>
        </div>
        <NModal
          v-model:show={state.visiablePlan}
          preset="dialog"
          showIcon={false}
          title={state.actvieRow ? '修改曲谱分类' : '新增曲谱分类'}
          style={{ width: '550px' }}
        >
          <EidtCategroy
            onGetList={() => {
              state.visiablePlan = false
              getList()
            }}
            onClose={() => {
              state.visiablePlan = false
            }}
            list={state.dataList}
            isAdd={state.isAdd}
            actvieRow={state.actvieRow}
          ></EidtCategroy>
        </NModal>
      </div>
    )
  }
})
