import { PlusOutlined } from '@ant-design/icons';
import { Card, Tree, Button, message, Input, Drawer, Divider } 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 ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import { add, getpage, gettree, DelStoreFoodMenu } from './service';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  if (fields.FoodMenuId == undefined) {
    message.error('请选择菜谱');
    return false;
  }
  const hide = message.loading('正在添加');
  try {
    add({ ...fields }).then((r) => {
      if (!r.succeeded) {
        message.error(r.errors);
        hide();
        return false;
      } else {
        hide();
        message.success('添加成功');
        return true;
      }
    });
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows,FoodMenuId) => {
  debugger
  try {
    const hide =  message.loading('正在删除');
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    debugger
    await DelStoreFoodMenu({
      "storeIds": ids,
      "foodMenuId": FoodMenuId
    }).then((r) => {
      hide();
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.success('删除失败');
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};
const TableList = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [treeData, setTreeData] = useState();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  const [FoodMenuId, setKey] = useState();
  /** 国际化配置 */
  useEffect(() => {
    function initfranchiseeType() {
      gettree().then((r) => {
        setTreeData(r.data);
      });
    }
    initfranchiseeType();
  }, []);
  const columns = [
    {
      title: '店铺名称',
      dataIndex: 'name',
      search:false
    }
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="店铺列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Card title="菜谱列表">
              <Tree defaultExpandAll={true} onSelect={(e) => setKey(e[0])} treeData={treeData} />
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 选择店铺
          </Button>,
        ]}
        params={{
          FoodMenuId,
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;

          await getpage(params).then((r) => {
            UserData = r.data.data;
            total = r.data.total;
          });
          return {
            data: UserData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState,FoodMenuId);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onSubmit={async (value) => {

          if (typeof (FoodMenuId) == undefined) {
            handleModalVisible(false);
          } else {
            const defaultData = [];
            value.map((data) => {
              defaultData.push({ StoreId: data.id });
            });
            const valuejson = { FoodMenuId: FoodMenuId, StoreIds: defaultData }
            var success = false;
            success = await handleAdd(valuejson);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }


        }}
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        values={FoodMenuId}
      />
    </PageContainer>
  );
};

export default TableList;
