import React from 'react'
import { connect } from 'dva'
import { Table, Button, Row, Col, Form, Input, Select, InputNumber, Modal, Switch, TreeSelect, message, Tree, Popconfirm, Popover, Spin, Tabs } from 'antd'

import {
  empty,
  extendRule,
  initFilter,
  initQueryFilter,
  setDataFieldValue,
  guid,
  getDataFieldValue,
  getOnlyPropertyData
} from '../utils/common'
import CheckToInput from '../common/CheckToInput'

const TreeSelectNode = TreeSelect.TreeNode
const TreeNode = Tree.TreeNode
const Option = Select.Option
const TabPane = Tabs.TabPane

class UserCustomQuryEditPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: {},
      queryFields: []
    }
  };

  loadData = (id, isCopySys, copySrcId) => {
    const { login } = this.props
    const json = initFilter(login.OrgId, this.props.formId, '', 0, 1, id, this.props.login.userId, this.props.code, isCopySys, copySrcId)
    this.props.dispatch({
      type: 'search/getUserConfig',
      payload: json
    }).then(ret => {
      if (ret) {
        this.setState({
          data: ret && ret.Nav_UserCCQuery ? ret.Nav_UserCCQuery : {
            ID: id || guid(),
            ORG_ID: this.props.login.OrgId
          },
          queryFields: ret && ret.Nav_Fields ? ret.Nav_Fields : []
        })
      }
    })
  };

  doGetQueryFields = (curFieldName, tableName, curLabel, onComplete) => {
    const json = initFilter(this.props.login.OrgId, this.props.formId, 'CREATE_TIME', 0, 1, curFieldName, tableName, curLabel)
    this.props.dispatch({
      type: 'search/getQueryFields',
      payload: json
    }).then(ret => {
      onComplete && onComplete(ret)
    })
  }

  handleOnHeadChange = (field, value) => {
    const data = { ...this.state.data }
    setDataFieldValue(data, field, value)
    this.setState({
      data
    })
  }

  handleFieldAddRow = (groupId) => {
    const data = { ...this.state.data }
    if (!data.Nav_Fields) {
      data.Nav_Fields = []
    }
    data.Nav_Fields.push({
      ORG_ID: this.props.login.OrgId,
      ID: guid(),
      IS_DEFAULT_QUERY: true,
      FEILD_TYPE: 0,
      USER_C_C_QUERY_GROUP_ID: groupId,
      USER_C_C_QUERY_ID: data.ID,
      CODE: this.props.code
    })

    this.setState({
      data
    })
  };

  handleGroupAddRow = (groupId) => {
    const data = { ...this.state.data }
    if (!data.Nav_Groups) {
      data.Nav_Groups = []
    }
    data.Nav_Groups.push({
      ORG_ID: this.props.login.OrgId,
      ID: guid(),
      IS_DISPLAY: true,
      PARENT_ID: groupId,
      USER_C_C_QUERY_ID: data.ID,
      RELATION_TYPE: 1,
      CODE: this.props.code
    })

    this.setState({
      data
    })
  };

  handleFieldDeleteRow = (id) => {
    const data = { ...this.state.data }
    if (data.Nav_Fields) {
      const tmps = []
      data.Nav_Fields.forEach(t => {
        if (t.ID !== id) {
          tmps.push(t)
        }
      })
      data.Nav_Fields = tmps
    }
    this.setState({
      data
    })
  };

  handleGroupDeleteRow = (id) => {
    const data = { ...this.state.data }
    if (data.Nav_Groups) {
      const tmps = []
      data.Nav_Groups.forEach(t => {
        if (t.ID !== id) {
          tmps.push(t)
        }
      })
      data.Nav_Groups = tmps
    }
    this.setState({
      data
    })
  };

  handleOnDetailChange = (id, field, e) => {
    if (e != null && e != undefined) {
      const value = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e))
      const data = { ...this.state.data }
      if (data.Nav_Fields) {
        data.Nav_Fields.forEach(t => {
          if (t.ID === id) {
            setDataFieldValue(t, field, value)
          }
        })
      }
      this.setState({
        data
      })
    }
  };

  handleOnGroupChange = (id, field, e) => {
    if (e != null && e != undefined) {
      const value = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e))
      const data = { ...this.state.data }
      if (data.Nav_Groups) {
        data.Nav_Groups.forEach(t => {
          if (t.ID === id) {
            setDataFieldValue(t, field, value)
          }
        })
      }
      this.setState({
        data
      })
    }
  };

  handleLoadChildTreeNode = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.data.Children) {
        resolve()
        return
      }
      this.doGetQueryFields(treeNode.props.data.FieldName, treeNode.props.data.TypeName, treeNode.props.data.Label, (ret) => {
        treeNode.props.data.Children = ret
        this.setState({
          queryFields: [...this.state.queryFields]
        })
        resolve()
      })
    })
  }

  getFieldTreeNode = (data) => {
    return data.map((item) => {
      if (item.Children) {
        return (
          <TreeSelectNode title={item.Label} key={item.FieldName} value={item.FieldName} data={item} isLeaf={item.IsLeaf}>
            {this.getFieldTreeNode(item.Children)}
          </TreeSelectNode>
        )
      }
      return <TreeSelectNode title={<>{item.IsRequire ? <span style={{ color: 'red' }}>*</span> : null}{item.Label}</>} key={item.FieldName} value={item.FieldName} data={item} isLeaf={item.IsLeaf} />
    })
  };

  handleSelectFieldNode = (id, nodeData) => {
    const data = { ...this.state.data }
    if (data.Nav_Fields) {
      data.Nav_Fields.forEach(t => {
        if (t.ID === id) {
          setDataFieldValue(t, 'FEILD_TYPE', 0)
          setDataFieldValue(t, 'QUERY_NAME', getDataFieldValue(nodeData, 'FieldName'))
          setDataFieldValue(t, 'LABEL', getDataFieldValue(nodeData, 'ShowLabel'))
          setDataFieldValue(t, 'IS_SYS_QUERY_FIELD', getDataFieldValue(nodeData, 'IsSysField'))
          setDataFieldValue(t, 'DATA_TYPE', getDataFieldValue(nodeData, 'DataType'))
          setDataFieldValue(t, 'IS_CUSTOM', getDataFieldValue(nodeData, 'IsCustom'))
          setDataFieldValue(t, 'IS_SYS_PARAM', getDataFieldValue(nodeData, 'IsSysParam'))
          setDataFieldValue(t, 'OP_DEFAULT', getDataFieldValue(nodeData, 'OpDefault'))
          setDataFieldValue(t, 'ENUM_NAME', getDataFieldValue(nodeData, 'EnumName'))
          setDataFieldValue(t, 'NUM', getDataFieldValue(nodeData, 'Num'))
          setDataFieldValue(t, 'CASE', getDataFieldValue(nodeData, 'CaseType'))
          setDataFieldValue(t, 'IS_REQUIRE', getDataFieldValue(nodeData, 'IsRequire'))
          setDataFieldValue(t, 'DATA_VALUE', '')
        }
      })
    }
    this.setState({
      data
    })
  };

  handleOk = () => {
    const data = { ...this.state.data }

    let isError = false
    const updateData = getOnlyPropertyData(data)
    if (empty(updateData.TITLE)) {
      message.error('请填写标题')
      isError = true
      return
    }

    if (data.Nav_Fields) {
      const tmps = []
      data.Nav_Fields.forEach(t => {
        if (empty(t.QUERY_NAME)) {
          message.error('请选择字段')
          isError = true
          return
        }
        if (empty(t.LABEL)) {
          message.error('请填写显示名称')
          isError = true
          return
        }
        if (t.IS_REQUIRE && !t.DATA_VALUE) {
          message.error('必填字段时，请填写默认值')
          isError = true
          return
        }
        const tmp = getOnlyPropertyData(t)
        tmps.push(tmp)
      })
      updateData.Nav_Fields = tmps
    }

    if (data.Nav_Groups) {
      const tmps = []
      data.Nav_Groups.forEach(t => {
        const tmp = getOnlyPropertyData(t)
        tmps.push(tmp)
      })
      updateData.Nav_Groups = tmps
    }

    if (isError) return

    this.props.dispatch({
      type: 'search/saveUserConfig',
      payload: updateData
    }).then(ret => {
      if (ret) {
        this.props.afterSave && this.props.afterSave(this.state.data)
        message.success('执行成功')
      }
    })
  };

  getFieldTable = (groupId) => {
    const data = this.state.data
    const enums = this.props.app.enums
    const columns = [
      // {title: ' 类型', dataIndex: 'FEILD_TYPE', key: 'FEILD_TYPE',render:(text,record,index)=>{
      //     return <Select  value={text} onChange={(e) => {
      //       const data = {...this.state.data};
      //       if (data.Nav_Fields) {
      //         data.Nav_Fields.forEach(t => {
      //           if (t.ID === record.ID) {
      //             setDataFieldValue(t, 'FEILD_TYPE', e);
      //             setDataFieldValue(t, 'QUERY_NAME', '');
      //             if(e===1){
      //               setDataFieldValue(t, 'IS_CUSTOM', true);
      //             }
      //             else{
      //               setDataFieldValue(t, 'IS_CUSTOM', false);
      //             }
      //             setDataFieldValue(t, 'DATA_VALUE', '');
      //           }
      //         });
      //       }
      //       this.setState({
      //         data,
      //       });
      //     }}>
      //       {
      //         enums && enums.FMUserCCQueryFieldTypeEnum && enums.FMUserCCQueryFieldTypeEnum.options ? enums.FMUserCCQueryFieldTypeEnum.options.map(t => {
      //           return <Option value={t.value}>{t.label}</Option>
      //         }) : null
      //       }
      //     </Select>
      //   }},
      // {title:'编号', dataIndex: 'CODE', key: 'CODE',render:(text,record,index)=>{
      //     return <Input value={text} onChange={(e)=>{this.handleOnDetailChange(record.ID,'CODE',e);}} style={{ width: 80 }} />
      //   }},
      {
        title: <><span style={{ color: 'red' }}>*</span>字段</>,
        dataIndex: 'QUERY_NAME',
        key: 'QUERY_NAME',
        render: (text, record, index) => {
          if (record.FEILD_TYPE === 1) {
            return <Input value={text} placeholder='请输入自定义参数名称' onChange={(e) => {
              if (record.CREATE_TIME) {
                this.props.updateIsFieldChange(true)
              }
              this.handleOnDetailChange(record.ID, 'QUERY_NAME', e)
            }} style={{ width: 260 }} />
          }
          return <TreeSelect
            showSearch
            style={{ width: 260 }}
            value={text}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder='请选择字段'
            allowClear
            treeNodeFilterProp='title'
            loadData={this.handleLoadChildTreeNode}
            onSelect={(value, node, extra) => {
              const nodeData = node.props.data
              if (record.CREATE_TIME) {
                this.props.updateIsFieldChange(true)
              }
              this.handleSelectFieldNode(record.ID, nodeData)
            }}
            onChange={(value, label, extra) => {
              if (!value) {
                if (record.CREATE_TIME) {
                  this.props.updateIsFieldChange(true)
                }
                this.handleSelectFieldNode(record.ID, null)
              }
            }}
          >
            {
              this.getFieldTreeNode(groupId && this.state.queryFields ? this.state.queryFields.filter(t => !t.IsCustom) : this.state.queryFields)
            }
          </TreeSelect>
        }
      },
      {
        title: <><span style={{ color: 'red' }}>*</span>显示名称</>,
        dataIndex: 'LABEL',
        key: 'LABEL',
        render: (text, record, index) => {
          return <Input value={text} onChange={(e) => { this.handleOnDetailChange(record.ID, 'LABEL', e) }} style={{ width: 120 }} />
        }
      },
      {
        title: '是否显示',
        dataIndex: 'IS_DEFAULT_QUERY',
        key: 'IS_DEFAULT_QUERY',
        render: (text, record, index) => {
          return <Switch checkedChildren='是' unCheckedChildren='否' checked={text} onChange={(e) => { this.handleOnDetailChange(record.ID, 'IS_DEFAULT_QUERY', e) }} />
        }
      },
      {
        title: ' 操作符',
        dataIndex: 'OP_DEFAULT',
        key: 'OP_DEFAULT',
        render: (text, record, index) => {
          let opName = ''
          if (record.DATA_TYPE == 1) {
            opName = 'PFOperateTypeEnum'
          }
          else if (record.DATA_TYPE == 2) {
            opName = 'PFOperateTypeWithOutStrEnum'
          }
          if (!opName) return
          return <Select value={text} allowClear onChange={(e) => {
            this.handleOnDetailChange(record.ID, 'OP_DEFAULT', e)
          }}>
            {
              enums && enums[opName] && enums[opName].options ? enums[opName].options.map((t, tIndex) => {
                return <Option key={`${t.label}-${tIndex}`} value={t.value.toString()}>{t.label}</Option>
              }) : null
            }
          </Select>
        }
      },

      // {title: ' 是否自定义字段', dataIndex: 'IS_CUSTOM', key: 'IS_CUSTOM',render:(text,record,index)=>{
      //     return <Switch checkedChildren="是" unCheckedChildren="否" checked={text} onChange={(e)=>{this.handleOnDetailChange(record.ID,'IS_CUSTOM',e);}}/>
      //   }},
      {
        title: '默认值',
        dataIndex: 'DATA_VALUE',
        key: 'DATA_VALUE',
        render: (text, record, index) => {
          if (record.DATA_TYPE == 3 && record.ENUM_NAME) {
            return <Select value={text} allowClear onChange={(e) => {
              this.handleOnDetailChange(record.ID, 'DATA_VALUE', e)
            }}>
              {
                enums && enums[record.ENUM_NAME] && enums[record.ENUM_NAME].options ? enums[record.ENUM_NAME].options.map((t, tIndex) => {
                  return <Option key={`${t.label}-${tIndex}`} value={t.value.toString()}>{t.label}</Option>
                }) : null
              }
            </Select>
          }
          else if (record.DATA_TYPE == 4) {
            return <Switch checkedChildren='是' unCheckedChildren='否' checked={!!text}
              onChange={(e) => { this.handleOnDetailChange(record.ID, 'DATA_VALUE', (e ? 'true' : '')) }} />
          }
          else if (record.DATA_TYPE == 5) {
            return <Select value={text} allowClear onChange={(e) => {
              this.handleOnDetailChange(record.ID, 'DATA_VALUE', e)
            }} style={{ width: 210 }}>
              <Option value='{now}'>系统日期</Option>
              <Option value='{now,d,1}'>系统日期到系统日期+1天</Option>
              <Option value='{now,w,1}'>系统日期到系统日期+1周</Option>
              <Option value='{now,M,1}'>系统日期到系统日期+1月</Option>
              <Option value='{now,y,1}'>系统日期到系统日期+1年</Option>
              <Option value='{now,d,-1}'>系统日期-1天到系统日期</Option>
              <Option value='{now,w,-1}'>系统日期-1周到系统日期</Option>
              <Option value='{now,M,-1}'>系统日期-1月到系统日期</Option>
              <Option value='{now,y,-1}'>系统日期-1年到系统日期</Option>
            </Select>
          }
          else if (record.DATA_TYPE === 6) {
            const checkedData = []
            const enumName = record.ENUM_NAME
            // 根据枚举名称获取树数据
            if (enumName && enums && enums[enumName] && enums[enumName].options && enums[enumName].options.length) {
              enums[enumName].options.forEach(t => {
                checkedData.push({
                  label: t.label,
                  value: t.value,
                  key: t.value
                })
              })
            }

            // 获取值
            const tempValue = []
            const tmp = record.DATA_VALUE ? record.DATA_VALUE.split('_') : []
            tmp.forEach((n, i) => {
              if (n !== '') { tempValue.push(n) }
            })

            return <div style={{ overflow: 'auto', width: '200px' }}>
              <CheckToInput checkedData={checkedData} value={tempValue} style={{ width: '100%' }} onChange={(changeValue) => {
                this.handleOnDetailChange(record.ID, 'DATA_VALUE', changeValue && changeValue.length ? ('_' + changeValue.join('_') + '_') : null)
              }} />
            </div>
          }
          return <Input value={text} onChange={(e) => { this.handleOnDetailChange(record.ID, 'DATA_VALUE', e) }} />
        }
      },
      {
        title: '顺序索引',
        dataIndex: 'NUM',
        key: 'NUM',
        render: (text, record, index) => {
          return <InputNumber value={text} onChange={(e) => { this.handleOnDetailChange(record.ID, 'NUM', e) }} />
        }
      },

      {
        title: '',
        dataIndex: '',
        key: '',
        render: (text, record, index) => {
          return <Button type='danger' size='small' onClick={(e) => { this.handleFieldDeleteRow(record.ID) }} icon='delete' />
        }
      }
    ]

    return <>
      <div className='td-align-left'>
        <Button type='primary' onClick={() => { this.handleFieldAddRow(groupId) }} icon='plus'>新增</Button>
      </div>
      <Table style={{ marginTop: '8px' }} columns={columns} dataSource={data.Nav_Fields ? data.Nav_Fields.filter(t => t.USER_C_C_QUERY_GROUP_ID === groupId) : null} pagination={false} scroll={{ x: '100%' }} />
    </>
  };

  getGroupTable = (groupId) => {
    const data = this.state.data
    const enums = this.props.app.enums
    const columns = [
      {
        title: '关联类型',
        dataIndex: 'RELATION_TYPE',
        key: 'RELATION_TYPE',
        render: (text, record, index) => {
          return <Select value={record.RELATION_TYPE} onChange={e => { this.handleOnGroupChange(record.ID, 'RELATION_TYPE', e) }}>
            {
              enums && enums['FMUserCCQueryGroupRelationTypeEnum'] && enums['FMUserCCQueryGroupRelationTypeEnum'].options ? enums['FMUserCCQueryGroupRelationTypeEnum'].options.map((t, tIndex) => {
                return <Option key={`${t.label}-${tIndex}`} value={t.value}>{t.label}</Option>
              }) : null
            }
          </Select>
        }
      },
      {
        title: '是否显示',
        dataIndex: 'IS_DISPLAY',
        key: 'IS_DISPLAY',
        render: (text, record, index) => {
          return <Switch checkedChildren='是' unCheckedChildren='否' checked={text} onChange={(e) => { this.handleOnGroupChange(record.ID, 'IS_DISPLAY', e) }} />
        }
      },
      {
        title: '顺序索引',
        dataIndex: 'NUM',
        key: 'NUM',
        render: (text, record, index) => {
          return <InputNumber value={text} onChange={(e) => { this.handleOnGroupChange(record.ID, 'NUM', e) }} />
        }
      },

      {
        title: '',
        dataIndex: '',
        key: '',
        render: (text, record, index) => {
          return <Button type='danger' size='small' onClick={(e) => { this.handleGroupDeleteRow(record.ID) }} icon='delete' />
        }
      }
    ]

    return <>
      <div className='td-align-left'>
        <Button type='primary' onClick={() => { this.handleGroupAddRow(groupId) }} icon='plus'>新增</Button>
      </div>
      <Table style={{ marginTop: '8px' }} columns={columns} dataSource={data.Nav_Groups ? data.Nav_Groups.filter(t => t.PARENT_ID === groupId) : null}
        expandedRowRender={this.getChildGroupRender}
        pagination={false} scroll={{ x: '100%' }} />
    </>
  };

  getChildGroupRender = (record) => {
    return <Tabs defaultActiveKey={record.ID + '_1'} >
      <TabPane tab='字段' key={record.ID + '_1'}>
        {
          this.getFieldTable(record.ID)
        }
      </TabPane>
      <TabPane tab='分组' key={record.ID + '_2'}>
        {
          this.getGroupTable(record.ID)
        }
      </TabPane>
    </Tabs>
  };

  render () {
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    const data = this.state.data
    return (
      <div>
        <Form>
          <Row>
            <Col span={12}>
              <Form.Item
                label={<> <span style={{ color: 'red' }}>*</span>标题</>}
                {...formItemLayout}
              >
                <Input placeholder='请输入标题' value={data.TITLE} onChange={(e) => { this.handleOnHeadChange('TITLE', e.target.value) }} />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label='是否默认'
                {...formItemLayout}
              >
                <Switch checked={data.IS_DEFAULT} checkedChildren='是' unCheckedChildren='否' onChange={(e) => { this.handleOnHeadChange('IS_DEFAULT', e) }} />
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ marginTop: '12px' }}>
            <Tabs defaultActiveKey='1' >
              <TabPane tab='字段' key='1'>
                {
                  this.getFieldTable(null)
                }
              </TabPane>
              <TabPane tab='分组' key='2'>
                {
                  this.getGroupTable(null)
                }
              </TabPane>
            </Tabs>
          </Row>
          <Row style={{ marginTop: '12px' }}>
            <Col style={{ textAlign: 'right' }}>
              <Button type='primary' onClick={this.handleOk} icon='save'>保存</Button>
            </Col>
          </Row>
        </Form>
      </div>
    )
  }
}

