import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage,
  NCascader,
  NDescriptions,
  NDescriptionsItem
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { musicSheetPage, musicSheetRemove, musicSheetStatus, musicTagPage } from '../../api'
import MusicOperation from '../modal/music-operation'
import { subjectBasicConfigPage } from '@/views/system-manage/api'
import { accompanimentTypeArray, audioTypeArray } from '@/utils/searchArray'
import MusicPreView from '../modal/musicPreView'
import TheTooltip from '@/components/TheTooltip'
import { filterPointCategory } from '@/views/teaching-manage/unit-test'
import {musicSheetCategoriesPage} from "@views/music-library/api";

export default defineComponent({
  name: 'content-flash',
  props: ['searchId'],
  setup(props, { emit }) {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        musicTag: null,
        musicSubject: null,
        audioType: null,
        accompanimentType: null,
        status: null,
        topFlag: null,
        musicSheetCategoriesId: props.searchId
      },
      dataList: [] as any,
      subjectList: [] as any,
      tagList: [] as any,
      visiableMusic: false,
      musicOperation: 'add',
      musicData: {} as any,
      musicSheetCategories: [] as any,
      musicPreview: false,
      musicScore: null as any
    })

    const columns = (): any => {
      return [
        {
          title: '曲目名称',
          key: 'id',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="曲目名称">
                  <TheTooltip content={row.musicSheetName} />{' '}
                </NDescriptionsItem>
                <NDescriptionsItem label="曲目编号">{row.id}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '曲目封面',
          key: 'titleImg',
          render(row: any) {
            return <NImage width={60} height={60} src={row.titleImg} />
          }
        },
        {
          title: '曲目信息',
          key: 'musicSheetCategoriesName',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="曲目分类">
                  <TheTooltip content={row.musicSheetCategoriesName} />{' '}
                </NDescriptionsItem>
                <NDescriptionsItem label="伴奏类型">
                  {row.accompanimentType === 'HOMEMODE' ? '自制伴奏' : '普通伴奏'}
                </NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        {
          title: '可用声部',
          key: 'musicSubject',
          render(row: any) {
            return <NTag type="primary">{row.musicSheetType === 'CONCERT' ? '合奏' :row.musicSubject}</NTag>
          }
        },
        {
          title: '播放类型',
          key: 'audioType',
          render(row: any) {
            return (
              <>
                {row.audioType === 'MP3' && <NTag type="primary">MP3</NTag>}
                {row.audioType === 'MIDI' && <NTag type="default">MIDI</NTag>}
              </>
            )
          }
        },
        {
          title: '能否转简谱',
          key: 'notation',
          render(row: any) {
            return (
              <NTag type={row.notation ? 'primary' : 'default'}>{row.notation ? '是' : '否'}</NTag>
            )
          }
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '排序',
          key: 'sortNumber'
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => {
                    state.musicPreview = true
                    state.musicScore = row
                  }}
                >
                  预览
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="musicSheet/status1612431726029942786"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="musicSheet/update1602302618558099458"
                  onClick={() => {
                    state.visiableMusic = true
                    state.musicOperation = 'edit'
                    state.musicData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => onRmove(row)}
                  //v-auth="musicSheet/remove1602302689404088321"
                >
                  删除
                </NButton>
                {/* <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => onRmove(row)}
                  v-auth="musicSheet/remove1599694768375701505"
                >
                  {row.topFlag ? '取消置顶' : '置顶'}
                </NButton> */}
              </NSpace>
            )
          }
        }
      ]
    }

    const onChangeStatus = (row: any) => {
      const statusStr = row.status ? '停用' : '启用'
      dialog.warning({
        title: '警告',
        content: `是否${statusStr}？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await musicSheetStatus({
              id: row.id
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {}
        }
      })
    }

    const onRmove = (row: any): void => {
      dialog.warning({
        title: '警告',
        content: `删除"${row.musicSheetName}"，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await musicSheetRemove({ id: row.id })
            getList()
            message.success('删除成功')
          } catch {}
        }
      })
    }

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

    // 获取标签
    const getTagList = async () => {
      try {
        const { data } = await musicTagPage({ page: 1, rows: 999 })
        const tempList = data.rows || []
        tempList.forEach((item: any) => {
          item.label = item.name
          item.value = item.id
        })
        state.tagList = tempList
      } catch {}
    }

    // 获取分类
    const getMusicSheetCategorieList = async () => {
      try {
        const { data } = await musicSheetCategoriesPage({ enable: true })
        state.musicSheetCategories = filterPointCategory(data, 'musicSheetCategoriesList')
      } catch (e) {}
    }

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

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }
    watch(
      () => props.searchId,
      (val) => {
        console.log(val, 'searchId')
      }
    )
    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    onMounted(() => {
      // getTagList()
      console.log()
      if (props.searchId) {
        state.searchForm.musicSheetCategoriesId = props.searchId || null
      }

      getSubjectList()
      getList()
      getMusicSheetCategorieList()
    })
    return () => (
      <div class="system-menu-container">
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          saveKey="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="musicTag">
            <NSelect
              placeholder="请选择标签"
              v-model:value={state.searchForm.musicTag}
              options={state.tagList}
              clearable
            />
          </NFormItem> */}
          <NFormItem label="分类" path="musicSheetCategoriesId">
            <NCascader
              valueField="id"
              labelField="name"
              children-field="musicSheetCategoriesList"
              placeholder="请选择分类"
              v-model:value={state.searchForm.musicSheetCategoriesId}
              options={state.musicSheetCategories}
              clearable
            />
          </NFormItem>
          <NFormItem label="声部" path="musicSubject">
            <NSelect
              placeholder="请选择声部"
              v-model:value={state.searchForm.musicSubject}
              options={state.subjectList}
              clearable
            />
          </NFormItem>
          <NFormItem label="播放类型" path="audioType">
            <NSelect
              placeholder="请选择播放类型"
              v-model:value={state.searchForm.audioType}
              options={audioTypeArray}
              clearable
            />
          </NFormItem>
          <NFormItem label="状态" path="status">
            <NSelect
              v-model={[state.searchForm.status, 'value']}
              placeholder="请选择状态"
              clearable
              options={
                [
                  {
                    label: '启用',
                    value: true
                  },
                  {
                    label: '停用',
                    value: false
                  }
                ] as any
              }
            />
          </NFormItem>
          {/* <NFormItem label="伴奏类型" path="accompanimentType">
            <NSelect
              placeholder="请选择伴奏类型"
              v-model:value={state.searchForm.accompanimentType}
              options={accompanimentTypeArray}
              clearable
            />
          </NFormItem> */}
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>
        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              //v-auth="musicSheet/save1602302550719426561"
              onClick={() => {
                state.visiableMusic = true
                state.musicOperation = 'add'
                state.musicData = {}
              }}
            >
              添加曲目
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            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="music-list"
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiableMusic}
          preset="dialog"
          showIcon={false}
          title={state.musicOperation === 'add' ? '新增曲目' : '修改曲目'}
          style={{ width: '950px' }}
        >
          <MusicOperation
            type={state.musicOperation}
            data={state.musicData}
            subjectList={state.subjectList}
            musicSheetCategories={state.musicSheetCategories}
            // tagList={state.tagList}
            onClose={() => (state.visiableMusic = false)}
            onGetList={getList}
          />
        </NModal>
        <NModal
          blockScroll={true}
          v-model:show={state.musicPreview}
          preset="dialog"
          showIcon={false}
          title={'曲目预览'}
          style={{ width: 'auto' }}
        >
          <MusicPreView item={state.musicScore} />
        </NModal>
      </div>
    )
  }
})
