import React from 'react';
import { FormBuilder, Connect, Input, Button, Form } from 'amos-framework';
import { getSceneValue, recursive, StdTable } from 'amos-designer';
import { Tip } from '@gm/graphmod-common';
import { fastDeepEqual } from 'amos-tool';
import { CommonModal } from '../../index';
import './index.scss';

const BasicForm = FormBuilder.BasicForm;
const enhanceForm = Connect.enhanceForm;
const FormItem = Form.Item;
/**
 * SelectSearchModel
 * @class SelectSearchModel
 * @extends {Component}
 */
@enhanceForm
class SelectSearchModel extends BasicForm {
  constructor(props) {
    super(props);
    this.state = {
      defaultvalue: '',
      posVisible: false,
      expandedKeys: [],
      dataSource: [],
      searchData: [],
      value: '',
      selectedDataRef: {},
      form: { }
    };
  }

  componentWillReceiveProps(nextProps) {
    const tarItem = recursive(this.props.data.items).find(e => e.title === nextProps.value) || {};
    this.setState({
      defaultvalue: tarItem.title
    });
    if (nextProps.data?.items && !fastDeepEqual(nextProps.data.items, this.state.dataSource)){
      this.initData(nextProps);
    }
  }

  initData = (props) => {
    const dataSource = getSceneValue(props, 'data.items', []);
    this.setState({
      dataSource,
      searchData: dataSource
    });
  }

  showModel = () => {
    this.setState({
      posVisible: true
    });
  }

  cancel = () => {
    this.setState({
      posVisible: false
    });
  }

  ok = () => {
    const { value, selectedDataRef } = this.state;
    if (value) {
      this.props.onChange(value, selectedDataRef);
      this.cancel();
    } else {
      Tip.warning('请先选择!');
    }
  };

  handleSearchChange = (key,e) => {
    const { form } = this.state;
    const value = e.target.value;
    form[key] = value;
    this.setState({ form });
  };

  handleSearch=()=>{
    if (Object.keys(this.state.form).length > 0) {
      let searchDataTmp = this.state.dataSource;
      let { address, orgName, organizationCode, unitType } = this.state.form;
      let arrTmp = searchDataTmp.filter(item=>{
        return (item.unitType && item.unitType.indexOf(unitType) !== -1) || (item.fullAddress && item.fullAddress.indexOf(address) !== -1) ||
        (item.orgName && item.orgName.indexOf(orgName) !== -1) || (item.organizationCode && item.organizationCode.indexOf(organizationCode) !== -1);
      });
      this.setState({
        dataSource: arrTmp
      });
    }
  }

  handleReset=()=>{
    this.setState({
      form: {},
      dataSource: this.state.searchData
    });
  }

  renderContent() {
    const { form, dataSource } = this.state;
    const innerColumns = [
      { title: '单位名称', dataIndex: 'orgName', key: 'orgName' },
      { title: '统一信用代码', dataIndex: 'organizationCode', key: 'organizationCode' },
      { title: '单位类型', dataIndex: 'unitType', key: 'unitType' },
      { title: '注册地址', dataIndex: 'fullAddress', key: 'fullAddress' },
      { title: '登记时间', dataIndex: 'approvedTime', key: 'approvedTime' },
      { title: '状态', dataIndex: 'unitStatus', key: 'unitStatus' }
    ];

    const cusColumns = innerColumns.reduce((prev, cur) => {
      if (cur.key === 'name'){
        prev.push({
          ...cur,
          render: text => <span>{text}</span>
        });
      } else {
        prev.push(cur);
      }
      return prev;
    }, []);

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          value: selectedRows[0].orgName,
          selectedDataRef: selectedRows[0]
        });
      },
      type: 'radio'
    };

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    return (
      <div>
        <Form
          className="basic-demo search-model-form"
          ref={component => this.form = component}
          model={form}>
          <div>
            <FormItem label="单位类型" field="unitType" {...formItemLayout} >
              <Input
                value={form.unitType}
                placeholder="请输入"
                onChange={(e) => this.handleSearchChange('unitType', e)}
              />
            </FormItem>
            <FormItem label="单位名称" field="orgName" {...formItemLayout} >
              <Input
                value={form.orgName}
                placeholder="请输入"
                onChange={(e) => this.handleSearchChange('orgName', e)}
              />
            </FormItem>
          </div>
          <div>
            <FormItem label="所在区域" field="address" {...formItemLayout} >
              <Input
                value={form.address}
                placeholder="请输入"
                onChange={(e) => this.handleSearchChange('address', e)}
              />
            </FormItem>
            <FormItem label="统一信用代码" field="organizationCode" {...formItemLayout} >
              <Input
                value={form.organizationCode}
                placeholder="请输入"
                onChange={(e) => this.handleSearchChange('organizationCode', e)}
              />
            </FormItem>
          </div>
          <div>
            <FormItem {...formItemLayout}>
              <Button className="search-model-btn" type="minor" onClick={this.handleSearch}>查询</Button>
              <Button type="minor" onClick={this.handleReset}>重置</Button>
            </FormItem>
          </div>
        </Form>
        <StdTable rowSelection={rowSelection} columns={cusColumns} dataSource={dataSource} pagination bordered  />
      </div>
    );
  }

  render() {
    const { posVisible, defaultvalue } = this.state;
    const { disabled } = this.props;
    const modelTitle = getSceneValue(this.props, 'data.modelTitle', '请选择');
    return (
      <div className="tree-select-model-box">
        <div className="tree-select-model">
          <div className="tree-select-model-input">
            <div className="amos-tree-select-title amos-text-overflow amos-popover-trigger">{defaultvalue ? defaultvalue : '请选择'}</div>
          </div>
          <Button className="mods-modelinput-btn" size="sm" disabled={disabled} onClick={this.showModel}>选择</Button>
        </div>
        <CommonModal modalClass="search-model-style" width={1100} title={modelTitle} visible={posVisible} destroyContent outterClosable={false} onOk={this.ok} onCancel={this.cancel} >
          <div className="eh-listselect-modal">
            <div className="eh-listselect-list mod-com-scrollbar">
              {this.renderContent()}
            </div>
          </div>
        </CommonModal>
      </div>
    );
  }
}

export default SelectSearchModel;
