import { NPopover, NScrollbar, NTooltip } from 'naive-ui';
import {
  PropType,
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch
} from 'vue';
import styles from './index.module.less';
import arrowDown from './images/icon-arrow-down.png';
import arrowUp from './images/icon-arrow-up.png';
import arrowDownSmall from './images/icon-arrow-down_small.png';
import arrowUpSmall from './images/icon-arrow-up_small.png';
import { audioPlayType } from '/src/utils/contants';

export default defineComponent({
  name: 'c-cascader',
  props: {
    /** 是否显示场景搜索条件 */
    showAudioPlayType: {
      type: Boolean,
      default: false
    },
    /** 子选项是否显示全部类型 */
    childShowAllCheck: {
      type: Boolean,
      default: true
    },
    value: {
      type: String,
      default: ''
    },
    options: {
      type: Array as PropType<any[]>,
      default: () => []
    },
    arrowType: {
      type: String as PropType<'default' | 'small'>,
      default: 'default'
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    placement: {
      type: String,
      default: 'bottom-start'
    },
    showPath: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:value', 'moreId'],
  setup(props, { emit }) {
    const state = reactive({
      popoverShow: false,
      selectParents: {}, // 选中的数据
      tempAudioPlayTypes: '',
      audioPlayTypes: '',
      tagActiveId: '' as any,
      tagActive: {} as any,
      childSelectId: null as any,
      x: 0,
      y: 0
    });
    const audioPlayTypeList = ref([] as any);

    const formatParentCurrentValue = (ids: any, list: any) => {
      for (const item of list) {
        if (ids.includes(item.id)) {
          if (item.children && item.children.length > 0) {
            let lastId: any;
            item.children.forEach((child: any) => {
              if (ids.includes(child.id)) {
                lastId = child.id;
              }
            });
            item.activeIndex = lastId;
          }
        }
        if (item.children && item.children.length > 0) {
          formatParentCurrentValue(ids, item.children);
        }
      }
    };

    const initParentSelect = (subject: any) => {
      let children: any;
      let columnName = '';
      if (subject.children) {
        children = [...subject.children];
        let activeIndex = subject.activeIndex
          ? subject.activeIndex
          : children.length > 0
          ? children[0].id
          : '';
        if (props.childShowAllCheck) {
          children.unshift({
            columnName: subject.children[0].columnName,
            name: '全部' + subject.children[0].columnName || '',
            id: ''
          });
          activeIndex = '';
        }
        columnName = subject.children[0].columnName;

        state.childSelectId = activeIndex;
        state.selectParents = {
          ...subject,
          columnName,
          activeIndex,
          children
        };
      } else {
        state.selectParents = {};
      }
    };

    watch(
      () => state.popoverShow,
      () => {
        if (!state.popoverShow || !props.value) return;
        let ids = formatParentId(props.value, props.options);

        const index = ids.findIndex((child: any) => child.id === props.value);
        ids = ids.slice(0, index + 1);
        const values = ids.map((item: any) => {
          return item.id;
        });
        // 格式化数据
        formatParentCurrentValue(values, props.options);

        // 初始化选中数据
        state.tagActiveId = ids[0].id;
        props.options.forEach((item: any) => {
          if (item.id === state.tagActiveId) {
            initParentSelect(item);
          }
        });
      }
    );

    const valueText = computed(() => {
      const id = props.value;
      const values = getValues(id);
      const names: any = [];
      audioPlayTypeList.value.forEach((item: any) => {
        if (item.id === state.tempAudioPlayTypes && props.showAudioPlayType) {
          names.push(item.name);
        }
      });
      if (state.tempAudioPlayTypes !== 'SING') {
        values.forEach((item: any) => {
          names.push(item.name);
        });
      }

      if (props.showPath) {
        return names.join(' / ');
      } else {
        const lastName = names[names.length - 1];
        // console.log(lastName, 'last names');
        return lastName;
      }
    });

    // 递归获取数据
    const formatParentId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.children && item.children.length > 0) {
          const cIds: any = formatParentId(id, item.children, [
            ...ids,
            {
              name: item.name,
              id: item.id
            }
          ]);
          const index = cIds.findIndex((c: any) => c.id === id);
          if (index > -1) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [
            ...ids,
            {
              name: item.name,
              id
            }
          ];
        }
      }
      return ids;
    };

    const getValues = (value: any) => {
      let ids = formatParentId(value, props.options);
      const index = ids.findIndex((child: any) => child.id === value);
      ids = ids.slice(0, index + 1);
      return ids;
    };

    // 重置
    const onReset = () => {
      // 重置默认选中第一个
      const firstChild = props.options[0];
      const children = firstChild.children ? firstChild.children[0] : null;
      // console.log(firstChild, '1111111');
      state.childSelectId = children?.value;
      state.tagActiveId = children?.value || firstChild.value || '';
      state.audioPlayTypes = '';
      state.tempAudioPlayTypes = '';
      state.selectParents = {};
      emit('update:value', children?.value || firstChild.value || '');

      emit('moreId', {
        childId: children?.value,
        parentId: firstChild.value,
        audioPlayTypes: ''
      });
      state.popoverShow = false;
    };

    // 提交
    const onConfirm = () => {
      if (state.audioPlayTypes !== 'SING') {
        emit('update:value', state.childSelectId || state.tagActiveId);
        emit('moreId', {
          childId: state.childSelectId,
          parentId: state.tagActiveId,
          audioPlayTypes: state.audioPlayTypes
        });
      } else {
        emit('update:value', '');
        emit('moreId', {
          childId: '',
          parentId: '',
          audioPlayTypes: state.audioPlayTypes
        });
        // state.tagActiveId = '';
        // state.childSelectId = null;
      }

      state.tempAudioPlayTypes = state.audioPlayTypes;
      state.popoverShow = false;
    };
    onMounted(() => {
      // 场景
      const tempAudio = Object.keys(audioPlayType).map(key => {
        return {
          id: key,
          name: audioPlayType[key]
        };
      });
      audioPlayTypeList.value = [{ name: '全部场景', id: '' }, ...tempAudio];
    });
    return () => (
      <NPopover
        placement={props.placement as any}
        v-model:show={state.popoverShow}
        showArrow={false}
        trigger="click"
        displayDirective="show"
        class={[styles.cascaderPopover, 'c-cascaderPopover']}>
        {{
          trigger: () => (
            <div
              class={[
                styles.nBaseCascaser,
                'nBaseCascaser',
                state.popoverShow ? styles.nBaseCascaserActive : ''
              ]}
              title={valueText.value}>
              <div
                class={[
                  styles['n-base-selection-tags'],
                  'n-base-selection-tags'
                ]}>
                <div class={styles['n-base-selection-input']}>
                  <div class={styles['n-base-selection-input__content']}>
                    {valueText.value}
                  </div>
                </div>

                <div class={[styles['n-base-suffix']]}>
                  <div
                    class={[
                      styles.arrow,
                      props.arrowType === 'small' ? styles.arrowSmall : ''
                    ]}>
                    {props.arrowType === 'default' && (
                      <img src={state.popoverShow ? arrowUp : arrowDown} />
                    )}
                    {props.arrowType === 'small' && (
                      <img
                        src={state.popoverShow ? arrowUpSmall : arrowDownSmall}
                      />
                    )}
                  </div>
                </div>
              </div>
              <div
                class={[
                  styles['n-base-selection-placeholder'],
                  styles['n-base-selection-overlay']
                ]}>
                {!valueText.value && (
                  <div class={styles.inner}>{props.placeholder}</div>
                )}
              </div>
              <div
                class={[
                  styles['n-base-selection__border'],
                  'n-base-selection__border'
                ]}></div>
              <div class={styles['n-base-selection__state-border']}></div>
            </div>
          ),
          default: () => (
            <div class={styles.baseContent}>
              <NScrollbar
                class={styles.baseScrollBar}
                style={{ maxHeight: '400px' }}>
                {props.showAudioPlayType && (
                  <>
                    <div class={styles.baseContentTitle}>场景</div>
                    <div class={styles.baseContentWrap}>
                      {audioPlayTypeList.value.map((subject: any) => (
                        <span
                          class={[
                            styles.tag,
                            (state.audioPlayTypes || '') == subject.id &&
                              styles.tagActive
                          ]}
                          onClick={() => {
                            if (state.audioPlayTypes !== subject.id) {
                              state.childSelectId = null;
                            }
                            state.audioPlayTypes = subject.id;
                          }}>
                          {subject.name}
                        </span>
                      ))}
                    </div>
                  </>
                )}

                {state.audioPlayTypes !== 'SING' && (
                  <>
                    <div class={styles.baseContentTitle}>
                      {props.options[0].columnName}
                    </div>
                    <div class={styles.baseContentWrap}>
                      {props.options.map((subject: any) => (
                        <span
                          class={[
                            styles.tag,
                            (state.tagActiveId || '') == subject.id &&
                              styles.tagActive
                          ]}
                          onClick={() => {
                            if (state.tagActiveId !== subject.id) {
                              state.childSelectId = null;
                            }
                            state.tagActiveId = subject.id;

                            initParentSelect(subject);
                          }}>
                          {subject.name}
                        </span>
                      ))}
                    </div>
                    <ChildNodeSearch
                      childShowAllCheck={props.childShowAllCheck}
                      activeRow={state.selectParents}
                      onSelectChildTag={(val: any) => {
                        state.childSelectId = val;
                      }}
                    />
                  </>
                )}
              </NScrollbar>
              <div class={styles.btnGroup}>
                <div class={[styles.btn, styles.btnCancel]} onClick={onReset}>
                  重置
                </div>
                <div
                  class={[styles.btn, styles.btnConfirm]}
                  onClick={onConfirm}>
                  确认
                </div>
              </div>
            </div>
          )
        }}
      </NPopover>
    );
  }
});

