import React from 'react';
import { View, ScrollView } from '@tarojs/components';
import { Button, Popup, Search, Cell, Icon } from '@antmjs/vantui';
import VABC from '@/components/VABC';

const wrapperStyle = {
  width: '90vw',
  height: '100vh',
  paddingBottom: 'env(safe-area-inset-bottom)',
}

export default (props) => {
  const { show, value, params = {}, keyValue, labelValue = 'name', dictAPI, onChange, onCancel } = props;

  const [dict, setDict] = React.useState([]);
  const [checked, setChecked] = React.useState();
  const [searchText, setSearchText] = React.useState('')
  const onSearch = () => {
    // todo
  }

  const list = React.useMemo(() => {
    if (!searchText) return dict;
    return dict.filter(x => x.name.indexOf(searchText) > -1);
  }, [searchText, dict]);

  const onClick = () => {
    if (!checked) return;
    onChange(checked[keyValue], checked)
  }

  React.useEffect(() => {
    dictAPI({pageSize: 500, ...params }).then(res => {
      setDict(res.records || []);
    })
  }, []);

  React.useEffect(() => {
    if (value && dict) {
      setChecked(dict.filter(x => x[keyValue] == value)[0]);
    }
  }, [value, dict]);
  
  return (
    <Popup position="right" show={show} onClose={onCancel}>
      <VABC
        header={(
          <Search
            onChange={(e) => setSearchText(e.detail)}
            placeholder="请输入搜索关键词"
            onSearch={onSearch}
            clearable
          />
        )}
        footer={(
          <View style={{ padding: '8px 2em' }}>
            <Button block type="primary" disabled={!checked} onClick={onClick}>确定</Button>
          </View>
        )}
        style={wrapperStyle}
      >
          <ScrollView scrollY style={{ height: '100%' }}>
            {
              list.map(item => (
                <Cell
                  key={item[keyValue]}
                  title={item[labelValue]}
                  renderRightIcon={
                    checked && checked[keyValue] == item[keyValue] ?
                    <Icon name="success" color="#1A7565" /> :
                    null
                  }
                  onClick={() => setChecked(item)}
                />
              ))
            }
          </ScrollView>
      </VABC>
    </Popup>
  )
}
