import React, { useEffect, useState, useCallback } from 'react';
import clsx from 'clsx';
import moment from 'moment';
import { EditOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Input,
  Radio,
  Spin,
  Select,
  DatePicker,
  TreeSelect,
  Cascader,
  Upload,
  Button,
} from 'antd';
import { getDeepValue, isChildOf  } from '@/utils'
import SearchPeople from './components/searchPeople'
import Editor from './components/editor'
import EditTable from '../editTable'
import _ from "lodash";
import styles from './style.module.less'
const { TextArea } = Input
const { Option } = Select
const { RangePicker } = DatePicker
const dateFormat = 'YYYY-MM-DD HH:mm:ss'
export default function SearchInput(props) {
  const [edit, setEdit] = useState(false)
  //viewInEdit 为false 控制外层是否改调用的update
  const { viewInEdit, viewInEditChange, renderFormData, valueData = {}, fetching = false, onChange } = props

  function getInput() {
    const value = getDeepValue(renderFormData.key, valueData, viewInEditChange && (renderFormData.childrenRouteInput ? renderFormData.childrenRouteInput : ''))
    switch(renderFormData.type) {
      case 'radio':
        return (
          <Radio.Group
            value={value}
            disabled={renderFormData.disabled}
            onChange={(e) => onChange(renderFormData.key, e.target.value)}
          >
            {
              renderFormData.options.map(t => (
              <Radio value={t.key} key={t.key}>{t.label}</Radio>
              ))
            }
          </Radio.Group>
        )
      case 'radioReturnObj':
        return (
          <Radio.Group
            value={value && `${value.key}%${value.label}`}
            disabled={renderFormData.disabled}
            onChange={
              (e) => onChange(
                renderFormData.key,
                { key: e.target.value.split('%')[0], label: e.target.value.split('%')[1]}
              )
            }
          >
            {
              renderFormData.options.map(t => (
              <Radio value={`${t.key}%${t.label}`} key={`${t.key}%${t.label}`}>{t.label}</Radio>
              ))
            }
          </Radio.Group>
        )
      case 'textarea':
        return (
          <TextArea
            maxLength={300}
            allowClear
            autoSize={renderFormData.autoSize}
            disabled={renderFormData.disabled}
            placeholder={renderFormData.placeholder}
            value={getDeepValue(renderFormData.key, valueData)}
            onChange={(e) => onChange(renderFormData.key, e.target.value)}
          />
        )
      case 'select':
        return (
          <Select
            mode={renderFormData.multiple && 'multiple'}
            showSearch
            optionFilterProp="children"
            allowClear={renderFormData.allowClear}
            placeholder={renderFormData.placeholder}
            notFoundContent={fetching ? <Spin size="small" /> : null}
            style={{ width: '100%' }}
            dropdownMatchSelectWidth={false}
            disabled={renderFormData.disabled}
            value={value}
            onChange={(e) => onChange(renderFormData.key, e)}
          >
            {renderFormData.options.map(d => (
              <Option key={d.key}>{(renderFormData.optionRender && renderFormData.optionRender(d)) || d.label}</Option>
            ))}
          </Select>
        )
      case 'selectReturnObj':
        return (
          <Select
            mode={renderFormData.multiple && 'multiple'}
            showSearch
            labelInValue
            optionFilterProp="children"
            dropdownMatchSelectWidth={false}
            allowClear={renderFormData.allowClear}
            placeholder={renderFormData.placeholder}
            notFoundContent={fetching ? <Spin size="small" /> : null}
            style={{ width: '100%' }}
            disabled={renderFormData.disabled}
            value={value || (renderFormData.multiple ? [] : undefined)}
            onChange={(e) => onChange(renderFormData.key, e)}
          >
            {renderFormData.options.map(d => (
              <Option key={d.key}>{(renderFormData.optionRender && renderFormData.optionRender(d)) || d.label}</Option>
            ))}
          </Select>
        )
      case 'selectAtWill':
        return (
          <Select
            mode="tags"
            style={{ width: '100%' }}
            labelInValue={renderFormData.labelInValue}
            placeholder={renderFormData.placeholder}
            dropdownMatchSelectWidth={false}
            value={
              renderFormData.multiple
              ?
              value || []
              :
              value ? [value] : []
            }
            onChange={(e) => selectAtWillChangeValue(renderFormData.key, e, renderFormData.multiple)}
          >
            {renderFormData.options.map(d => (
              <Option key={d.key}>{d.label}</Option>
            ))}
          </Select>
        )
      case 'searchPeople':
        return (
          <SearchPeople
            renderFormData={renderFormData}
            value={getDeepValue(renderFormData.key, valueData)}
            onChange={(e) => onChange(renderFormData.key, e)}
          />
        )
      case 'editor':
        return (
          <Editor
            keys={renderFormData.key}
            defaultContent={value}
            height={renderFormData.height}
            onChange={(e) => onChange(renderFormData.key, e)}
            // disabled={}
          />
        )
      case 'table':
        return (
          <EditTable
            renderFormData={renderFormData}
            value={value}
            onChange={(key, value) => onChange(key, value)}
          />
        )
      case 'time':
        const dataList = getDeepValue(renderFormData.key, valueData)
        return (
          <RangePicker
            value={dataList && dataList[0] && [moment(dataList[0], renderFormData.dateFormat || dateFormat), moment(dataList[1], renderFormData.dateFormat || dateFormat)]}
            disabled={renderFormData.disabled}
            style={{ width: '100%' }}
            format={renderFormData.dateFormat || dateFormat}
            onChange={(dates, dateStrings) => {
              if(!dateStrings[0]) {
                onChange(renderFormData.key, [])
              }
              onChange(renderFormData.key, dateStrings)
            }}
          />
        )
      case 'uploadFile':
        return (
          // <input type="file" id="file" onChange = {(e) => console.log(e)}></input>
          <Upload
            action={renderFormData.action}
            fileList={value}
            onChange = {({ file, fileList }) => onChange(renderFormData.key, fileList)}
          >
            <Button>
              <UploadOutlined /> Upload
            </Button>
          </Upload>
        );
      case 'tree':
        return (
          <TreeSelect
            showSearch
            allowClear={renderFormData.allowClear}
            style={{ width: '100%' }}
            value={value}
            treeNodeFilterProp={'title'}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={renderFormData.treeData || renderFormData.options}
            placeholder={renderFormData.placeholder}
            treeDefaultExpandAll={renderFormData.treeDefaultExpandAll}
            onChange={(value) => onChange(renderFormData.key, value)}
          />
        )
      case 'cascader':
        return (
          <Cascader
            showSearch
            style={{ width: '100%' }}
            value={value}
            disabled={renderFormData.disabled}
            options={renderFormData.options}
            onChange={(value) => onChange(renderFormData.key, value)}
          />
        )
      default:
        return (
          <Input
            allowClear
            maxLength={renderFormData.maxLength}
            placeholder={renderFormData.placeholder}
            value={getDeepValue(renderFormData.key, valueData)}
            disabled={renderFormData.disabled}
            onChange={(e) => onChange(renderFormData.key, e.target.value)}
          />
        )
    }
  }

  function selectAtWillChangeValue(key, value, multiple) {
    let val = value
    // 不是多选
    if(!multiple) {
      // 如果有一个以上就取第二个 字符串
      if (val.length > 1) {
        val = value[1]
      } else {
        val = value[0]
      }
    }
    onChange(key, val)
  }

  function onEditChange(e) {
    e.stopPropagation()
    // callback()
    // 先更新外层是打开编辑状态
    // 在更新内层为编辑状态
    setEdit(true)
    viewInEditChange(true)
  }
  function getText() {
    return (
      <div>
        {renderFormData.textInputRender
        ?
        renderFormData.textInputRender(valueData, onChange)
        :
        <span className={styles.text}>
          {
            <div
              style={{ display: 'inline-block' }}
              dangerouslySetInnerHTML={{
                __html: getDeepValue(renderFormData.nameKey || renderFormData.key, valueData, renderFormData.childrenRoute || '')
              }}
            />
          }
        </span>
        }
      </div>
    )
  }

 // 接收外层是否更改编辑状态，更新完成会更改状态
  useEffect(() => {
    // 如果外层为关闭编辑状态 内层为开启编辑状态，则更新为关闭
    if (edit && !viewInEdit) {
      setEdit(false)
    }
  },[viewInEdit])
  return (
    //  onClick={(e) => e.stopPropagation()}
    <div className={styles.searchInput} style={renderFormData.searchInputStyles || {}} onClick={(e) => renderFormData.layout === 'vertical' && onEditChange(e)}>
      {/* 传递onchange方法 并且不是编辑状态 */}
      { ((viewInEditChange && !edit) || renderFormData.onlyText) ? (
          // textInput为true可以编辑
          //
          renderFormData.textInput ? (
          <div style={{ cursor: 'pointer' }}>
            {renderFormData.textInputRender
              ?
              <>
                {renderFormData.textInputRender(valueData, onChange)
                ||
                <span className={styles.empty}>请填写</span>}
              </>
              :
              <span className={clsx(styles.inputText, styles.text)}>
                {
                  getDeepValue(renderFormData.nameKey || renderFormData.key, valueData, renderFormData.childrenRoute || '') ? 
                  <div
                    style={{ display: 'inline-block' }}
                    dangerouslySetInnerHTML={{
                      __html: getDeepValue(renderFormData.nameKey || renderFormData.key, valueData, renderFormData.childrenRoute || '')
                    }}
                  />
                  :
                  <span className={styles.empty}>请填写</span>
                }
              </span>
            }
            {renderFormData.layout !== 'vertical' && 
              <EditOutlined
                id={`${renderFormData.key}Icon`}
                className={styles.icon}
                onClick={(e) => onEditChange(e)} />
            }
          </div>
          )
          :
          (
            getText()
          )
        ) : (
          <div onClick={(e) => e.stopPropagation()} className="flex-center-end">
            <div style={{ flex: 1, width: '100px' }}>
              {renderFormData.inputRender ? renderFormData.inputRender(valueData, onChange) : getInput()}
            </div>
            {renderFormData.unit && <div style={{ marginLeft: '5px', minWidth: '22px', textAlign: 'right' }}>{renderFormData.unit}</div>}
          </div>
        )
      }
    </div>
  );
}
