import Pagination from '@/components/pagination'
import SaveForm from '@/components/save-form'
import { musicSheetPage, musicTagPage } from '@/views/content-manage/api'
import { subjectPage, sysApplicationPage } from '@/views/system-manage/api'
import {
  NButton,
  NImage,
  NSpace,
  NTag,
  NDataTable,
  NFormItem,
  NInput,
  NSelect,
  NCascader
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import styles from './index.module.less'
import { musicSheetCategoriesQueryTree } from '@views/music-library/api'
import { appKey } from '@/utils/constant'
import TheTooltip from '@/components/TheTooltip'

export default defineComponent({
  name: 'selectMusicSheet',
  props: {
    type: {
      type: String,
      default: 'upload'
    }
  },
  emits: ['select'],
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        musicCategoryId: null,
        subjectId: null,
        // playMode: null,
        // accompanimentType: null,
        status: null,
        topFlag: null,
        useAppId: [] as any
      },
      dataList: [] as any,
      subjectList: [] as any,
      musicSheetCategories: [] as any,
      useProjectData: [] as any, // 适用项目行数据
      visiableMusic: false,
      musicOperation: 'add',
      musicData: {} as any
    })

    const columns = (): any => {
      return [
        {
          title: '曲目名称',
          key: 'id',
          render(row: any) {
            return `${row.name}(${row.id})`
          }
        },
        {
          title: '适用项目',
          key: 'musicSheetExtend.useApplicationNames',
          redner(row: any) {
            return (
              <TheTooltip
                content={
                  row.musicSheetExtend && row.musicSheetExtend.useApplicationNames
                    ? row.musicSheetExtend.useApplicationNames
                    : ''
                }
              />
            )
          }
        },
        {
          title: '状态',
          minWidth: '50px',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '曲目封面',
          key: 'musicCover',
          render(row: any) {
            return <NImage width={35} height={35} src={row.musicCover} />
          }
        },
        {
          title: '分类',
          key: 'musicCategoryName'
        },
        {
          title: '伴奏类型',
          key: 'audioType',
          render(row: any) {
            return row.audioType === 'HOMEMODE' ? '自制伴奏' : '普通伴奏'
          }
        },
        {
          title: '可用声部',
          key: 'subjectNames',
          render(row: any) {
            return <TheTooltip content={row.subjectNames} />
          }
        },
        {
          title: '播放类型',
          key: 'playMode',
          render(row: any) {
            return (
              <>
                {row.playMode === 'MP3' && <NTag type="primary">MP3</NTag>}
                {row.playMode === 'MIDI' && <NTag type="default">MIDI</NTag>}
              </>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton type="success" size="small" text onClick={() => emit('select', row)}>
                  添加
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }
    const getList = async () => {
      try {
        state.loading = true
        const { data } = await musicSheetPage({
          page: state.pagination.page,
          rows: state.pagination.rows,
          ...state.searchForm,
          useAppId: state.searchForm.useAppId
            ? state.searchForm.useAppId.join(',')
            : state.searchForm.useAppId,
          status: props.type === 'upload' ? 1 : null
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    // app列表
    const initUseAppList = async () => {
      try {
        const appKeys = Object.keys(appKey)
        const { data } = await sysApplicationPage({ page: 1, rows: 999 })
        const tempList = data.rows || []
        state.useProjectData = []
        const filter = tempList.filter((next: any) => {
          return appKeys.includes(next.appKey)
        })
        filter.forEach((item: any) => {
          state.useProjectData.push({
            ...item,
            label: item.appName,
            value: item.id
          })
        })
      } catch {}
    }

    // 获取标签
    const getTagList = async () => {
      try {
        const { data } = await musicSheetCategoriesQueryTree({})
        state.musicSheetCategories = data || []
      } catch (e) {}
    }

    // 获取声部
    const getSubjectList = async () => {
      try {
        const { data } = await subjectPage({ page: 1, rows: 999 })
        const tempList = data.rows || []
        tempList.forEach((item: any) => {
          item.label = item.name
          item.value = item.id + ''
        })
        state.subjectList = tempList
      } catch {}
    }

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

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

    onMounted(() => {
      getTagList()
      getSubjectList()
      initUseAppList()
      getList()
    })
    return () => (
      <div class={styles.selectMusicSheet}>
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          saveKey="select-music-list"
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="关键字" path="keyword">
            <NInput
              placeholder="曲目编号/名称"
              v-model:value={state.searchForm.keyword}
              clearable
            />
          </NFormItem>
          <NFormItem label="曲目分类" path="musicCategoryId">
            <NCascader
              valueField="id"
              labelField="name"
              children-field="musicSheetCategoriesList"
              placeholder="请选择曲目分类"
              v-model:value={state.searchForm.musicCategoryId}
              options={state.musicSheetCategories}
              clearable
            />
          </NFormItem>
          <NFormItem label="声部" path="musicSubject">
            <NSelect
              placeholder="请选择声部"
              v-model:value={state.searchForm.subjectId}
              options={state.subjectList}
              clearable
            />
          </NFormItem>
          <NFormItem label="适用项目" path="useAppId">
            <NSelect
              placeholder="请选择适用项目"
              v-model:value={state.searchForm.useAppId}
              options={state.useProjectData}
              multiple
              maxTagCount={1}
              clearable
              filterable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>
        <NDataTable
          loading={state.loading}
          columns={columns()}
          scrollX={1200}
          data={state.dataList}
        ></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pagination.pageTotal}
          onList={getList}
          sync
          saveKey="select-music-list"
        ></Pagination>
      </div>
    )
  }
})
