import { spread, insert, createComponent, effect, className, style, delegateEvents, template } from 'solid-js/web';
import { For, createMemo } from 'solid-js';
import { OriginComponent, AtomToArray, atomization, extendsEvent, reflect } from '@cn-ui/use';
import { areaList } from '@vant/area-data';

const _tmpl$ = /*#__PURE__*/template(`<div></div>`, 2),
      _tmpl$2 = /*#__PURE__*/template(`<div class="scroll-box-none flex flex-1 flex-col overflow-x-auto  "></div>`, 2),
      _tmpl$3 = /*#__PURE__*/template(`<div class="cursor-pointer text-ellipsis whitespace-nowrap rounded-md p-2 text-center transition-colors duration-300"></div>`, 2);
const Cascader = OriginComponent(props => {
  const options = AtomToArray(atomization(props.options));
  const value = atomization(props.value);
  return (() => {
    const _el$ = _tmpl$.cloneNode(true);

    const _ref$ = props.ref;
    typeof _ref$ === "function" ? _ref$(_el$) : props.ref = _el$;

    spread(_el$, () => extendsEvent(props), false, true);

    insert(_el$, createComponent(For, {
      each: options,
      children: (subArray, index) => {
        return (() => {
          const _el$2 = _tmpl$2.cloneNode(true);

          insert(_el$2, createComponent(For, {
            get each() {
              return subArray();
            },

            children: item => {
              const isSelect = createMemo(() => item === value()[index()]);
              return (() => {
                const _el$3 = _tmpl$3.cloneNode(true);

                _el$3.$$click = () => {
                  value(i => {
                    const newArray = [...i];
                    newArray.splice(index(), newArray.length - index(), item);
                    return newArray;
                  });
                };

                insert(_el$3, item);

                effect(_p$ => {
                  const _v$3 = !!isSelect(),
                        _v$4 = !!isSelect();

                  _v$3 !== _p$._v$3 && _el$3.classList.toggle("bg-slate-50", _p$._v$3 = _v$3);
                  _v$4 !== _p$._v$4 && _el$3.classList.toggle("text-blue-600", _p$._v$4 = _v$4);
                  return _p$;
                }, {
                  _v$3: undefined,
                  _v$4: undefined
                });

                return _el$3;
              })();
            }
          }));

          return _el$2;
        })();
      }
    }));

    effect(_p$ => {
      const _v$ = props.class('flex max-h-64 font-thin text-slate-700'),
            _v$2 = props.style;

      _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
      _p$._v$2 = style(_el$, _v$2, _p$._v$2);
      return _p$;
    }, {
      _v$: undefined,
      _v$2: undefined
    });

    return _el$;
  })();
});

delegateEvents(["click"]);

const findCodeByName = (name, obj) => {
  if (!name) return null;

  for (let [key, val] of Object.entries(obj)) {
    if (val === name) return key;
  }

  return null;
};

const countyEntry = Object.entries(areaList.county_list);
/** @zh 搜索中国省市区域 */

const searchChinaArea = () => {
  /** 因为地区不长，没有必要进行 fuse.js 加载 */
  return searchText => {
    return countyEntry.filter(([code, name]) => {
      return name.startsWith(searchText);
    });
  };
};
/**
 * @zh 中国地区的数据查询，配合 Cascader 使用
 */

const useChinaArea = value => {
  const provinceList = Object.values(areaList.province_list);
  const options = reflect(() => {
    const [province, city] = value();
    const provinceCode = (findCodeByName(province, areaList.province_list) || '110101').slice(0, 2);
    const cityList = Object.entries(areaList.city_list).filter(i => i[0].startsWith(provinceCode)).map(i => i[1]);
    const cityCode = (findCodeByName(city, areaList.city_list) || provinceCode + '0101').slice(0, 4);
    const countyList = countyEntry.filter(i => i[0].startsWith(cityCode)).map(i => i[1]); // console.log(cityList);

    return [provinceList, cityList, countyList];
  });
  return {
    options,

    getCode() {
      return findCodeByName(value()[2], areaList.county_list);
    },

    changeToCode(code) {
      const province = code.slice(0, 2) + '0000';
      const city = code.slice(0, 4) + '00';
      return [areaList.province_list[province], areaList.city_list[city], areaList.county_list[code]];
    }

  };
};

export { Cascader, searchChinaArea, useChinaArea };
