import 'default-passive-events';
import React, { useEffect, useState } from 'react'
import { View } from '@tarojs/components'
import AtIndexes from './indexes';
import { Checkbox, Popup, Radio } from 'tea-component-mobile'
// import { Popup, Button, InputNumber } from "tea-component-mobile";
import { isString, isPlainObject, intersection, uniq } from 'lodash-es';
import './main.less'
import back from '../../assets/images/icon/back.svg';

interface IProps {
  selectedAllTexts: string[];
  onChange: Function;
  value: any[];
  selectable: boolean; // 是否支持选择
  list: any[];
  empty: string | React.ReactNode;
  positionCheckBox: string;
  isPopup: Boolean; // 是否弹窗
  popupHeight: Number;//popup的高度
  onClosePopup: Function;//popup关闭时候的回调
  maskClosable: boolean;//遮罩层是否可以点击关闭
  isSingleSelect: boolean;
  visible: boolean;
  popupTitle: string; // popup标题
  children?: any;
}
// const stateFlag = {
//     'all':1,
//     'empty': 2,
//     'part': 3
// }

export default (props: IProps) => {
  const {
    selectedAllTexts = ['Selecte All', 'Clear All'],
    positionCheckBox = 'left',
    isPopup = false,
    popupHeight = 500,
    onClosePopup = (selecteds) => {
      console.log('关闭pop的回调', selecteds)
    },
    onChange = (selecteds, isSelectAll) => {
      console.log(selecteds, isSelectAll, '-----')
    },
    isSingleSelect = false,
    maskClosable = false,
    popupTitle = '自定义标题'
  } = props;

  const [selectedAll, setSelectedAll] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [allValues, setAllValues] = useState([]);
  const [selecteds, setSelecteds] = useState(props.value || []);
  const [stateSelectFlag, setStateSelectFlag] = useState('empty')
  const [detailKey, setDetailKey] = useState(Math.random());
  const [domId] = useState(`popupPicker-${Math.random().toString()}`.replace(/\./, ''));
  // const [statePopup,setStatePopup] = useState(isPopup)
  useEffect(() => {
    // 处理数据
    const {
      list = [],
    } = props;
    if (!list.length) {
      setData([]);
    }
    // ['a', 'b' ...] 列表格式，然后自动筛选字母
    const [one] = list;
    if (isString(one)) {
      return processStringList(list);
    }
    // [{ label: 'a', value: 'A', abbr: 'A' }, { label: 'xds', value: 'X', abbr: 'X' }]
    if (isPlainObject(one) && one.abbr) {
      return processPlatinObject(list as any);
    }
    setData([]);
  }, [props.value, props.list])
  useEffect(() => {
    setDetailKey(Math.random())   
  }, [props.visible])

  useEffect(() => {
    setSelecteds(!isSingleSelect ? props.value || [] : props.value.slice(0, 1) || []);
    setSelectedAll(checkSelectedAll());
  }, [props.value]);
  useEffect(() => {
    if (allValues.length == selecteds.length) {
      setStateSelectFlag('all')
    } else if (selecteds.length === 0) {
      setStateSelectFlag('empty')
    } else {
      setStateSelectFlag('part')
    }
  }, [allValues, selecteds, isSingleSelect])
  useEffect(() => {
    // TODO: 这段代码没有执行
    if (isPopup) {
      const popupPicker = document.querySelectorAll(`.${domId} .tea-popup__container`)
      if (popupPicker[0]) {
        (popupPicker[0] as any).style.height = `${popupHeight}px`
      }
    }
    setDetailKey(Math.random());
  }, [isPopup, props.selectable])
  function checkSelectedAll(list?: any) {
    // debugger
    list = list || selecteds;
    return list.length === allValues.length && intersection(list, allValues).length === selecteds.length;
  }
  // ['a', 'b' ...] 列表格式，然后自动筛选字母
  function processStringList(list: string[] = []) {
    const map = list.reduce((obj, v) => {
      const abbr = v.slice(0, 1).toUpperCase();
      if (!obj[abbr]) {
        obj[abbr] = [];
      }
      obj[abbr].push(v);
      return obj;
    }, {})
    const data = Object.keys(map).sort().map((abbr) => {
      return {
        title: abbr,
        key: abbr,
        items: map[abbr].sort().map((name) => {
          return {
            name,
            label: name,
            value: name,
          };
        })
      }
    });
    setData(data);
    setAllValues(uniq(list));
  }
  // [{ label: 'a', value: 'A', abbr: 'A' }, { label: 'xds', value: 'X', abbr: 'X' }]
  function processPlatinObject(list = []) {
    const map = list.reduce((obj, v) => {
      const abbr: string = { v } as any;
      if (!obj[abbr]) {
        obj[abbr] = [];
      }
      obj[abbr].push(v);
      return obj;
    }, {})
    const data = Object.keys(map).sort().map((abbr) => {
      return {
        title: abbr,
        key: abbr,
        items: map[abbr].sort((a, b) => a.label - b.label),
      }
    });
    setData(data);
    setAllValues(uniq(
      list.map((v: any) => v.value),
    ))
  }


  function renderSelectAll(close) {
    // if (!props.selectable || !props.allowSelectAll) {
    //   return <View></View>;
    // }
    if (!props.selectable) {
      return <View></View>;
    }
    const backClose = <View className='backCLose' onClick={() => {
      onClosePopup(selecteds)
      close()
    }}>{isPopup ? <View className='popTitle'> <img src={back} /><View className='titleName'>{popupTitle}</View></View> : null}</View>
    return (
      <View className="select-all">
        {  isSingleSelect ? backClose :
          <View>
            {backClose}
            <View className="select-all-text">
              <Radio className={stateSelectFlag} onChange={() => {
                // setPositionCheckBoxPop(!positionCheckBoxPop)
                onToggleSelectAll()
              }}> {true ? selectedAllTexts[0] : ''}</Radio>
              {/* {true ? selectedAllTexts[0] : ''} */}
              {/* {
                `勾选状态${stateSelectFlag}`
              } */}
            </View>
          </View>
        }
      </View>
    )
  }

  function renderDetail() {
    const dataArr = [...data]
    const atList = props.selectable
      ? dataArr.map((v: any) => {
        const vObj: any = {}
        vObj.key = v.key
        vObj.title = v.title
        vObj.items = (v.items || []).map((v) => {
          return {
            ...v,
            name: (
              <View className="index-item">
                <Checkbox name={v.value} className={`${positionCheckBox == 'left' ? 'checkBoxItemLeft' : 'checkBoxItemRight'}`}>
                  <View className="index-item-label">{v.label}</View>
                </Checkbox>
              </View>
            )
          };
        });
        return vObj;
      })
      : dataArr;
    const partDetail = (
      <AtIndexes
        key={detailKey}
        list={atList}
        animation={true}
        isVibrate={true}
        onScrollIntoView={onScrollIntoView}>
      </AtIndexes>
    );
    return (
      props.selectable
        ? (
          <Checkbox.Group value={selecteds} onChange={onChangeCheckBox}>
            {partDetail}
          </Checkbox.Group >
        )
        : partDetail

    )
  }

  function onScrollIntoView(key) {
    console.log(key, 'onScrollIntoView')
  }

  function onChangeCheckBox(value) {
    const data = !isSingleSelect ? value || [] : [value[value.length - 1]] || []
    // debugger
    setSelecteds(data)
    setSelectedAll(checkSelectedAll());
    // debugger
    onChange(data, data.length == allValues.length)
  }

  function onToggleSelectAll() {
    if (allValues.length === selecteds.length) {
      setSelecteds([]);
      onChange([], !selectedAll)
    } else {
      setSelecteds(allValues);
      onChange(allValues, !selectedAll)
    }
    setSelectedAll(!selectedAll);
  }

  const renderPartDetail = (close?: Function) => {
    return (
      <View className="taro-scroll-picker" key={detailKey}>
        {
          props.selectable
            ? renderSelectAll(close)
            : <View></View>
        }
        {renderDetail()}
      </View>
    )
  }
  // debugger
  return (
    !isPopup
      ? renderPartDetail()
      : <Popup
        className={`popupPicker ${domId}`}
        defaultVisible={false}
        overlay={close => {
          return renderPartDetail(close);
        }}
        mask={true}
        maskClosable={maskClosable}
        onClose={() => {
          onClosePopup(selecteds)
        }}
      >
        {props.children}
      </Popup>

  )
}