import { Button, Modal, Form, Input, Drawer, Popconfirm, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import api from './service';
import { message } from 'antd/lib';
const app = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [current, setCurrent] = useState({});
  const [orgTree, setOrgTree] = useState([]);
  const [orgList, setOrgList] = useState([]);
  const [orgList2, setOrgList2] = useState([]);

  const [form] = Form.useForm();
  //绑定
  const actionRef = useRef();
  
  useEffect( () => {
     const initTypeList = async (value) => {
      var data = await api.GetOrgList({ "pid": "" });
      var list = [];
      if (data.statusCode == 200) {
        data.data.forEach((item) => {
          list.push({ id: item.id, text: item.name, value: item.id, label: item.name });
        });
      }
      
      setOrgList2(list);
     
    };
    initTypeList();
    GetOrgtree();
    GetOrgList();
  }, []);

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '所属组织',
      dataIndex: 'orgId',
      valueType: 'select',
      fieldProps: {
        options: orgList2,
      },
    },
    // {
    //   title: '所属组织',
    //   dataIndex: 'orgId',
    //   valueType: 'select',
    //   render: (_, record) => {
    //     const find = orgList.find(item => item.id === record.orgId);
    //     return <div>
    //       {find ? find.name : record.orgId}
    //     </div>
    //   }
    // },
    {
      title: '场景名称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      key: 'operation',
      fixed: 'right',
      width: 150,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setIsModalOpen(true);
            setCurrent(record);
            form.setFieldsValue(record);
          }}
        >
          更新
        </a>,
        <Popconfirm
          key="delete"
          title={`确定要删除吗？`}
          onConfirm={async () => {
            var res = await api.Del(record.id);
            if (res.data) {
              message.success('删除成功');
              actionRef.current.reloadAndRest();
            } else {
              message.error(response.errors ||'删除失败');
            }
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>
      ],
    },
  ];


  //获取组织树
  const GetOrgtree = async () => {
    const response = await api.GetOrgtree();
    if (response.statusCode == 200) {
      setOrgTree(response.data);
    }
  }

  //获取组列表
  const GetOrgList = async () => {
    const response = await api.GetOrgList({ "pid": "" });
    if (response.statusCode == 200) {
      setOrgList(response.data);
    }
  }

  const onOk = async () => {
    if (current.id) {
      var res = await api.Update(form.getFieldsValue());
      if (res.data) {
        message.success('修改成功');
        actionRef.current.reloadAndRest();
        setIsModalOpen(false);
        form.resetFields();
      } else {
        message.error(res.errors||"修改失败");
      }

    } else {
      var res = await api.Add(form.getFieldsValue());
      if (res.data) {
        message.success('新增成功');
        actionRef.current.reloadAndRest();
        setIsModalOpen(false);
        form.resetFields();
      } else {
        message.error(res.errors||"新增失败");
      }

    }

  }

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };



  return (
    <div>
      <PageContainer  header={{
      title: '',
      breadcrumb: {},
    }}>
        <ProTable
          columns={columns}
          actionRef={actionRef}
          rowKey="id"
          pagination={{
            pageSize: 10
          }}
          scroll={{
            x: 1300,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setIsModalOpen(true);
                setCurrent({});
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          //数据绑定
          request={async (params) => {
            var res = await api.Page(params);
            var datas = res.data.data;
            var total = res.data.total;
            return {
              data: datas,
              success: true,
              total: total,
            };
          }}

        ></ProTable>
      </PageContainer>



      <Modal width={600} title={current.id ? "更新" : "新增"} open={isModalOpen} onOk={form.submit} onCancel={() => { form.resetFields(); setIsModalOpen(false); }}>


        <Form
          name="basic"
          form={form} 
          onFinish={onOk}
          labelCol={{ span: 4 }}
        >

          <Form.Item name="id" label="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item name="orgId" label="所属组织" rules={[{ required: true,message: '请选择所属组织' }]}>
            <TreeSelect
              style={{ width: '100%' }}
              // dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={orgTree}
              placeholder="请选择所属组织"
              treeDefaultExpandAll
            />
          </Form.Item>
          <Form.Item name="name" label="场景名称" rules={[{ required: true,max:20 }]}>
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="电话" rules={[{ required: true,max:20 }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>

  );
};

export default app;