class UserCustomSearchEditModel extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: [],
      treeSelectedKeys: [],
      selectId: null,
      isTreeNodeMenuVisible: false,
      treePopoverVisible: false,
      isFieldChange: false
    }
  };

  componentDidMount () {
    this.getFormId()
  };

  getFormId = () => {
    const { formCode, formId } = this.props
    const orgId = this.props.login.OrgId
    if (formCode) {
      const OJson = { 'Key': formCode, 'orgid': orgId }
      this.props.dispatch({
        type: 'app/getFormByRedis',
        payload: OJson,
        onComplete: (ret) => {
          if (ret) {
            this.setState({
              formId: ret.ID
            })
          }
        }
      })
    }
    else if (formId) {
      this.setState({
        formId
      })
    }
  };

  loadData = () => {
    const json = initQueryFilter(this.props.login.OrgId, 1, 100, 'CREATE_TIME', 0)
    extendRule(json, 'PAGE_FORM_ID', 1, this.state.formId)
    extendRule(json, 'Nav_UserCustomConfig.USER_ID', 1, this.props.login.userId)
    this.props.dispatch({
      type: 'search/getUserFields',
      payload: json
    }).then(res => {
      this.setState({ data: res || [] }, () => {
        this.props.selectId && this.selectTreeNode(this.props.selectId)
      })
    })
  };

  handleAdd = (visibleKey, isCopySys, copySrcId) => {
    const data = [...this.state.data]
    const id = guid()
    data.push({
      TITLE: '新增查询方案',
      ID: id,
      isAdd: true,
      copySrcId: copySrcId,
      isCopySys: isCopySys
    })
    this.setState({
      data,
      [visibleKey]: false
    }, () => {
      this.selectTreeNode(id)
    })
  }

  handleDelete = (visibleKey, id) => {
    this.setState({
      [visibleKey]: false
    })
    if (id) {
      this.props.dispatch({
        type: 'search/deleteUserConfig',
        payload: { id }
      }).then(ret => {
        if (ret) {
          const data = []
          this.state.data.forEach(item => {
            item.ID !== id && data.push(item)
          })
          this.setState({ data }, () => {
            this.selectTreeNode(null)
          })
          message.success('执行成功')
        }
      })
    }
  }

  updateIsFieldChange = (isFieldChange) => {
    if (isFieldChange) {
      this.isFieldChange = isFieldChange
    }
  }

  getTreeNodeMenu = (visibleKey, id, isAdd, isCopySys, copySrcId) => {
    return (
      <Form className='opt-search__contextMenu-form'>
        <Form.Item>
          <Button type='primary' onClick={(e) => { this.handleAdd(visibleKey) }} size='small' icon='plus'>新增</Button>
        </Form.Item>
        {
          (() => {
            if (isCopySys) {
              return <Form.Item>
                <Button type='primary' onClick={(e) => { this.handleAdd(visibleKey, isCopySys) }} size='small' icon='plus' title='依系统方案复制新增'>复制</Button>
              </Form.Item>
            }
          })()
        }
        {
          (() => {
            if (copySrcId) {
              return <Form.Item>
                <Button type='primary' onClick={(e) => { this.handleAdd(visibleKey, false, copySrcId) }} size='small' icon='plus' title='依选中方案复制新增'>复制</Button>
              </Form.Item>
            }
          })()
        }
        {
          (() => {
            if (id && !isAdd) {
              return <Form.Item>
                <Popconfirm title='是否确定删除?' onConfirm={() => this.handleDelete(visibleKey, id)}>
                  <Button type='danger' size='small' icon='delete'>删除</Button>
                </Popconfirm>
              </Form.Item>
            }
          })()
        }
        {
          (() => {
            if (id && this.state.selectId === id) {
              return <Form.Item>
                <Button type='default' size='small' icon='rollback' title='取消选中状态' onClick={() => {
                  this.setState({
                    [visibleKey]: false
                  })
                  this.selectTreeNode(null)
                }}>反选</Button>
              </Form.Item>
            }
          })()
        }
      </Form>
    )
  }

  renderTreeNode = (data) => {
    if (data && data.length) {
      return data.map(t => {
        const visibleKey = 'treeNodeMenuVisible_' + t.ID
        const title = <Popover placement='bottom' content={this.getTreeNodeMenu(visibleKey, t.ID, t.isAdd, false, t.ID)} trigger={['contextMenu']} visible={this.state[visibleKey]} onVisibleChange={(visible) => {
          this.setState({
            isTreeNodeMenuVisible: visible,
            [visibleKey]: visible
          }, () => {
            if (visible) {
              this.setState({
                treePopoverVisible: false
              })
            }
          })
        }}><span>{t.IS_DEFAULT ? (t.TITLE + '(默认)') : t.TITLE}</span></Popover>
        if (t.Children) {
          return (
            <TreeNode title={title} key={t.ID} data={t} isLeaf={false}>
              {this.getFieldTreeNode(t.Children)}
            </TreeNode>
          )
        }
        return <TreeNode title={title} key={t.ID} data={t} isLeaf />
      })
    }
  };

  upateData = () => {
    this.loadData()
  }

  selectTreeNode = (id) => {
    this.setState({
      selectId: id,
      treeSelectedKeys: (id !== null ? [id] : [])
    }, () => {
      if (this.state.selectId !== null) {
        if (this.searchFormRef) {
          let node = null
          if (this.state.data && this.state.data.length) {
            this.state.data.forEach(t => {
              if (t.ID === id) {
                node = t
              }
            })
          }
          this.searchFormRef.loadData(this.state.selectId, (node ? node.isCopySys : null), (node ? node.copySrcId : null))
        }
      }
    })
  }

  handleSelectTreeNode = (selectedKeys) => {
    if (selectedKeys && selectedKeys.length) {
      this.selectTreeNode(selectedKeys && selectedKeys.length ? selectedKeys[0] : null)
    }
  }

  handleShowModal = () => {
    this.setState({
      visible: true
    })
    this.loadData()
    if (this.props.click) {
      this.props.click()
    }
    this.isFieldChange = false
  };

  handleCloseModal = () => {
    this.setState({
      visible: false
    })
    if (this.props.close) {
      this.props.close(this.isFieldChange)
    }
  };

  render () {
    const { loading } = this.props
    return (
      <>
        <span onClick={this.handleShowModal}>{this.props.children}</span>
        <Modal visible={this.state.visible} maskClosable={false} onCancel={this.handleCloseModal} footer={false} width='80%'>
          <Spin spinning={loading.global}>
            <Row>
              <Col span={4}>
                <div className='opt-search__queryTreePanel'>
                  <Popover placement='bottom' content={this.getTreeNodeMenu('treePopoverVisible', null, false, true)} mouseEnterDelay={0.1}
                    trigger={['contextMenu']} visible={this.state.treePopoverVisible} onVisibleChange={(visible) => {
                      this.setState({
                        treePopoverVisible: (this.state.isTreeNodeMenuVisible ? false : visible)
                      })
                    }} >
                    <div className='opt-search__queryTip'>右键新增/删除</div>
                    <div style={{ minHeight: '100px', userSelect: 'none' }}>
                      <Tree onSelect={this.handleSelectTreeNode} selectedKeys={this.state.treeSelectedKeys} >
                        {
                          this.renderTreeNode(this.state.data)
                        }
                      </Tree>
                    </div>
                  </Popover>
                </div>
              </Col>
              <Col span={20}>
                {
                  this.state.selectId !== null
                    ? <UserCustomQuryEditPage formId={this.state.formId} login={this.props.login} app={this.props.app} dispatch={this.props.dispatch}
                      code={this.props.code} ref={ref => { this.searchFormRef = ref }} afterSave={this.upateData} updateIsFieldChange={this.updateIsFieldChange} /> : null
                }
              </Col>
            </Row>
          </Spin>
        </Modal>
      </>
    )
  }
}

UserCustomSearchEditModel.propTypes = {
}

export default connect(({ app, loading, login }) => ({ app, loading, login }))(UserCustomSearchEditModel)
