
import { Row, Col, Card, Tree, Form, Tabs, TreeSelect, Input, InputNumber, Modal, Button, message } from 'antd'
import React, { useState, useEffect } from 'react';
import request from '@/utils/request';
import apis from '@/services/apis';
import moment from 'moment';
import TreedataFrom from './form';
const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const { Search } = Input;
const { TabPane } = Tabs;

const treeData =
  [
    {
      title: 'institutionId',
      name: 'institutionName',
      key: '0-0-0',
      selectable: false,
      children: [
        { name: 'institutionName', phone: '13184013427', remark: "", day: "1991-11-22", cardId: '210203197503102721', sex: 2, id: '4242', belon: 2, homeaddres: 2, key: '0-0-0-1', },
        { title: '柯琼彦', phone: '13184013427', remark: "", day: "1991-11-22", cardId: '210203197503102721', sex: 2, id: '4242', belon: 2, homeaddres: 2, key: '0-0-0-2', },
      ],
    },
    {
      title: '分厂员工管理',
      key: '0-0-1',
      selectable: false,
      children: [
        { title: '伏佳', phone: '18613523527', remark: "", day: "1992-10-11", cardId: '520323197806058856', sex: 1, id: '1124', belon: 4, homeaddres: 4, key: '0-0-1-0' },
        { title: '舒宏', phone: '14736632088', remark: "", day: "1992-12-13", cardId: '610729197408202551', sex: 1, id: '4534', belon: 3, homeaddres: 2, key: '0-0-1-1' },
        { title: '狄莉珍', phone: '17604898508', remark: "", day: "1993-10-11", cardId: '820000195008115837', sex: 1, id: '4242', belon: 1, homeaddres: 5, key: '0-0-1-2' },
      ],
    },
  ]




// const item = this.info.node.key 

class TreeDemo extends React.Component {
  formRef = React.createRef();

  constructor(props) {
    super(props)
    this.state = {
      expandedKeys: ['0-0-0', '0-0-1'],
      autoExpandParent: false,
      checkedKeys: ['0-0-0'],
      searchValue: '',
      selectedKeys: [],
      // treeTitle: [info.node.props],
      checked: true,
      treeData: [],
      testarr: []
    };
  }
  // --------标签页
  callback = (key) => {
    console.log(key);
  }




