import React, { useState, useImperativeHandle, forwardRef, useMemo } from 'react';
import { Modal, Divider, Checkbox, Radio } from 'antd';
import DragTable from '@/components/DragTable/DragTable';
import classnames from 'classnames';
import styles from './index.less';

const SelectField = (props, ref) => {

  useImperativeHandle(ref, () => ({
    open
  }))

  const { filed, filedArray } = props

  const [visible, setVisible] = useState(false)
  const [checkedList, setCheckedList] = useState([]); // 选中复选框内容
  const [selectData, setSelectData] = useState([]);
  const [attr, setAttr] = useState('')

  const columns = useMemo(() => {
    if (attr === 'OrderByFieldConfig') {
      return [
        {
          title: '已选字段',
          dataIndex: 'name',
          key: 'name',
          width: 150,
        },
        {
          title: '正序/倒序',
          dataIndex: 'value',
          key: 'value',
          width: 150,
          render: (t, x) => {
            return (
              <Checkbox.Group
                onChange={(value) => {
                  radioChange({ row: x, value: value })
                }}
                value={[t]}
              >
                <Checkbox value={'asc'}>正序</Checkbox >
                <Checkbox value={'desc'}>倒序</Checkbox >
              </Checkbox.Group>
            )
          }
        }
      ]
    }
    if (attr === 'SearchFields') {
      return [
        {
          title: '已选字段',
          dataIndex: 'name',
          key: 'name',
          width: 150,
        },
        {
          title: '形态配置',
          dataIndex: 'widget',
          width: 150,
          key: 'widget',
          render: (t, x) => {
            const style = { width: '100px', height: '28px', lineHeight: '28px', textAlign: 'center' }
            let widget = filedArray.find(v => v.fieldName === x.name)?.shape
            if (['日期时间', '日期', '日期年份', '日期月份', '日期周', '日期季度', '时分秒'].includes(widget)) {
              return <div style={{ ...style, background: 'rgb(255 225 127)', color: 'rgb(255 145 34)' }}>日期时间</div>
            }
            if (['可编辑值选择器', '平铺值选择器', '站点选择器'].includes(widget)) {
              return <div style={{ ...style, background: 'rgb(181 229 157)', color: 'rgb(50 128 10)' }}>下拉框</div>
            }
            return <div style={{ ...style, background: 'rgb(255 165 214)', color: 'rgb(255 0 140)' }}>文本搜索</div>
          }
        },
      ]
    }
    return [
      {
        title: '已选列表',
        dataIndex: 'name',
        width: 150,
        key: 'name',
      },
    ]
  }, [attr, selectData, filedArray])

  const radioChange = ({ row, value }) => {
    let array = selectData.map(v => ({ name: v.name, value: v.name === row.name ? (value[1] || value[0] || '') : v.value }))
    setSelectData(array)
  }

  const open = ({ attr, values }) => {
    setAttr(attr)
    if (attr === 'OrderByFieldConfig') {
      if (values?.[attr]) {
        setSelectData(JSON.parse(values?.[attr]))
      } else {
        setSelectData([])
      }
    } else {
      let value = values?.[attr]
      let array = value ? value.split(',')?.map(v => ({ name: v })) : []
      setSelectData(array)
    }
    setVisible(true)
  }

  const checkChange = (value) => {
    let array = []
    value.forEach(v => {
      array.push({ name: v, value: selectData.find(s => s.name === v)?.value || '' })
    })
    setSelectData(array)
  }

  const dragCallBack = (value) => {
    if (value) {
      setSelectData(value);
    }
  }

  const getIndeterminate = (group) => {
    let length = 0
    if (Array.isArray(group)) {
      selectData.forEach(v => {
        if (group.includes(v.name)) {
          length++
        }
      })
    }
    if (!length) {
      return 'false'
    } else if (length === group.length) {
      return 'true'
    } else {
      return 'other'
    }
  }

  const groupChange = ({ type, group }) => {
    if (type === 'true') {
      let array = selectData.filter(v => !group.includes(v.name))
      setSelectData(array)
    } else {
      let array = selectData.map(v => v.name)
      let newArr = [...new Set([...array, ...group])]
      setSelectData(newArr.map(v => ({ name: v })))
    }
  }

  const onOk = () => {
    setVisible(false)
    props?.submit?.({ attr, selectData })
  }

  if (!visible) {
    return null
  }

  return (
    <Modal
      visible={visible}
      title="字段集选择"
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      width="750px"
      destroyOnClose
      centered
      cancelText="取消"
      okText="确认"
      onCancel={() => setVisible(false)}
      onOk={onOk}
      forceRender
      getContainer={false}
    >
      <div className={styles.listCard}>
        <div className={styles.cardItem} style={{ borderRight: '1px solid #99bbe8' }}>
          <div className={styles.cardContent}>
            <Checkbox.Group
              value={selectData?.map(v => v.name)}
              onChange={checkChange}
            >
              {
                Object.keys(filed).map((item, index) => {
                  const type = getIndeterminate(filed[item])
                  return (
                    <div
                      className={classnames({ [styles.cardItemData]: true, [styles.cardItemData1]: item == '外部字段' })}
                      key={index}
                    >
                      <Divider
                        orientation="left"
                        style={{ margin: '0 0 10px 0', color: '#15428b', borderTopColor: '#99bbe8' }}
                      >
                        <span
                          className={styles.groupCheck}
                          type={type}
                          onClick={() => groupChange({ type, group: filed[item] })}
                          style={{ marginRight: '7px' }}
                        />
                        {item == '外部字段' && <span style={{ color: 'red' }}>{item}</span>}
                        {item == '内置字段' && <span>{`${item}（谨慎选择）`}</span>}
                        {item != '外部字段' && item != '内置字段' && <span>{item}</span>}
                      </Divider>
                      {
                        filed[item].map(v => <Checkbox key={v} style={{ marginLeft: '0', width: '100%' }} value={v}>{v}</Checkbox>)
                      }
                    </div>
                  )
                })
              }
            </Checkbox.Group>
          </div>
        </div>
        <div className={styles.cardItem}>
          <div className={styles.cardContent}>
            <div className={styles.doctorTable}>
              <DragTable
                bordered
                style={{ marginBottom: '10px' }}
                rowKey={record => record.name}
                columns={columns}
                dataSource={selectData}
                pagination={false}
                size="small"
                dragCallBack={dragCallBack}
                ItemTypes="stadingOrder"
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  )

}

export default forwardRef(SelectField)
