import React from 'react'
import { connect } from 'dva'
import { Button, Col, Form, Input, message, Row, Select, Tabs, Tree,Spin } from 'antd'
import styles from './roleEditPage.css'
import { extend, extendRule, getOnlyPropertyData, initFilter } from "../../../utils/common"
import { cloneDeep } from 'lodash'
const FormItem = Form.Item
const Option = Select.Option
const { TextArea } = Input
const TabPane = Tabs.TabPane

class RoleEditPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: {},
      btns: [],
      permissionData: [],
      permissionTotalCount: 0,
      workstageData: {},
      panelData: {},
      menuSelectedRowKeys: [],
      menuLoadParam: {
        "RuleCount": 0,
        "IncludeCount": 0,
        "OrderCount": 0,
        "PageIndex": 1,
        "Limit": 10,
        "Start": 0,
        OrgId: this.props.login.OrgId,
        Sort: 'CODE',
        Order: '1',
        FilterGroupCount: 0,
      },
      workstageLoadParam: {
        "RuleCount": 0,
        "IncludeCount": 0,
        "OrderCount": 0,
        "PageIndex": 1,
        "Limit": 10,
        "Start": 0,
        OrgId: this.props.login.OrgId,
        Sort: 'CREATE_TIME',
        Order: '1',
        FilterGroupCount: 0,
      },
      panelLoadParam: {
        "RuleCount": 0,
        "IncludeCount": 0,
        "OrderCount": 0,
        "PageIndex": 1,
        "Limit": 10,
        "Start": 0,
        OrgId: this.props.login.OrgId,
        Sort: 'CREATE_TIME',
        Order: '1',
        FilterGroupCount: 0,
      },
      checked: true,
      menuSearch: {},
      workstageSearch: {},
      departmentTreeData: [],
      departmentCheckedKeys: [],
      panes: []
    }
    this.checkedNode = []
    this.serverLoadedRows = []
    this.selectTab = ''
  }

  componentDidMount () {
    //this.props.form.resetFields()
    this.loadData()
  }

  componentWillReceiveProps (NextProps, NextContent) {
    const { data } = this.props
    let { id } = data ? data : {}
    if (!id) {
      id = ''
    }
    if (NextProps.custom['roleEditClick' + id]) {
      this.props.form.resetFields()
      this.loadData()
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['roleEditClick' + id]: false
        },
      })
    }
  }

  loadData = () => {
    const { data, formId } = this.props
    const { id } = data ? data : {}

    if (id) {
      const userGroupJson = initFilter(this.props.login.OrgId)
      extendRule(userGroupJson, 'ID', 1, id)
      // extendInclude(userGroupJson, 'Nav_Workstages');
      this.props.dispatch({
        type: 'FMRoleEdit/getRole',
        payload: userGroupJson,
        onComplete: (ret) => {
          if (ret) {        
            this.setState({
              data: ret,
              menuLoadParam: {
                ...this.state.menuLoadParam,
                ...{
                  PageIndex: 1,
                  Start: 0
                }
              }
            }, () => {
              this.loadPermissionData()
              this.LoadDepartment()
              //this.loadWorkstage();
              //this.loadPanel();
            })
          }
        }
      })
    } else {
      this.setState({
        data: {
          ...this.state.data,
          ORG_ID: this.props.login.OrgId,
          PLATFORM_TYPE: 0,
          menuLoadParam: {
            ...this.state.menuLoadParam,
            ...{
              PageIndex: 1,
              Start: 0
            }
          }
        }
      }, () => {
        this.loadPermissionData()
        this.LoadDepartment()
        // this.loadWorkstage();
        //this.loadPanel();
        const { form, } = this.props
        const { setFieldsValue } = form
        if (this.props.login.OrgCode) {
          setFieldsValue({
            CODE: (this.props.login.OrgCode),
          })
        }
      })
    }
    if (formId) {
      const btnJson = initFilter(this.props.login.OrgId, '', 'NUM', 0)
      extendRule(btnJson, 'PAGE_CUSTOM_FORM_ID', 1, formId)
      this.props.dispatch({
        type: 'FMRoleEdit/getBtnList',
        payload: btnJson,
        onComplete: (ret) => {
          if (ret) {
            this.setState({
              btns: ret,
            })
          }
        }
      })
    }
  }

  getBtns = () => {
    if (this.state.btns) {
      return this.state.btns.map(item => {
        if (item.BTN_TYPE === 1) {
          return (
            <Button
              key={item.ID}
              type={item.CSS}
              icon={item.ICON}
              onClick={() => this.handleOk()}
            >
              {item.LABEL}
            </Button>
          )
        }
        return null
      })
    }
  }

  handleOk = () => {
    const { form, dispatch } = this.props
    const { validateFieldsAndScroll } = form
    validateFieldsAndScroll((errors, values) => {
      if (errors) return
      extend(this.state.data, values)
      const menuSelectedRowKeys = this.state.menuSelectedRowKeys || []
      let updateData = getOnlyPropertyData(this.state.data)
      let permissions = []
      const workstages = []
      const panels = []
      this.serverLoadedRows.forEach(item => {
        item.Permission.IS_PERMISSION = false
        menuSelectedRowKeys.forEach(key => {
          key === item.ID && (item.Permission.IS_PERMISSION = true)
        })
        item.Permission.Nav_PermissionBtns = []
        item.Permission.Nav_PermissionColumns = []
        item.Nav_Btns && item.Nav_Btns.forEach(btn => {
          btn.IsCheck && item.Permission.Nav_PermissionBtns.push(btn.Btn)
        })
        item.Nav_Columns && item.Nav_Columns.forEach(col => {
          col.IsCheck && item.Permission.Nav_PermissionColumns.push(col.Column)
        })
        permissions.push(item.Permission)
      })

      if (this.state.workstageData && this.state.workstageData.Data) {
        this.state.workstageData.Data.forEach(t => {
          let isSelect = false
          if (this.state.workstageSelectedRowKeys && this.state.workstageSelectedRowKeys.length) {
            this.state.workstageSelectedRowKeys.forEach(t2 => {
              if (t.ID === t2) {
                isSelect = true
              }
            })
          }
          let isGet = false
          if (this.state.data.Nav_Workstages && this.state.data.Nav_Workstages.length) {
            this.state.data.Nav_Workstages.forEach(t1 => {
              if (t1.WORKSTAGE_ID === t.ID) {
                t1.IS_PERMISSION = isSelect
                workstages.push(t1)
                isGet = true
              }
            })
          }
          if (isSelect && !isGet) {
            workstages.push({ WORKSTAGE_ID: t.ID, ORG_ID: this.props.login.OrgId, IS_PERMISSION: true })
          }
        })
      }

      if (this.state.panelData && this.state.panelData.Data) {
        this.state.panelData.Data.forEach(t => {
          let isSelect = false
          if (this.state.panelSelectedRowKeys && this.state.panelSelectedRowKeys.length) {
            this.state.panelSelectedRowKeys.forEach(t2 => {
              if (t.ID === t2) {
                isSelect = true
              }
            })
          }
          if (!isSelect) {
            return
          }
          let isGet = false
          if (this.state.data.Nav_Panels && this.state.data.Nav_Panels.length) {
            this.state.data.Nav_Panels.forEach(t1 => {
              if (t1.PANEL_ID === t.ID) {
                panels.push(t1)
                isGet = true
              }
            })
          }
          if (isSelect && !isGet) {
            panels.push({ PANEL_ID: t.ID, ORG_ID: this.props.login.OrgId })
          }
        })
      }

      //updateData['Nav_MenuPermissions'] = permissions
      //updateData['Nav_Workstages'] = workstages
      //updateData['Nav_Panels'] = panels
      updateData['CheckKeys'] = this.checkedNode
      updateData['DepartmentCheckedKeys'] = this.state.panes
      dispatch({
        type: 'FMRoleEdit/updateRole',
        payload: updateData,
        //payload:checkedNode,
        onComplete: (ret) => {
          ret && message.success('执行成功')
        }
      })
    })
  }

  workstageChangeTable = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination
    let newParams = {
      ...this.state.workstageLoadParam,
      OrgId: this.props.login.OrgId,
      PageIndex: current,
      Limit: pageSize,
      Sort: sorter.field || 'CREATE_TIME',
      Order: sorter.order === "descend" ? '0' : '1',
      Start: (current - 1) * pageSize
    }
    this.doLoadWorkstage(newParams)
    this.setState({
      workstageLoadParam: {
        ...this.state.workstageLoadParam,
        ...newParams
      }
    })
  }

  doLoadWorkstage = (param) => {
    const { dispatch } = this.props
    const newParam = JSON.parse(JSON.stringify(param)) // {...param};
    newParam.OrgType = 1
    newParam.OrgId = this.state.data && this.state.data.ORG_ID ?
      this.state.data.ORG_ID : this.props.login.OrgId
    extendRule(newParam, 'ENABLE_STATUS', 1, 0)
    if (this.state.workstageSearch.CODE) {
      extendRule(newParam, 'CODE', 9, this.state.workstageSearch.CODE)
    }
    if (this.state.workstageSearch.NAME) {
      extendRule(newParam, 'NAME', 9, this.state.workstageSearch.NAME)
    }
    if (this.state.workstageSearch.TYPE != null) {
      extendRule(newParam, 'TYPE', 1, this.state.workstageSearch.TYPE)
    }
    dispatch({
      type: 'FMRoleEdit/getWorkstages',
      payload: newParam,
      onComplete: (ret) => {
        this.setState({
          workstageData: ret,
        })
      }
    })
  }

  loadWorkstage = () => {
    const workstageSelectedRowKeys = []
    if (this.state.data && this.state.data.Nav_Workstages && this.state.data.Nav_Workstages.length) {
      this.state.data.Nav_Workstages.forEach(n => {
        if (n.IS_PERMISSION) {
          workstageSelectedRowKeys.push(n.WORKSTAGE_ID)
        }
      })
    }
    this.setState({
      workstageSelectedRowKeys,
    })
    this.doLoadWorkstage(this.state.workstageLoadParam)
  }

  panelChangeTable = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination
    let newParams = {
      ...this.state.panelLoadParam,
      OrgId: this.props.login.OrgId,
      PageIndex: current,
      Limit: pageSize,
      Sort: sorter.field || 'CREATE_TIME',
      Order: sorter.order === "descend" ? '0' : '1',
      Start: (current - 1) * pageSize
    }
    this.doLoadPanel(newParams)
    this.setState({
      panelLoadParam: {
        ...this.state.panelLoadParam,
        ...newParams
      }
    })
  }

  doLoadPanel = (param) => {
    const { dispatch } = this.props
    const newParam = { ...param }
    extendRule(newParam, 'ENABLE_STATUS', 1, 0)
    newParam.OrgType = 1
    newParam.OrgId = this.state.data && this.state.data.ORG_ID ?
      this.state.data.ORG_ID : this.props.login.OrgId
    dispatch({
      type: 'FMRoleEdit/getPanels',
      payload: newParam,
      onComplete: (ret) => {
        this.setState({
          panelData: ret,
        })
      }
    })
  }

  LoadDepartment = () => {
    const json = {
      OrgId: this.props.login.OrgId,
      Keyword: this.state.data.ID,
      IgnoreOrgRule: true
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Role/GetTreeDepartment',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data && re.Data) {
          this.setState({
            panes: re.Data
          })
        }
      }
    })
  }

  loadPanel = () => {
    const panelSelectedRowKeys = []
    if (this.state.data && this.state.data.Nav_Panels && this.state.data.Nav_Panels.length) {
      this.state.data.Nav_Panels.forEach(n => {
        panelSelectedRowKeys.push(n.PANEL_ID)
      })
    }
    this.setState({
      panelSelectedRowKeys,
    })
    this.doLoadPanel(this.state.panelLoadParam)
  }

  menuChangeTable = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination

    let newParams = {
      ...this.state.menuLoadParam,
      OrgId: this.props.login.OrgId,
      PageIndex: current,
      Limit: pageSize,
      Sort: sorter.field || 'CODE',
      Order: sorter.order === "descend" ? '0' : '1',
      Start: (current - 1) * pageSize
    }
    this.doLoadPermissionData(newParams)
    this.setState({
      menuLoadParam: {
        ...this.state.menuLoadParam,
        ...newParams
      }
    })
  }

  loadPermissionData = () => {
    this.doLoadPermissionData(this.state.menuLoadParam)
  }

  doLoadPermissionData = (param) => {
    const { form, dispatch } = this.props
    const { getFieldValue } = form
    const newParam = { ...param }
    extendRule(newParam, 'PLATFORM_TYPE', 1, getFieldValue('PLATFORM_TYPE'))
    extendRule(newParam, 'ENABLE_STATUS', 1, 0)
    if (this.state.menuSearch.CODE) {
      extendRule(newParam, 'CODE', 9, this.state.menuSearch.CODE)
    }
    if (this.state.menuSearch.NAME) {
      extendRule(newParam, 'NAME', 9, this.state.menuSearch.NAME)
    }
    if (this.state.menuSearch.MODULE_TYPE != null) {
      extendRule(newParam, 'MODULE_TYPE', 1, this.state.menuSearch.MODULE_TYPE)
    }
    newParam.Keyword = this.state.data.ID
    newParam.OrgType = 1
    newParam.OrgId = this.state.data && this.state.data.ORG_ID ? this.state.data.ORG_ID : this.props.login.OrgId
    dispatch({
      type: 'FMRoleEdit/getPermissionForms',
      payload: newParam,
      onComplete: (ret) => {
        if (ret == null) return
        const { Forms = [], TotalCount = 0 } = ret || {}
        const currSelectedKeys = cloneDeep(this.state.menuSelectedRowKeys)
        const serverLoadedRowKeys = this.serverLoadedRows.map(slr => slr.ID)
        const permissionData = []
        Forms.forEach(tableRow => {
          const { ID, IsCheck } = tableRow
          if (IsCheck) {
            const findIndex = serverLoadedRowKeys.indexOf(ID)
            if (findIndex !== -1) {
              this.serverLoadedRows[findIndex].IsCheck && currSelectedKeys.indexOf(ID) === -1 && currSelectedKeys.push(ID)
            } else {
              currSelectedKeys.push(ID)
            }
          }
          serverLoadedRowKeys.indexOf(ID) === -1 && this.serverLoadedRows.push(tableRow)
          permissionData.push(ID)
        })
        this.checkedNode = ret.checks
        this.setState({
          permissionData,
          permissionTotalCount: TotalCount,
          menuSelectedRowKeys: currSelectedKeys,
          treeDatas: ret.rolePermissionTreeModels,
          checkedKeys: ret.checkLastKey
        })
      }
    })
  }
  loadPermissionData = () => {
    this.doLoadPermissionData(this.state.menuLoadParam)
  }


  // 选择复选框触发函数
  onCheckTree = (checkedKeys, checkedNodes) => {
    let checkednode = [...checkedKeys, ...checkedNodes.halfCheckedKeys]
    this.checkedNode = checkednode
    this.setState({
      checkedKeys
    })
  }

  onLoad = (loadedKeys, { event, node }) => {
  }

  onMenuSelectChange = (selectedRowKeys, selectedRows) => {  // 选择菜单行
    const selectedIds = (selectedRows || []).map(row => row.ID)
    const { permissionData } = this.state
    this.serverLoadedRows.forEach(tableRow => {
      // 对当前table页行数据进行是否选中标记
      if (permissionData.indexOf(tableRow.ID) !== -1) {
        tableRow.IsCheck = selectedIds.indexOf(tableRow.ID) !== -1
        // 表单列权限勾选与取消
        tableRow.Nav_Columns && tableRow.Nav_Columns.forEach(nc => {
          nc.IsCheck = tableRow.IsCheck
        })
        // 表单按钮权限勾选与取消
        tableRow.Nav_Btns && tableRow.Nav_Btns.forEach(nb => {
          nb.IsCheck = tableRow.IsCheck
        })
      }
    })
    this.setState({
      menuSelectedRowKeys: selectedRowKeys
    })
  }

  onWorkstageSelectChange = (selectedRowKeys) => {  // 选择工作中心
    this.setState({ workstageSelectedRowKeys: selectedRowKeys })
  }

  onPanelSelectChange = (selectedRowKeys) => {  // 选择表格行
    this.setState({ panelSelectedRowKeys: selectedRowKeys })
  }

  onTabClick = (checkedKeys) => {
    this.selectTab = checkedKeys
  }

  onCheckDepartmentTree = (checkedKeys, pane) => {
    pane.departmentCheckedKeys = checkedKeys
    this.forceUpdate()
  }

  

  render () {
    const {loading} = this.props;
    const {
      checkedKeys,
      treeDatas,
      menuLoadParam,
      panes,   
    } = this.state  
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    return (
      <Spin spinning={loading.global}>
      <Form {...formItemLayout}>
        <Row>
          <Col span={12}>
            <Form.Item label={'角色名称'}>
              {
                getFieldDecorator('NAME', {
                  validateTrigger: 'onBlur',
                  initialValue: this.state.data.NAME,
                  rules: [{ required: true, message: '请输入角色名称' }],
                })(<Input maxLength={30} placeholder={'请输入角色名称'} />)
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={'角色编码'}>
              {
                getFieldDecorator('CODE', {
                  validateTrigger: 'onBlur',
                  initialValue: this.state.data.CODE,
                  rules: [{ required: true, message: '请输入角色编码' }],
                })(<Input maxLength={30} placeholder={'请输入角色编码'} />)
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={'平台类型'}>
              {
                getFieldDecorator('PLATFORM_TYPE', {
                  validateTrigger: 'onBlur',
                  initialValue: (this.state.data.PLATFORM_TYPE ? this.state.data.PLATFORM_TYPE.toString() : '0'),
                })(
                  <Select
                    onChange={() => {
                      this.setState({
                        menuLoadParam: {
                          ...menuLoadParam,
                          PageIndex: 1,
                          Start: 0
                        }
                      }, () => this.loadPermissionData())
                    }}
                    placeholder='数据类型'
                  >
                    <Option value='0'>后台</Option>
                    <Option value='1'>客户端</Option>
                    <Option value='2'>APP</Option>
                  </Select>
                )
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={'角色类型'}>
              {
                getFieldDecorator('ROLE_TYPE', {
                  validateTrigger: 'onBlur',
                  initialValue: (this.state.data.ROLE_TYPE ? this.state.data.ROLE_TYPE.toString() : '0')
                })(
                  <Select placeholder="数据类型" >
                    {
                      this.props.app.enums && this.props.app.enums.FMRoleTypeEnum
                        ? (
                          this.props.app.enums.FMRoleTypeEnum.options.map(t => {
                            return <Option key={t.value} value={t.value.toString()}>{t.label}</Option>
                          })
                        )
                        : null
                    }
                  </Select>
                )
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <FormItem label={'启用标志'}>
              {
                getFieldDecorator('ENABLE_STATUS', {
                  validateTrigger: 'onBlur',
                  initialValue: this.state.data.ENABLE_STATUS ? this.state.data.ENABLE_STATUS.toString() : '0'
                })(
                  <Select placeholder="数据类型" >
                    {
                      this.props.app.enums && this.props.app.enums.FMEnableStatusEnum
                        ? (
                          this.props.app.enums.FMEnableStatusEnum.options.map(t => {
                            return <Option key={t.value} value={t.value.toString()}>{t.label}</Option>
                          })
                        )
                        : null
                    }
                  </Select>
                )
              }
            </FormItem>
          </Col>
          <Col span={12}>
            <Form.Item label={'是否开启短信验证'}>
              {
                getFieldDecorator('IS_CHECK_MESSAGE', {
                  validateTrigger: 'onBlur',
                  initialValue: (this.state.data.IS_CHECK_MESSAGE ? this.state.data.IS_CHECK_MESSAGE.toString() : 'false'),
                })(
                  <Select placeholder='数据类型'>
                    <Option value='false'>否</Option>
                    <Option value='true'>是</Option>
                  </Select>
                )
              }
            </Form.Item>
          </Col>   
          <Col span={12}>
            <Form.Item label={'备注'}>
              {
                getFieldDecorator('REMARK', {
                  initialValue: this.state.data.REMARK,
                })(<TextArea maxLength={300} rows={4} placeholder={'请输入备注'} />)
              }
            </Form.Item>
          </Col>
        </Row>
        <Tabs defaultActiveKey='role-edit-page-tab1' className={styles.tabsWrap}>
          <TabPane tab='菜单授权' key='role-edit-page-tab1'>
            <Tree checkable
              multiple
              checkedKeys={checkedKeys}
              treeData={treeDatas}
              onCheck={this.onCheckTree}
            />
          </TabPane>
          <TabPane tab='数据授权' key='role-edit-page-tab4'>
            <Tabs defaultActiveKey='role-edit-page-tab2' onTabClick={this.onTabClick} tabPosition='left' className={styles.tabsWrap}>
              {
                panes.map(pane => {
                  return (
                    <TabPane
                      tab={pane.title}
                      key={pane.OrgId}
                    >
                      <Tree
                        checkable
                        multiple
                        checkedKeys={pane.departmentCheckedKeys}
                        treeData={pane.treeDataModels}
                        onCheck={(checked) => this.onCheckDepartmentTree(checked, pane)}
                      />
                    </TabPane>
                  )
                })
              }
            </Tabs>
          </TabPane>
          <div className={styles.btnRow}>{this.getBtns()}</div>
        </Tabs>
      </Form>
       </Spin>
    )
  }
}

export default connect(({ login, loading, app, FMBase, FMRoleEdit, custom }) => ({ login, loading, app, FMBase, FMRoleEdit, custom }))(Form.create()(RoleEditPage))
