import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {DataTableRowKey, NButton, NDataTable, NFormItem, NIcon, NImage, NInput, NModal, NSelect, NSpace, NTag, useDialog, useMessage} from 'naive-ui'
import {defineComponent, onMounted, reactive, ref, watch} from 'vue'
import {musicSheetCategoriesQueryTree, musicSheetDetail, musicSheetPage, musicSheetRemove, musicSheetStatusList, musicTagPage} from '../../api'
import MusicOperation from '../modal/music-operation'
import {subjectPage} from '@/views/system-manage/api'
import MusicPreView from '../modal/musicPreView'
import {filterPointCategory} from '@/views/teaching-manage/unit-test'
import UseProject from "@views/music-library/music-sheet/modal/use-project";
import {getMapValueByKey} from "@/utils/filters";
import {musicSheetSourceType, musicSheetType} from "@/utils/constant";
import {getSelectDataFromObj} from "@/utils/objectUtil";
import {sysApplicationPage} from "@views/menu-manage/api";

export default defineComponent({
  name: 'music-list',
  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,
        musicSheetType: null,
        subjectId: null, //声部ID
        sourceType: null, //来源类型/作者属性(PLATFORM: 平台; ORG: 机构; PERSON: 个人
        composer: null, //作曲人/音乐人
        userId: null, //所属人
        applicationId: null, //适用项目ID
        status: null, //曲目状态（0：停用，1：启用）
        appAuditFlag: null, //是否审核版本
        categoriesId: null, //是否审核版本
      },
      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,
      showUseProject: false, // 适用项目
      useProjectData: [], // 适用项目行数据
      showUseProjectId: null as any, // 适用项目行数据
      detailReadonly: false // 新增、修改、详情是否可编辑
    })

    const columns = (): any => {
      return [
        {
          type: 'selection'
        },
        {
          title: '曲目编号',
          key: 'id'
        },
        // {
        //   title (column: any) {
        //     return <NImage width={60} height={60} src={column.titleImg}/>
        //   },
        //   key: 'id'
        // },
        {
          title: '曲目名称',
          key: 'name'
        },
        {
          title: '封面图',
          key: 'titleImg',
          render(row: any): JSX.Element {
            return <NImage width={60} height={60} src={row.musicCover}/>
          }
        },
        {
          title: '音乐人',
          key: 'composer'
        },
        {
          title: '曲目类型',
          key: 'musicSheetType',
          render(row: any) {
            return getMapValueByKey(row.musicSheetType, new Map(Object.entries(musicSheetType)));
          }
        },
        {
          title: '作者属性',
          key: 'sourceType',
          render(row: any) {
            return getMapValueByKey(row.sourceType, new Map(Object.entries(musicSheetSourceType)));
          }
        },
        {
          title: '所属人',
          key: 'composer'
        },
        {
          title: '上传人',
          key: 'createBy'
        },
        {
          title: '上传时间',
          key: 'createTime'
        },
        {
          title: '审核版本',
          key: 'userName'
        },
        {
          title: '适用项目',
          key: 'projectName',
          render(row: any) {
            return (
                <NSpace>
                  <NButton type="primary"
                           size="small"
                           text
                           onClick={() => {
                             state.showUseProject = true
                             state.showUseProjectId = row.id
                           }}
                  >
                    {row.musicSheetExtend && row.musicSheetExtend.useApplicationNames ? row.musicSheetExtend.useApplicationNames : ""}

                    <NIcon size={15} style="padding-left: 9px">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
                        <path d="M2 26h28v2H2z" fill="currentColor"></path>
                        <path d="M25.4 9c.8-.8.8-2 0-2.8l-3.6-3.6c-.8-.8-2-.8-2.8 0l-15 15V24h6.4l15-15zm-5-5L24 7.6l-3 3L17.4 7l3-3zM6 22v-3.6l10-10l3.6 3.6l-10 10H6z" fill="currentColor"></path>
                      </svg>
                    </NIcon>
                  </NButton>
                </NSpace>
            )
          }
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
                <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          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/update1602302618558099458"
                      onClick={() => {
                        state.visiableMusic = true
                        state.musicOperation = 'preview'
                        state.musicData = row
                        state.detailReadonly = true
                      }}
                  >
                    查看
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      //v-auth="musicSheet/update1602302618558099458"
                      onClick={() => {
                        state.visiableMusic = true
                        state.musicOperation = 'edit'
                        state.musicData = row
                        state.detailReadonly = true
                      }}
                  >
                    修改
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      //v-auth="musicSheet/status1612431726029942786"
                      onClick={() => onChangeStatus(row)}
                  >
                    {row.status ? '停用' : '启用'}
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      onClick={() => {
                      }}
                  >
                    生成图片
                  </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 checkedRowKeysRef = ref<DataTableRowKey[]>([])
    const handleCheck = (rowKeys: DataTableRowKey[]) => {
      checkedRowKeysRef.value = rowKeys
    }

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

    const onBatchChangeStatus = (status: boolean) => {
      const length = checkedRowKeysRef.value.length;
      if (length == 0) {
        message.warning("未选择数据")
      }
      const statusStr = !status ? '停用' : '启用'
      dialog.warning({
        title: '警告',
        content: `是否${statusStr}` + length + `条数据？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await musicSheetStatusList({
              ids: checkedRowKeysRef.value,
              status: status
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {
          }
        }
      })
    }

    const onRmove = (row: any): void => {
      dialog.warning({
        title: '警告',
        content: `删除"${row.name}"，是否继续？`,
        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.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 musicSheetCategoriesQueryTree({enable: true})
        state.musicSheetCategories = filterPointCategory(data, 'musicSheetCategoriesList')
      } catch (e) {
      }
    }

    // 获取声部
    const initSubjectList = 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 {
      }
    }

    // app列表
    const initUseAppList = async () => {
      try {
        const {data} = await sysApplicationPage({page: 1, rows: 999})
        const tempList = data.rows || []
        tempList.forEach((item: any) => {
          item.label = item.appName
          item.value = item.id
        })
        state.useProjectData = 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()
      if (props.searchId) {
        state.searchForm.categoriesId = props.searchId || null
      }

      initSubjectList()
      initUseAppList()
      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="musicSheetType">
              <NSelect
                  placeholder="请选择曲目类型"
                  v-model:value={state.searchForm.musicSheetType}
                  options={getSelectDataFromObj(musicSheetType)}
                  clearable
              />
            </NFormItem>
            <NFormItem label="声部" path="musicSubject">
              <NSelect
                  placeholder="请选择声部"
                  v-model:value={state.searchForm.subjectId}
                  options={state.subjectList}
                  clearable
              />
            </NFormItem>
            <NFormItem label="作者属性" path="authorFrom">
              <NSelect
                  placeholder="请选择作者属性"
                  v-model:value={state.searchForm.sourceType}
                  options={getSelectDataFromObj(musicSheetSourceType)}
                  clearable
              />
            </NFormItem>
            <NFormItem label="音乐人" path="author">
              <NInput
                  placeholder="请选择音乐人"
                  v-model:value={state.searchForm.composer}
                  clearable
              />
            </NFormItem>
            <NFormItem label="所属人" path="author">
              <NInput
                  placeholder="请选择所属人"
                  v-model:value={state.searchForm.userId}
                  clearable
              />
            </NFormItem>
            <NFormItem label="适用项目" path="app">
              <NSelect
                  placeholder="请选择适用项目"
                  v-model:value={state.searchForm.applicationId}
                  options={state.useProjectData}
                  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="appAuditFlag">
              <NSelect
                  v-model={[state.searchForm.appAuditFlag, 'value']}
                  placeholder="请选择审核版本"
                  clearable
                  options={
                    [
                      {
                        label: '是',
                        value: 1
                      },
                      {
                        label: '否',
                        value: 0
                      }
                    ] as any
                  }
              />
            </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 = {}
                    state.detailReadonly = true
                  }}
              >
                新增曲目
              </NButton>
              <NButton
                  disabled={checkedRowKeysRef.value.length == 0}
                  //v-auth="musicSheet/save1602302550719426561"
                  onClick={() => {
                    // state.musicOperation = 'unable'
                    // state.musicData = {}
                    onBatchChangeStatus(false)
                  }}
              >
                批量禁用
              </NButton>
              <NButton
                  disabled={checkedRowKeysRef.value.length == 0}
                  //v-auth="musicSheet/save1602302550719426561"
                  onClick={() => {
                    onBatchChangeStatus(true)
                    // state.musicOperation = 'enable'
                    // state.musicData = {}
                  }}
              >
                批量启用
              </NButton>
            </NSpace>

            <NDataTable
                loading={state.loading}
                columns={columns()}
                data={state.dataList}
                rowKey={(row: any) => row.id}
                onUpdateCheckedRowKeys={handleCheck}
            ></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}
              maskClosable={false}
              title={() => {
                if (state.musicOperation === 'add') {
                  return '添加曲目';
                } else if (state.musicOperation === 'preview') {
                  return '曲目详情';
                }
                return '修改曲目';
              }}
              style={{width: '980px'}}
          >
            <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>

          <NModal
              blockScroll={true}
              v-model:show={state.showUseProject}
              preset="dialog"
              showIcon={false}
              title={'适用项目'}
              style={{width: '500px'}}
          >
            <UseProject
                id={state.showUseProjectId}
                useProject={state.useProjectData}
                onClose={() => (state.showUseProject = false)}
                onGetList={getList}
            />
          </NModal>
        </div>
    )
  }
})