  onExpand = expandedKeys => {
    console.log('onExpand', expandedKeys);

    // 如果没有将 autoExpandParent 设置为 false，如果子项展开，父项不能折叠。
    // 或者，您可以删除所有扩展的子键。
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  handelSex = e => {
    this.setState({
      sex: e.target.value
    });
    console.log(valeu);
  };

  //修改
  onChangethis = (value) => {

    const treeData = this.state.treeData
    let Data1 = this.state.treeData
    for (var i = 0; i < treeData.length; i++) {
      for (var j = 0; j < treeData[i].children.length; j++) {
        // console.log(Data1[i].children[j].key);
        // console.log("---------")
        // console.log(value);
        if (treeData[i].children[j].key == value.key) {

          Data1[i].children[j] = value
          //qileguaile wo cao
          console.log(Data1[i].children[j]);
          // console.log(treeData[i].children[j].key)
          break
        }
      }
    }
    this.setState({
      treeData1: Data1
    }, () => {
      message.success('修改成功！')
    })

  }
  //删除
  onDelect = (value) => {
    const treeData = this.state.treeData
    let Data1 = this.state.treeData
    for (var i = 0; i < treeData.length; i++) {
      for (var j = 0; j < treeData[i].children.length; j++) {

        if (treeData[i].children[j].key == value.key) {

          delete Data1[i].children[j]
          break
        }
      }

    }
    // console.log("----Data1-----")
    // console.log(Data1)
    this.setState({
      treeData: Data1
    }, () => {
      message.success('shanchuchenggong')
    })

  }



  onSelect = (values, info) => {
    // this.FromValue(info.node)
    console.log(this.state.treeData)
    console.log(info)
    this.setState({ values }, () => {
      this.formRef.current.setFieldsValue({
        ...info.node.props,
        key: info.node.props.eventKey,//event
        day: moment(info.node.props.day)
      })
      console.log(this.getTreeData)

      // moment(info.node.props.day).format('YYYY-MM-DD')
    })
  }



  // getTreeData = (e) => {
  //   request({
  //     url: "http://localhost:8000/api/admin/institution/list",
  //     method: 'GET',

  //     // params: {leveltype: 3, cityId},
  //     action: "admin.institution.get",
  //   }).then((treeData) => {
  //     setData(treeData)
  //     console.log(this.getTreeData)
  //   })
  // }






  async institutionTree(params) {
    let arr = []

    return request('/api/admin/institution/list', {
      method: 'GET',
      data: params,
    }).then((testarr2) => {
      this.setState({ testarr: testarr2 }, () => {
        console.log("testarr2")
        console.log(this.state.testarr)
        // title: 'institutionId',
        // name: 'institutionName',
        // key: '0-0-0',
        const arr2 = this.state.testarr
        for (var i = 0; i < this.state.testarr.length; i++) {
          let list = {
            title: 'institutionId',
            name: 'institutionName',
            key: '0-0-0'
          }
          list.title = arr2[i].institutionName
          list.key = '0' + i.toString
          arr.push(list)

        }

        this.setState({
          treeData: arr
        })

      })
      // console.log(this.getTreeData)
    })
  }

  componentDidMount() {
    // fetch(`http://localhost:8000/api/admin/institution/list`, {
    //   headers: {
    //     Authorization: "Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxIiwib3JnSWQiOiIxIiwiZXhwIjoxNjI3MDQ1MjQxfQ.7FhVDoI0dEECZinRUzMzcLl-kcobkamZSqoUzTxBTRo"
    //   }
    // }).then((res) => {
    //   console.log(res)
    // }),
    // this.institutionTree()
    this.institutionTree([])

  }







  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}  >
            {this.renderTreeNodes(item.children)}
          </TreeNode >
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });
  //搜索框 
  // onChange = e => {
  //   const { value } = e.target;
  //   const expandedKeys = treeData
  //     .map(item => {
  //       if (item.title.indexOf(value) > -1) {
  //         return getParentKey(item.key, gData);
  //       }
  //       return null;
  //     })
  //     .filter((item, i, self) => item && self.indexOf(item) === i);
  //   this.setState({
  //     expandedKeys,
  //     searchValue: value,
  //     autoExpandParent: true,
  //   });
  // };




  render() {
    const { searchValue } = this.state;
    return (
      <Card>
        <Row >
          <Col xs={{ span: 5, offset: 1 }} lg={{ span: 6, offset: 0 }}>
            <Card>
              <FormItem
                label="管辖部门"
              >
                {/* <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} /> */}
                <Tree
                  // api={apis.Institution.instIist}
                  showLine
                  defaultExpandedKeys={['0-0']}
                  onSelect={this.onSelect}
                  treeData={this.state.treeData}
                // api={apis.Institution.instIist} 
                >
                  {this.renderTreeNodes(this.state.treeData)}
                  {/* 动态渲染 */}
                </Tree >
              </FormItem>
            </Card>
          </Col>
          <Col xs={{ span: 10, offset: 10 }} lg={{ span: 10, offset: 4 }}>
            <Card>
              <Tabs defaultActiveKey='1' onChange={this.callback}  >
                <TabPane tab='编辑' key='1'>
                  <TreedataFrom
                    ref={this.formRef}
                    triggerRef={this.bindRef}
                    onChangethis={this.onChangethis}
                    onSubmit={this.onChangethis}
                  />
                </TabPane>
                <TabPane tab='新增' key='2'>
                  <div>You cannot set a form field before rendering a field associated with the value. </div>
                </TabPane>

              </Tabs>
            </Card>
          </Col>
        </Row>
      </Card>
    );
  }

}

export default TreeDemo