// 核心库
import React, { useState } from 'react'
import { connect } from 'dva'
// 组件库
import { Button, Popover, Popconfirm, message, Switch, Form } from 'antd'
import UserCustomSearchEditModel from './UserCustomSearchEditModel'
// 工具库
import { initFilter } from '../utils/common'

function EditPaneMenu (props) {
  const { data, formCode, formId, code, setVisible, onSave, onEditModalClose, login, dispatch } = props
  const { IS_DEFAULT, ID } = data

  const [isDefault, setIsDefault] = useState(IS_DEFAULT)
  const handleSwitchDefault = (val) => {
    const json = initFilter(login.OrgId, ID, '', 0, 1, val)
    dispatch({
      type: 'search/updateUserConfigIsDefault',
      payload: json
    }).then(ret => {
      if (ret) {
        setIsDefault(val)
        message.success('设置成功')
      }
    })
  }

  const handleDelPane = (id) => {
    dispatch({
      type: 'search/deleteUserConfig',
      payload: { id }
    }).then(ret => {
      ret && message.success('执行成功')
    })
  }

  return (
    <Form className='opt-search__contextMenu-form'>
      <Form.Item>
        <Switch
          checkedChildren='默认'
          unCheckedChildren='非默认'
          checked={isDefault}
          onChange={handleSwitchDefault}
        />
      </Form.Item>
      <Form.Item>
        <Button icon='save' title='保存' size='small' onClick={onSave}>保存</Button>
      </Form.Item>
      <Form.Item>
        <UserCustomSearchEditModel
          formCode={formCode}
          formId={formId}
          code={code}
          selectId={ID}
          click={() => setVisible(false)}
          close={onEditModalClose}
        >
          <Button icon='edit' title='编辑' size='small'>编辑</Button>
        </UserCustomSearchEditModel>
      </Form.Item>
      <Form.Item>
        <Popconfirm
          title='是否确定删除?'
          onConfirm={() => handleDelPane(ID)}
        >
          <Button type='danger' icon='delete' title='删除' size='small'>删除</Button>
        </Popconfirm>
      </Form.Item>
    </Form>
  )
}

const CEditPaneMenu = connect(({ login }) => ({ login }))(EditPaneMenu)

function EditTabPane (props) {
  const [visible, setVisible] = useState(false)

  const getGroupFieldValue = (data, result) => {
    data.forEach(item => {
      if (item.fieldConfigs && item.fieldConfigs.length) {
        item.fieldConfigs.forEach(config => config.field && config.dataType !== 5 && result.fields.push(config))
      }
      result.groups.push(item)
      if (item.childGroups && item.childGroups.length) {
        getGroupFieldValue(item.childGroups, result)
      }
    })
  }

  const onSave = () => {
    const { data, refsOfField, refsOfGroup, login, dispatch } = props
    const { ID: id } = data

    const result = { fields: [], groups: [] }

    if (refsOfField && refsOfField[id]) {
      const { fieldConfigs = [] } = refsOfField[id].state
      fieldConfigs.forEach(item => item.field && item.dataType !== 5 && result.fields.push(item))
    }
    if (refsOfGroup && refsOfGroup[id]) {
      const { groupConfigs = [] } = refsOfGroup[id].state
      getGroupFieldValue(groupConfigs, result)
    }

    const fields = result.fields.map(item => ({
      ORG_ID: login.OrgId,
      ID: item.id,
      FEILD_TYPE: item.fieldType,
      IS_SYS_QUERY_FIELD: item.isSysQueryField,
      USER_C_C_QUERY_ID: item.userCCQueryId,
      CODE: item.code,
      QUERY_NAME: item.field,
      LABEL: item.label,
      USER_C_C_QUERY_GROUP_ID: item.searchGroupId,
      DATA_TYPE: item.dataType,
      IS_DEFAULT_QUERY: item.isDefaultQuery,
      IS_CUSTOM: item.isCustom,
      IS_SYS_PARAM: item.isSysParam,
      OP_DEFAULT: item.operator,
      DATA_VALUE: item.value,
      ENUM_NAME: item.data ? item.data.enumName : '',
      CASE: item.caseType,
      IS_REQUIRE: item.isRequire,
      NUM: item.num
    }))
    const groups = result.groups.map(item => ({
      ORG_ID: login.OrgId,
      ID: item.id,
      CODE: item.code,
      RELATION_TYPE: item.relationType,
      TITLE: item.title,
      PARENT_ID: item.parentId,
      IS_DISPLAY: item.isDisplay,
      NUM: item.num,
      USER_C_C_QUERY_ID: item.userCCQueryId
    }))
    dispatch({
      type: 'search/saveUserConfigFeildDefaultValue',
      payload: { ID: id, Nav_Fields: fields, Nav_Groups: groups }
    }).then(ret => {
      if (ret) {
        message.success('执行成功')
        setVisible(false)
      }
    })
  }

  const { data, formCode, formId, code, activeKey, onEditModalClose } = props
  const { isSysQuery, ID, TITLE } = data

  if (!isSysQuery && ID && ID === activeKey) {
    return (
      <Popover
        placement='bottom'
        content={
          <CEditPaneMenu
            data={data}
            formCode={formCode}
            formId={formId}
            code={code}
            setVisible={setVisible}
            onSave={onSave}
            onEditModalClose={onEditModalClose}
          />
        }
        trigger={['contextMenu']}
        visible={visible}
        onVisibleChange={setVisible}
      >
        <span>{TITLE}</span>
      </Popover>
    )
  }
  return <span>{TITLE}</span>
}

export default connect(({ login }) => ({ login }))(EditTabPane)
