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, DelDeviceBOM } from './service';
import DeviceStock from '../deviceRecipeStock';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields }).then((r) => {
      if (!r.succeeded) {
        message.error(r.errors);
        return false;
      }
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows) => {
  try {
    message.loading('正在删除');
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await DelDeviceBOM(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.error('删除失败');
        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 [stockModalVisible, setStockModalVisible] = useState(false);

  const [DeviceInfo, setDeviceInfo] = useState();
  const [DeviceId, setKey] = useState();
  const [type, setType] = useState();
  const [bom, setBom] = 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,info) => [
                setKey(e[0]),
                setType(info.node.type),
                setDeviceInfo(info.node)
              ]
              } treeData={treeData} />
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 上架配方
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setStockModalVisible(true);
            }}
          >
            设备库存管理
          </Button>,
        ]}
        params={{
          DeviceId,
          type
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;

          await getpage(params).then((r) => {
            UserData = r.data.data;
            setBom(UserData);
            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);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onSubmit={async (value) => {

          if (DeviceId== undefined) {
            message.error('请选择设备');
            handleModalVisible(false);
          } else {
            const defaultData = [];
            value.map((data) => {

              defaultData.push({ BOMId: data.id });
            });
            const valuejson = { DeviceId: DeviceId,type:type, Boms: defaultData }
            var success = false;
            success = await handleAdd(valuejson);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }


        }}
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        values={DeviceId}
        type ={type}
      />
      {/* 库存调拨 */}
      <DeviceStock
        onCancel={() => {
          setStockModalVisible(false);
        }}
        stockModalVisible={stockModalVisible}
        values={DeviceInfo}
        isbom={true}
        bomIds={bom.map(x=>x.id)}
      />
    </PageContainer>
  );
};

export default TableList;
