import React, { useState, useEffect } from 'react';
import { Select, Card, Button, TreeSelect, Modal, message } from 'antd';
import { Tree } from 'antd';

const { TreeNode } = Tree;
import request from '@/utils/request';
const { SHOW_CHILD } = TreeSelect;
const { Option } = Select;

function parentTree(arr, id) {
  //arr 所有的树数据 id 某个子节点的id
  console.log(arr, id, 'sss');
  let temp;
  let callback = function(nowArr, id) {
    //先定义个函数寻找子节点位置 找到后 再找改节点父元素位置 以此类推
    for (let i = 0; i < nowArr.length; i++) {
      let item = nowArr[i];
      if (item.value === id) {
        // temp.push(item);
        temp = item;
        // callback(arr, item.parentid);     //pid 父级ID
        break;
      } else {
        if (item.children) {
          callback(item.children, id); //menus 子节点字段名称
        }
      }
    }
  };
  callback(arr, id);
  return temp; //最后返回
}

/**
 *
 *
 * @param {*} props
 * @returns
 */
const CitySelect = props => {
  const [data, setData] = useState({});
  const [submitting, setSubmitting] = useState(false);
  // 初始化的值
  const [tree, setTree] = useState([]);
  // 城市的值
  const [selectCityTree, setSelectCityTree] = useState([]);
  const [loading, setLoading] = useState(true);
  // {
  //   title: 'Node1',
  //   value: '0-0',
  //   key: '0-0',
  //   children: [
  //     {
  //       title: 'Child Node1',
  //       value: '0-0-0',
  //       key: '0-0-0',
  //     },
  //   ],
  // },
  // {
  //   title: 'Node2',
  //   value: '0-1',
  //   key: '0-1',
  //   children: [
  //     {

  const getTree = data => {
    return data?.map(x => {
      if (x?.children?.length > 0) {
        return {
          title: x.name,
          value: x.id,
          key: x.id,
          parentid: x.parentid,
          selectable: false,
          disableCheckbox: true,
          children: getTree(x?.children),
        };
      } else {
        return {
          title: x.name,
          value: x.id,
          key: x.id,
          parentid: x.parentid,
        };
      }
    });
  };
  const getAllCityList = e => {
    request({
      url: '/api/admin/taUser/city/tree',
      method: 'GET',
      //   params: { leveltype: 2, pageNum: 1, pageSize: 999 },
      // action: 'select',
    }).then(data => {
      // console.log(getTree(data.tdCityList), 'data.tdCityList');
      setTree(getTree(data.tdCityList));
    });
    // GET /api/admin/city/list
    // request({
    //   url: '/api/center/tdCity',
    //   method: 'GET',
    // //   params: { leveltype: 2, pageNum: 1, pageSize: 999 },
    //   action: 'select',
    // }).then(data => {
    // //   setData(data);
    // });
  };

  const getCityList = e => {
    setLoading(true)
    request({
      url: '/api/admin/tdCityList/tdCity',
      method: 'GET',
      params: { leveltype: 2, pageNum: 1, pageSize: 999 },
      action: 'select',
    }).then(data => {
      setSelectCityTree(data.map(x => x.id));
      setLoading(false)
      
    });
  };

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  // 选择城市
  const onCheck = (checkedKeys, info) => {
    setSelectCityTree(checkedKeys);
    console.log('onCheck', checkedKeys, info);
  };

  // 选择城市
  const onChange = (checkedKeys, label, extra) => {
    const info = parentTree(tree, extra.triggerValue);
    if (checkedKeys?.length > selectCityTree.length) {
      // console.log(parentTree(tree,extra.triggerValue))
      // 新增
      request({
        url: '/api/admin/city/add',
        method: 'POST',
        data: {
          cityId: info.value,
          name: info.title,
          parentid: info.parentid,
        },
        // action: 'select',
      }).then(data => {
        getCityList();
        message.success('新增成功')
        // console.log(getTree(data.tdCityList), 'data.tdCityList');
        // setTree(getTree(data.tdCityList));
      });
    } else {
      Modal.confirm({
        title: '确认是否关闭该城市?',
        // content: 'Some descriptions',
        onOk() {
          console.log('OK');
          request({
            url: `/api/admin/org/city/${extra.triggerValue}`,
            method: 'DELETE',

            // action: 'select',
          }).then(data => {
            getCityList();
            message.success('修改成功')
            // console.log(getTree(data.tdCityList), 'data.tdCityList');
            // setTree(getTree(data.tdCityList));
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }

    console.log('onCheck', checkedKeys, label, extra);
  };

  const tProps = {
    treeData: tree,
    value: selectCityTree,
    // onSelect:onChange,
    onChange: onChange,
    treeCheckable: true,
    // multiple:true,
    showCheckedStrategy: SHOW_CHILD,
    searchPlaceholder: '请选择',
    // labelInValue: true,
    style: {
      width: '100%',
    },
    loading:loading
  };

  useEffect(() => {
    getAllCityList();
    getCityList();
  }, []);

  return (
    <Card>
      <div style={{ display: 'flex' }}>
        <TreeSelect {...tProps} />
      </div>

      {/* <Tree
        checkable
        // 展开指定节点
        // expandedKeys={selectProvinceTree}
        // 选择节点,但同时会包含父节点
        checkedKeys={selectCityTree}
        //  defaultSelectedKeys={['420100']}
        onSelect={onSelect}
        onCheck={onCheck}
      >
        <TreeNode title="全部">
          {tree.map(item => (
            <TreeNode title={item.name} key={item.id}>
              {item.children.map(itemCity => (
                <TreeNode
                  title={<span style={{ color: '#1890ff' }}>{itemCity.name}</span>}
                  key={itemCity.id}
                />
              ))}
            </TreeNode>
          ))}
        </TreeNode>
      </Tree> */}
    </Card>
  );
};
export default CitySelect;
