import React from 'react';
import { usePlatform } from '../../../utils/platform';
import FormCell from '../formcell';
import SelectH5, { decodeIsoDatetime } from './h5';
import classNames from '../../../utils/classnames';
import * as PropTypes from 'prop-types';
import {
  Select as TeaSelect,
  DatePicker,
  TimePicker,
  Cascader,
  ConfigProvider,
} from 'tea-component';
import moment from 'moment';
import isObjectEqual from '../../../utils/isObjectEqual';
import { getRegionTree } from './region';

export default function Select(props) {
  const platform = usePlatform();

  if (platform === 'h5') {
    return <SelectH5 {...props} />;
  }

  return (
    <ConfigProvider classPrefix="wedatea2td">
      <SelectPc {...props} />
    </ConfigProvider>
  );
}

function SelectPc({
  id,
  style,
  className,
  defaultValue,
  placeholder,
  label,
  labelVisible,
  mode,
  events,
  layout,
  disabled,
  requiredFlag,
  range,
  startDate,
  endDate,
  defaultDate,
  defaultTime,
  startTime,
  endTime,
  defaultRegion,
  separator,
  size,
}) {
  const cls = classNames({
    'weda-ui': true,
    'weda-select': true,
    [className]: className,
  });
  // 两次默认值不同, 需要刷新
  const prevDefaultRef = React.useRef();
  const [date, setDate] = React.useState(
    decodeIsoDatetime(defaultDate, 'date')
  );
  const [time, setTime] = React.useState(
    decodeIsoDatetime(defaultTime, 'time')
  );
  const [region, setRegion] = React.useState(defaultRegion || undefined);
  const [selectedValue, setSelectedValue] = React.useState(defaultValue);

  React.useEffect(() => {
    let hasChange = false;
    if (prevDefaultRef.current?.defaultValue !== defaultValue) {
      setSelectedValue(defaultValue);
      hasChange = true;
    }
    if (prevDefaultRef.current?.defaultDate !== defaultDate) {
      setDate(decodeIsoDatetime(defaultDate, 'date'));
      hasChange = true;
    }
    if (prevDefaultRef.current?.defaultTime !== defaultTime) {
      const ts = decodeIsoDatetime(defaultTime, 'time');
      setTime(ts);
      hasChange = true;
    }
    if (!isObjectEqual(prevDefaultRef.current?.defaultRegion, defaultRegion)) {
      setRegion(defaultRegion ?? []);
      hasChange = true;
    }
    if (hasChange) {
      prevDefaultRef.current = {
        defaultDate,
        defaultTime,
        defaultRegion,
      };
    }
  });
  const onDataChange = (value) => {
    let finalVal;
    if (mode === 'date') {
      finalVal = value.valueOf();
    } else if (mode === 'time') {
      finalVal = (value.hour() * 60 * 60 + value.minute() * 60) * 1000;
    } else if (mode === 'region') {
      finalVal = value ?? [];
    } else {
      finalVal = value;
    }
    events.change({ value: finalVal });
  };
  const createDropdown = () => {
    switch (mode) {
      case 'selector':
        return (
          <TeaSelect
            size={size}
            onChange={onDataChange}
            disabled={disabled}
            defaultValue={selectedValue}
            type="simulate"
            appearance="button"
            placeholder={placeholder}
            options={range.map((i) => ({ text: i.label, value: i.value }))}
          />
        );
      case 'date': {
        const now = moment();
        const start = startDate
          ? decodeIsoDatetime(startDate, 'date')
          : `${now.year() - 20}-01-01`;
        const end = endDate
          ? decodeIsoDatetime(endDate, 'date')
          : `${now.year() + 20}-12-31`;
        return (
          <DatePicker
            range={[moment(start), moment(end)]}
            onChange={onDataChange}
            disabled={disabled}
            placeholder={placeholder}
            value={date ? moment(date) : undefined}
          />
        );
      }
      case 'time': {
        const start = startTime
          ? decodeIsoDatetime(startTime, 'time')
          : '00:00';
        const end = endTime ? decodeIsoDatetime(endTime, 'time') : '23:59';
        const now = moment();
        return (
          <TimePicker
            onChange={onDataChange}
            disabled={disabled}
            placeholder={placeholder}
            value={time ? moment(time, 'HH:mm') : undefined}
            range={[moment(start, 'HH:mm'), moment(end, 'HH:mm')]}
            format="HH:mm"
          />
        );
      }
      case 'region':
        return (
          <Cascader
            clearable
            searchable
            type="menu"
            disabled={disabled}
            data={getRegionTree()}
            multiple={false}
            onChange={onDataChange}
            valueRender={(options) =>
              options.map(({ label, value }, index) => (
                <React.Fragment key={`${value}-${index}`}>
                  {index !== 0 && `${separator}`}
                  {label || value}
                </React.Fragment>
              ))
            }
            value={region}
          />
        );
    }
  };
  const dropdown = createDropdown();
  return (
    <FormCell
      size={size}
      id={id}
      className={cls}
      style={style}
      label={labelVisible ? label : null}
      layout={layout}
      multiCell={false}
      requiredFlag={requiredFlag}
    >
      {dropdown}
    </FormCell>
  );
}
