import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { NButton, NForm, NFormItem, NPopselect, NSpace } from 'naive-ui';
import iconUpload from '../../images/icon-upload.png';
import iconEdit from '../../images/icon-edit.png';
import iconSelectAll from '../../images/icon-selectall.png';
import iconSelectAllDefault from '../../images/icon-selectall-default.png';
import iconPen from '../../images/icon-pen.png';
import iconDelete from '../../images/icon-delete.png';
import TheSearch from '/src/components/TheSearch';
import { resourceTypeArray } from '/src/utils/searchArray';
import { useCatchStore } from '/src/store/modules/catchData';

export default defineComponent({
  name: 'search-group',
  emits: [
    'search',
    'upload',
    'edit',
    'selectAll',
    'delete',
    'update',
    'editOver',
    'cancel'
  ],
  setup(props, { emit, expose }) {
    const resourceList = ref([] as any[]);
    const catchStore = useCatchStore();
    const forms = reactive({
      type: 'MUSIC', //
      name: '',
      audioPlayTypes: ['PLAY'],
      bookVersionId: null,
      subjectId: null,
      materialTagId: null
    });
    const state = reactive({
      tempSubjectId: null,
      isEdit: false, // 是否编辑
      isSelectAll: false
    });

    const onSearch = () => {
      emit('search', forms);
    };

    /** 默认选中第一个声部 */
    const formatFirstSubject = () => {
      const tempSubjects = catchStore.getSubjectInstrumentOnly;
      if (tempSubjects.length > 0) {
        const firstSubject = tempSubjects[0];
        if (firstSubject.instruments && firstSubject.instruments.length > 1) {
          state.tempSubjectId = firstSubject.instruments[0]?.value;
          forms.subjectId = firstSubject.instruments[0]?.value;
        } else {
          forms.subjectId = firstSubject.value;
        }
      }

      onSearch();
    };

    onMounted(async () => {
      resourceList.value = [];
      resourceTypeArray.forEach((item: any) => {
        resourceList.value.push(item);
      });

      // 获取声部列表
      await catchStore.getSubjects();
      // 获取素材标签
      await catchStore.getMaterialTagsApi();

      if (forms.subjectId) {
        state.tempSubjectId = forms.subjectId;
      }

      formatFirstSubject();
    });

    const selectChildObj = (item: any) => {
      const obj: any = {};
      item?.forEach((child: any) => {
        if (child.id === forms.subjectId) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };

    const resetStatus = () => {
      state.isSelectAll = false;
    };
    expose({
      resetStatus
    });
    return () => (
      <div class={styles.searchGroup}>
        <div class={styles.searchCatatory}>
          <NSpace size="small" class={styles.btnType}>
            {resourceList.value.map((item: any) => (
              <NButton
                type={forms.type === item.value ? 'primary' : 'default'}
                secondary={forms.type === item.value ? false : true}
                round
                size="small"
                focusable={false}
                onClick={() => {
                  if (forms.type !== item.value) {
                    state.isEdit = false;
                    state.isSelectAll = false;
                    emit('edit', state.isEdit);
                  }
                  forms.audioPlayTypes = item.value === 'MUSIC' ? ['PLAY'] : [];
                  forms.type = item.value;
                  // forms.subjectId = null;
                  // state.tempSubjectId = null;

                  forms.materialTagId = null;
                  // onSearch();

                  formatFirstSubject();
                }}>
                {item.label}
              </NButton>
            ))}
          </NSpace>

          <NSpace size="small" class={styles.btnGroup}>
            {state.isEdit ? (
              <>
                <NButton
                  type="primary"
                  class={styles.addTrain}
                  focusable={false}
                  strong
                  onClick={() => {
                    state.isSelectAll = !state.isSelectAll;
                    emit('selectAll', state.isSelectAll);
                  }}>
                  <img
                    src={
                      state.isSelectAll ? iconSelectAll : iconSelectAllDefault
                    }
                    class={styles.iconSelectAll}
                  />
                  全选
                </NButton>
                <NButton
                  type="error"
                  class={[styles.addTrain, styles.error]}
                  focusable={false}
                  strong
                  onClick={() => emit('delete')}>
                  <img src={iconDelete} class={styles.iconDelete} />
                  删除
                </NButton>
                {forms.type !== 'MUSIC' && (
                  <NButton
                    type="primary"
                    class={styles.addTrain}
                    focusable={false}
                    strong
                    onClick={() => emit('update')}>
                    <img src={iconPen} class={styles.iconPen} />
                    修改
                  </NButton>
                )}

                <NButton
                  type="primary"
                  class={styles.addTrain}
                  focusable={false}
                  strong
                  onClick={() => {
                    state.isEdit = false;
                    state.isSelectAll = false;
                    emit('editOver', state.isEdit);
                  }}>
                  完成编辑
                </NButton>
                <NButton
                  type="error"
                  class={[styles.addTrain, styles.error]}
                  focusable={false}
                  strong
                  onClick={() => {
                    state.isEdit = false;
                    state.isSelectAll = false;
                    emit('cancel', state.isEdit);
                  }}>
                  {/* <img src={iconDelete} class={styles.iconDelete} /> */}
                  取消编辑
                </NButton>
              </>
            ) : (
              <>
                <NButton
                  type="primary"
                  class={styles.addTrain}
                  focusable={false}
                  {...{ id: 'myResources-0' }}
                  strong
                  onClick={() => emit('upload')}>
                  <img src={iconUpload} class={styles.iconUpload} />
                  上传资源
                </NButton>
                <NButton
                  type="primary"
                  class={styles.addTrain}
                  focusable={false}
                  strong
                  onClick={() => {
                    state.isEdit = true;
                    emit('edit', state.isEdit);
                  }}>
                  <img src={iconEdit} class={styles.iconEdit} />
                  编辑资源
                </NButton>
              </>
            )}
          </NSpace>
        </div>
        <NForm labelAlign="left" labelPlacement="left">
          <NFormItem label="乐器：">
            <NSpace class={styles.spaceSection2}>
              {catchStore.getSubjectInstrumentOnly.map((subject: any) =>
                subject.instruments && subject.instruments.length > 1 ? (
                  <NPopselect
                    options={subject.instruments}
                    trigger="hover"
                    scrollable
                    v-model:value={state.tempSubjectId}
                    onUpdate:value={() => {
                      if (state.tempSubjectId !== subject.value) {
                        state.isEdit = false;
                        state.isSelectAll = false;
                        emit('edit', state.isEdit);
                      }
                      // if (forms.type === 'MUSIC') {
                      forms.subjectId = state.tempSubjectId;
                      // }
                      onSearch();
                    }}
                    key={subject.value}
                    class={[styles.popSelect]}>
                    <span
                      class={[
                        styles.textBtn,
                        selectChildObj(subject.instruments).selected &&
                          styles.textBtnActive
                      ]}>
                      {selectChildObj(subject.instruments).name || subject.name}
                      <i class={styles.iconArrow}></i>
                    </span>
                  </NPopselect>
                ) : (
                  <span
                    class={[
                      styles.textBtn,
                      forms.subjectId === subject.value && styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.subjectId = subject.value;

                      state.tempSubjectId = null;
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                )
              )}
            </NSpace>
          </NFormItem>

          {/* 乐谱没有标签 */}
          {forms.type !== 'MUSIC' && (
            <NFormItem label="标签：">
              <NSpace class={styles.spaceSection2}>
                {catchStore.getAllMaterialTags.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,
                      forms.materialTagId === subject.value && styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.materialTagId = subject.value;
                      onSearch();
                    }}>
                    {subject.label}
                  </span>
                ))}
              </NSpace>
            </NFormItem>
          )}

          <TheSearch
            class={styles.inputSearch}
            value={forms.name}
            onUpdate:value={(val: string) => {
              forms.name = val;
            }}
            round
            onSearch={(val: string) => {
              forms.name = val;
              onSearch();
            }}
          />
        </NForm>
      </div>
    );
  }
});
