import React, { useEffect, useState } from 'react';
import './index.scss';
import { pinyin } from 'pinyin-pro';
import { Select } from 'antd';

// 搜索列表的类型
interface searchColumns {
  type: 'Alphabet' | 'Brand' | 'Price' | 'Industry' | 'Product';
  options: { label: string; value: any; children?: { label: string; value: any }[] }[];
  name: string;
  label: string;
  subLabel?: string;
}

// 传参类型
interface propType {
  columns: searchColumns[];
  selected: boolean;
  region: boolean;
}

const BrandSelectItem: React.FC<{ label: string; children: any }> = (props) => {
  const { label, children } = props;

  return (
    <div className={'brand-select-item'}>
      <div className={'item-label'}>{label}</div>
      <div className={'item-content'}>{children}</div>
    </div>
  );
};

const BrandSelectSearch: React.FC<propType> = (props) => {
  const { columns, selected, region } = props;
  // 字母列表转换
  const [alphabetList, setAlphabetList] = useState<{ label?: string; children: any }[]>([]);
  // 字母列表索引
  const [alphabetIndex, setAlphabetIndex] = useState<number>(0);
  // 字母列表详情索引
  const [alphabetContentIndex, setAlphabetContentIndex] = useState<number>(0);
  // 普通筛选索引
  const [optionsIndex, setOptionsIndex] = useState<{ index: number; subIndex?: number }[]>([]);
  // 转换过后的普通筛选列表
  const [columnsList, setColumnsList] = useState<searchColumns[]>([]);

  // 获取字母列表 (将传入的列表转成以拼音开头的数组)
  const getAlphabetList = () => {
    // 如果没有字母列表则不执行
    if (!columns.some((i) => i.type === 'Alphabet')) return;
    // 获取字母列表
    const options = columns.find((i) => i.type === 'Alphabet')?.options;
    var _options;
    var temp = new Set(
      (_options = options) === null || _options === void 0
        ? void 0
        : _options.map(function (i) {
            var _pinyin, _pinyin$at, _pinyin$at$at;
            return (_pinyin = pinyin(i.label, {
              toneType: 'none',
              type: 'array',
            })) === null || _pinyin === void 0
              ? void 0
              : (_pinyin$at = _pinyin.at(0)) === null || _pinyin$at === void 0
              ? void 0
              : (_pinyin$at$at = _pinyin$at.at(0)) === null || _pinyin$at$at === void 0
              ? void 0
              : _pinyin$at$at.toUpperCase();
          }),
    );
    // 获取开头字母列表（去重）
    const arr = [
      ...new Set(
        options?.map((i) =>
          pinyin(i.label, { toneType: 'none', type: 'array' })?.at(0)?.at(0)?.toUpperCase(),
        ),
      ),
    ].sort();
    // 转换成展示列表
    setAlphabetList(
      arr?.map((i) => {
        const children =
          options?.filter(
            (j) =>
              pinyin(j.label, { toneType: 'none', type: 'array' })?.at(0)?.at(0)?.toUpperCase() ===
              i,
          ) || [];
        return {
          label: i,
          children: [{ label: '不限', value: 'all' }, ...children],
        };
      }),
    );
  };
  // 获取普通列表
  const getOptionsList = (options: { label: string; value: any }[]) => {
    return [{ label: '不限', value: 'all' }, ...options];
  };
  // componentDidMount
  useEffect(() => {
    if (!columns) return;
    getAlphabetList();
    // 初始化索引
    setOptionsIndex(columns.map((i) => (i.subLabel ? { index: 0, subIndex: 0 } : { index: 0 })));
    // 初始化列表
    setColumnsList(columns?.map((i) => ({ ...i, options: getOptionsList(i.options) })));
  }, [columns]);
  // componentDidUpdate
  useEffect(() => {
    // 如果没有普通筛选列表则不执行
    if (!optionsIndex.length) return;
    // 如果普通筛选列表全为0则不执行
    if (!optionsIndex.some((i) => i.index !== 0)) return;
    console.log('optionsIndex --->', optionsIndex);
    console.log(
      'componentDidUpdate -->',
      optionsIndex.map((i, j) => columnsList[j].options[i.index]),
    );
  }, [optionsIndex]);

  return (
    <div className={'brand-select-search-view'}>
      {region && (
        <BrandSelectItem label={'地区'}>
          <div className={'select-region'}>
            <span className={'region-label'}>省</span>
            <Select placeholder={'请选择省份'} options={[]} size={'small'} />
            <span className={'region-label'}>市</span>
            <Select placeholder={'请选择城市'} options={[]} size={'small'} />
          </div>
        </BrandSelectItem>
      )}
      {columnsList.map((i, j) => {
        if (i.type === 'Alphabet') {
          return (
            <BrandSelectItem label={'品牌'} key={j}>
              <div className='alphabet-list'>
                {alphabetList.map((n, m) => (
                  <div
                    className={`list-item ${alphabetIndex === m && 'item-active'}`}
                    key={m}
                    onClick={() => {
                      setAlphabetIndex(m);
                      setAlphabetContentIndex(0);
                    }}
                  >
                    {n.label}
                  </div>
                ))}
              </div>
              <div className='alphabet-content'>
                {alphabetList[alphabetIndex]?.children?.map((n: any, m: number) => (
                  <div
                    className={`content-item ${alphabetContentIndex === m && 'item-active'}`}
                    key={m}
                    onClick={() => {
                      setAlphabetContentIndex(alphabetContentIndex === m ? 0 : m);
                      const index =
                        columnsList
                          .find((i) => i.type === 'Alphabet')
                          ?.options?.findIndex((i) => i.label === n.label) || 0;
                      // setOptionsIndex(optionsIndex?.map((i, k) => (k === j ? index : i)));
                      setOptionsIndex(optionsIndex?.map((i, k) => (k === j ? { index } : i)));
                    }}
                  >
                    {n.label}
                  </div>
                ))}
              </div>
            </BrandSelectItem>
          );
        }
        if (['Industry', 'Brand', 'Price', 'Product'].includes(i.type)) {
          return (
            <div key={j}>
              <BrandSelectItem label={i.label}>
                <div className='select-list'>
                  {i.options?.map((n, m) => (
                    <div
                      className={`list-item ${optionsIndex[j].index === m && 'item-active'}`}
                      key={m}
                      onClick={() => {
                        setOptionsIndex(
                          optionsIndex.map((l, k) =>
                            k === j
                              ? optionsIndex[j].index === m
                                ? i.subLabel
                                  ? { index: 0, subIndex: 0 }
                                  : { index: 0 }
                                : i.subLabel
                                ? { index: m, subIndex: 0 }
                                : { index: m }
                              : l,
                          ),
                        );
                      }}
                    >
                      {n.label}
                    </div>
                  ))}
                </div>
              </BrandSelectItem>
              {!!i.subLabel && (
                <BrandSelectItem label={i.subLabel}>
                  <div className='select-list'>
                    {getOptionsList(i.options[optionsIndex[j].index]?.children || [])?.map(
                      (n, m) => (
                        <div
                          className={`list-item ${optionsIndex[j].subIndex === m && 'item-active'}`}
                          key={m}
                          onClick={() => {
                            setOptionsIndex(
                              optionsIndex.map((i, k) =>
                                k === j ? { ...i, subIndex: m === i.subIndex ? 0 : m } : i,
                              ),
                            );
                          }}
                        >
                          {n.label}
                        </div>
                      ),
                    )}
                  </div>
                </BrandSelectItem>
              )}
            </div>
          );
        }
      })}
      {selected && (
        <BrandSelectItem label={'已选'}>
          <div className='select-list selected'>
            {optionsIndex.map(
              (n, m) =>
                columnsList[m].options[n.index].label !== '不限' && (
                  <div
                    className={`list-item`}
                    key={m}
                    onClick={() => {
                      // setOptionsIndex(
                      //   optionsIndex.map((i, k) => (k === j ? (optionsIndex[j] === m ? 0 : m) : i)),
                      // );
                    }}
                  >
                    {columnsList[m].options[n.index].label}
                  </div>
                ),
            )}
          </div>
        </BrandSelectItem>
      )}
    </div>
  );
};

export default BrandSelectSearch;
