import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Select,Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import Enumerable from 'linq';
import CreateForm from './components/CreateForm';
import api from './service';

const Prefix = "Menu";
const menuManager = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  /** 分布更新窗口的弹窗 */
  const [stepFormValues, setStepFormValues] = useState({});
  /*绑定数据 */
  const actionRef = useRef();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  const [treeData, setTreeData] = useState();

  const [handlData, setHandlData] = useState();
/**
 * 添加节点
 *
 * @param fields
 */

 const handleAdd = async (fields) => {
  // fields.type=fields.type.join(',');
    await api.add({ ...fields }).then((r) => {
      if (r.succeeded) {
        message.success('添加成功');
        actionRef.current.reloadAndRest();
        handleModalVisible(false);
      }else{
        message.error(r.errors);
      }
    });
  
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
    api.update(fields).then((r) => {
      if (r.succeeded) {
        message.success('更新成功');
        actionRef.current.reloadAndRest();
        handleModalVisible(false);
      }else{
        message.error(r.errors);
      }
    });
};
  const InitTree = async () => {
    await api.trees().then((r) => {
      setTreeData(r.data);
    });
  };

  useEffect(() => {
  }, [])

  const Btn = (record) => {
    var arr = [];
    arr.push(<a
      onClick={() => {
        InitTree();
        handleModalVisible(true);
      //   console.log("record.type",record.type)
      //  if(!Array.isArray(record.type)){
      //   record.type=record.type.split(',');
      //  }
        setStepFormValues(record);
      }}
    >
      更新
    </a>);
    arr.push(
    // <a
    //   onClick={() => {
    //     api.remove([record.id]).then((r) => {
    //       actionRef.current.reloadAndRest();
    //     });
    //   }}
    // >
    //   删除
    // </a>
     <Popconfirm
     type="primary"
     key="primary"
     title="删除会将子菜单一起删除，确认删除吗？"
     okText="是"
     cancelText="否"
     onConfirm={() => {
      api.remove([record.id]).then((r) => {
        if (r.succeeded) {
          message.success('操作成功');
          actionRef.current.reloadAndRest();
        }else{
          message.error(r.errors);
        }
      });
     }}
     onCancel={() => { }}
   >
     <a href="#">删除</a>
   </Popconfirm>,
    );
    return arr;
  }

  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
      ellipsis:true,
    },
    // {
    //   title: '所属平台',
    //   dataIndex: 'typeName',
      
    // },
    // {
    //   title: '所属平台',
    //   dataIndex: 'type',
    //   valueType: 'select',
    //   ellipsis:true,
    //   hideInTable: true,
    //   valueEnum: {
    //     0: {
    //       text: '团餐',
    //     },
    //     1: {
    //       text: '门店',
    //     },
    //     2: {
    //       text: '后厨',
    //     },
    //     3: {
    //       text: '公共',
    //     },
    //   },
    // },
    {
      title: '菜单编码',
      dataIndex: 'code',
      ellipsis:true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      ellipsis:true,
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      hideInSearch: true,
    },
    {
      title: '菜单路径',
      dataIndex: 'router',
      hideInSearch: true,
      ellipsis:true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => Btn(record)
    },
  ];
  return (
    <PageContainer ghost header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
      style={{marginTop: '20px'}}
        headerTitle="菜单列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return <Button
            type="primary"
            key="primary1"
            onClick={() => {
              InitTree();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>
        }}
        request={async (value) => {
          let UserData = [];
          //添加机构组织
          await api.menutreepage(value).then((r) => {
            UserData=r.data
            console.log("UserData",UserData)
          });
          return {
            data: UserData,
            success: true,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
          checkStrictly: false
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
        </FooterToolbar>

      )}
      <CreateForm
        treeDatas={treeData}
        dictData={handlData}
        onFinish={async (value) => {
          if (value.id) {
           await handleUpdate(value);
          } else {
            await handleAdd(value);
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
    </PageContainer>
  );
};

export default menuManager;