const ChildNodeSearch = defineComponent({
  name: 'ChildNodeSearch',
  props: {
    /** 子选项是否显示全部类型 */
    childShowAllCheck: {
      type: Boolean,
      default: true
    },
    activeRow: {
      type: Object,
      default: () => ({})
    },
    list: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['selectChildTag'],
  setup(props, { emit }) {
    const { activeRow } = toRefs(props);
    const selectItem = ref({});
    watch(
      () => props.activeRow,
      () => {
        activeRow.value = props.activeRow;
        initActiveRow();
      }
    );

    const initActiveRow = () => {
      if (activeRow.value.activeIndex) {
        const childList = activeRow.value.children || [];
        childList.forEach((subject: any) => {
          if (subject.id === activeRow.value.activeIndex) {
            let children: any;
            let columnName = '';
            if (subject.children) {
              children = [...subject.children];
              if (props.childShowAllCheck) {
                children.unshift({
                  columnName: subject.children[0].columnName,
                  name: '全部' + subject.children[0].columnName || '',
                  id: ''
                });
              }
              columnName = subject.children[0].columnName;

              selectItem.value = {
                ...subject,
                columnName,
                activeIndex: subject.activeIndex || '',
                children
              };
              emit('selectChildTag', subject.activeIndex || '');
            }
          }
        });
      } else {
        selectItem.value = {};
      }
    };

    onMounted(() => {
      initActiveRow();
    });
    return () => (
      <>
        {activeRow.value?.id && (
          <>
            <div class={styles.baseContentTitle}>
              {activeRow.value.columnName}
            </div>
            <div class={styles.baseContentWrap}>
              {activeRow.value?.children.map((subject: any) => (
                <span
                  class={[
                    styles.tag,
                    (activeRow.value.activeIndex || '') == subject.id &&
                      styles.tagActive
                  ]}
                  onClick={() => {
                    if (props.loading) return;
                    activeRow.value.activeIndex = subject.id;
                    let children: any;
                    let columnName = '';
                    if (subject.children) {
                      children = [...subject.children];
                      let activeIndex =
                        children.length > 0 ? children[0].id : '';
                      if (props.childShowAllCheck) {
                        children.unshift({
                          columnName: subject.children[0].columnName,
                          name: '全部' + subject.children[0].columnName || '',
                          id: ''
                        });
                        activeIndex = '';
                      }
                      columnName = subject.children[0].columnName;

                      selectItem.value = {
                        ...subject,
                        columnName,
                        activeIndex,
                        children
                      };
                    } else {
                      selectItem.value = {};
                    }
                    emit('selectChildTag', activeRow.value.activeIndex);
                  }}>
                  {subject.name}
                </span>
              ))}
            </div>

            <ChildNodeSearch
              activeRow={selectItem.value}
              onSelectChildTag={(item: any) => {
                emit('selectChildTag', item || activeRow.value.activeIndex);
              }}
            />
          </>
        )}
      </>
    );
  }
});
