import {
  PropType,
  computed,
  defineComponent,
  onMounted,
  reactive,
  watch
} from 'vue';
import styles from './index.module.less';
import { Button, Collapse, CollapseItem, showToast } from 'vant';
import {
  barLineList,
  beatList,
  elementList,
  initSelectScorePartModal,
  renderScore,
  renderScoreModal,
  setting,
  setting_modal,
  getTempList,
  tempo4,
  tempo8
} from '../setting';
import { getImage } from '../images/music';
import { hendleEndTick } from '../tick';
import { hendleEndBeat } from '../beat-tick';
import { useRoute } from 'vue-router';
import settingArrowActive from '../images/setting-arrow-active.png';
import settingArrowDefault from '../images/setting-arrow-default.png';
import Draggable from 'vuedraggable';

export default defineComponent({
  emits: ['close'],
  props: {
    class: {
      type: Object as PropType<any>,
      default: () => {}
    }
    // dataJson: {
    //   type: Object,
    //   default: () => {}
    // }
  },
  name: 'setting-modal',
  setup(props, { emit, expose }) {
    const route = useRoute();
    // const { element, beat, barLine, tempo } = props.dataJson;

    const tempDeepClone = (val: any) => {
      return JSON.parse(JSON.stringify(val));
    };
    const state = reactive({
      win: route.query.win,
      platform: route.query.platform,
      activeNames: ['base', 'beat'] as any, // 折叠面板
      element:
        tempDeepClone(setting_modal.element) ||
        ('jianpu' as 'jianpu' | 'staff'), // 元素
      beat:
        tempDeepClone(setting_modal.beat) ||
        ('4-4' as '4-2' | '4-3' | '4-4' | '8-3' | '8-6'), // 拍号
      barLine: tempDeepClone(setting_modal.barLine) || ('1' as '1' | '2' | '4'), // 小节数
      tempo: tempDeepClone(setting_modal.tempo) || (['1', '2', '3'] as any[]) // 节奏形筛选
    });

    const tempoList = computed(() => {
      if (['4-2', '4-3', '4-4'].includes(state.beat)) {
        return getTempList(state.element).tempo4;
      } else if (['8-3', '8-6'].includes(state.beat)) {
        return  getTempList(state.element).tempo8;
      }
      return  getTempList(state.element).tempo4;
    });
    const tempoListNum = computed(() => {
      if (['4-2', '4-3', '4-4'].includes(state.beat)) {
        return getTempList(state.element).tempo4Num;
      } else if (['8-3', '8-6'].includes(state.beat)) {
        return  getTempList(state.element).tempo8Num;
      }
      return  getTempList(state.element).tempo4Num;
    });

    // 重置选中数据
    watch(
      () => setting_modal,
      () => {
        state.element =
          tempDeepClone(setting_modal.element) ||
          ('jianpu' as 'jianpu' | 'staff'); // 元素
        state.beat =
          tempDeepClone(setting_modal.beat) ||
          ('4-4' as '4-2' | '4-3' | '4-4' | '8-3' | '8-6'); // 拍号
        state.barLine =
          tempDeepClone(setting_modal.barLine) || ('1' as '1' | '2' | '4'); // 小节数
        state.tempo =
          tempDeepClone(setting_modal.tempo) || (['1', '2', '3'] as any[]); // 节奏形筛选
      },
      {
        deep: true
      }
    );

    const getBeatUrl = (value: any) => {
      const prefix = state.element === 'jianpu' ? 'j-' : 'f-';
      return prefix + value + '.png';
    };
    const onChangeTempo = (item: any) => {
      let si = 0,
        ji = 0;
      let status = false;
      setting_modal.scorePart.forEach((part: Array<any>, i: number) => {
        part.forEach((child: any, j: number) => {
          if (child.selected) {
            child.url = getBeatUrl(item);
            child.index = item;
            child.selected = false;
            si = i;
            ji = j;

            status = true;
          }
        });
      });

      if (status) {
        const indexs = toNext(si, ji);
        if (indexs && indexs.length > 0) {
          initSelectScorePartModal(indexs[0], indexs[1]);
        }
      }
    };

    const toNext = (i: number, j: number) => {
      const scorePart = setting_modal.scorePart;
      let tempJ = j + 1;
      for (let si = i; si < scorePart.length; si++) {
        for (let ji = tempJ; ji < scorePart[si].length; ji++) {
          return [si, ji];
        }
        tempJ = 0;
      }
    };

    const handleStop = () => {
      setting_modal.playState = 'pause';
      if (setting_modal.playType === 'beat') {
        hendleEndTick();
      } else {
        hendleEndBeat();
      }
    };

    /** 数据有变化时重置 */
    const onChangeResetTempo = () => {
      // if (state.tempo.length <= 0) {
      //   showToast('节奏型不能为空');
      //   return;
      // }
      let status = false; // 是否有更改
      if (
        setting_modal.element !== state.element ||
        setting_modal.beat !== state.beat ||
        setting_modal.barLine !== state.barLine ||
        setting_modal.tempo.join(',') !== state.tempo.join(',')
      ) {
        status = true;
      }

      // 判断是否有数据变化
      handleStop();
      if (status) {
        setting_modal.element = tempDeepClone(state.element);
        setting_modal.beat = tempDeepClone(state.beat); //state.beat;
        setting_modal.barLine = tempDeepClone(state.barLine); // state.barLine;
        setting_modal.tempo = tempDeepClone(state.tempo); // state.tempo;
        renderScoreModal();
      }
    };

    const onSubmit = () => {
      // 初始化设置的数据
      for (let i in setting_modal) {
        setting[i] = JSON.parse(JSON.stringify(setting_modal[i]));
      }

      emit('close');
    };

    const tempoListData = computed(() => {
      const list = tempoListNum.value  // Object.keys(tempoList.value);
      return list.map((key: any) => {
        return {
          index: key,
          key: key,
          url: getBeatUrl(key),
          sourceFrom: 'setting-modal'
        };
      });
    });

    expose({
      onSubmit
    });

    return () => (
      <div
        class={[
          props.class,
          styles.settingContainer,
          state.win === 'pc' ? styles.pcS : '',
          state.platform === 'modal' && state.win !== 'pc' ? styles.modalS : ''
        ]}>
        {/* <div class={styles.title}></div> */}
        <div class={[styles.iconTitBox, 'iconTitBoxMove']}>
          <i
            class={styles.iconClose}
            onClick={() => {
              emit('close');
              setTimeout(() => {
                state.element = tempDeepClone(setting_modal.element);
                state.beat = tempDeepClone(setting_modal.beat); //state.beat;
                state.barLine = tempDeepClone(setting_modal.barLine); // state.barLine;
                state.tempo = tempDeepClone(setting_modal.tempo); // state.tempo;
              }, 300);
            }}></i>
        </div>

        <div class={[styles.settingContent]}>
          <Collapse v-model={state.activeNames} border={false}>
            <CollapseItem
              title="基础设置"
              name="base"
              border={false}
              isLink={false}
              class={[
                styles.collapseContainer,
                state.activeNames.includes('base') ? '' : styles.paddingBottom
              ]}>
              {{
                icon: () => (
                  <img
                    src={
                      state.activeNames.includes('base')
                        ? settingArrowActive
                        : settingArrowDefault
                    }
                    class={styles.iArrow}
                  />
                ),
                default: () => (
                  <>
                    <div class={styles.parmaTitle}>元素</div>
                    <div class={styles.paramContent}>
                      {Object.keys(elementList).map((item: any) => (
                        <Button
                          round
                          class={[
                            styles.btn,
                            state.element === item && styles.active
                          ]}
                          onClick={() => {
                            state.element = item;
                            onChangeResetTempo();
                          }}>
                          {elementList[item]}
                        </Button>
                      ))}
                    </div>
                    <div class={styles.parmaTitle}>拍号</div>
                    <div class={[styles.paramContent, styles.beatContent]}>
                      {Object.keys(beatList).map((item: any) => (
                        <Button
                          round
                          class={[
                            styles.btn,
                            state.beat === item && styles.active
                          ]}
                          onClick={() => {
                            state.beat = item;
                            if (['4-2', '4-3', '4-4'].includes(state.beat)) {
                              state.tempo = ['1', '2', '3'];
                            } else if (['8-3', '8-6'].includes(state.beat)) {
                              state.tempo = ['15', '16', '17'];
                            }
                            onChangeResetTempo();
                          }}>
                          {beatList[item]}
                        </Button>
                      ))}
                    </div>
                    <div class={styles.parmaTitle}>每页显示小节数量</div>
                    <div class={styles.paramContent}>
                      {Object.keys(barLineList).map((item: any) => (
                        <Button
                          round
                          class={[
                            styles.btn,
                            state.barLine === item && styles.active
                          ]}
                          onClick={() => {
                            state.barLine = item;
                            onChangeResetTempo();
                          }}>
                          {barLineList[item]}
                        </Button>
                      ))}
                    </div>
                  </>
                )
              }}
            </CollapseItem>
            <CollapseItem
              title="节奏型"
              name="beat"
              border={false}
              isLink={false}
              class={styles.collapseContainer}>
              {{
                icon: () => (
                  <img
                    src={
                      state.activeNames.includes('beat')
                        ? settingArrowActive
                        : settingArrowDefault
                    }
                    class={styles.iArrow}
                  />
                ),
                default: () => (
                  <>
                    {/* <div class={styles.parmaTitle}>节奏型筛选</div> */}

                    <Draggable
                      modelValue={tempoListData.value}
                      itemKey="id"
                      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                      // @ts-ignore
                      // group="description"
                      group={{
                        name: 'description',
                        pull: 'clone',
                        put: false
                      }}
                      animation={200}
                      sort={false}
                      onMove={(evt: any) => {
                        return evt.from !== evt.to;
                      }}
                      onStart={(evt: any) => {
                        evt.from.classList.add('onstart');
                      }}
                      onEnd={(evt: any) => {
                        evt.from.classList.remove('onstart');
                      }}
                      componentData={{
                        draggable: 'row-nav',
                        itemKey: 'id',
                        tag: 'div',
                        pull: 'clone',
                        put: false,
                        animation: 200,
                        group: 'description'
                      }}
                      class={[styles.paramContent, styles.tempo]}>
                      {{
                        item: (element: any) => {
                          const item = element.element;
                          return (
                            <div
                              data-id={item.key}
                              onClick={() => onChangeTempo(item.key)}>
                              <img
                                class={'draggable'}
                                // class={state.tempo.includes(item) && styles.active}
                                src={getImage(
                                  (state.element === 'jianpu' ? 'j-' : 'f-') +
                                    tempoList.value[item.key]
                                )}
                              />
                            </div>
                          );
                        }
                      }}
                    </Draggable>
                  </>
                )
              }}
            </CollapseItem>
          </Collapse>
          {/* <div class={styles.settingParams}></div> */}
        </div>
        {!state.win && !state.platform && (
          <div class={styles.btnGroup}>
            <Button class={styles.btnSubmit} onClick={onSubmit}></Button>
          </div>
        )}
      </div>
    );
  }
});
