import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, 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 ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import ActionsEntry from './components/BomList';
import api from './services';

//页面 相当于 class
/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  try {
    api.addupdate(JSON.stringify(fields)).then((r) => {
      if (r.data) {
        message.success('添加成功');
      } else {
        message.error('添加失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
}
/**
   * 批量删除节点
   *
   * @param selectedRows
   */
const handleRemove = async (fields) => {
  try {
    api.delete(fields.id).then((r) => {
      if (r.data) {
        message.success('删除成功，即将刷新');
      } else {
        message.error('删除失败，请重试');
      }
    });
    return true;
  } catch (error) {
    message.error('删除失败，请重试');
  }
}

/**
 * 更新节点
 *
 * @param fields
 */

const handlePotUpdate = async (fields) => {
  try {
    api.UpdatePot(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.error('修改失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
}
const handleRobotUpdate = async (fields) => {
  try {
    api.UpdateRobot(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.error('修改失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
}
const handleUpdate = async (fields) => {
  try {
    api.addupdate(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.error('修改失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
}
const cookingwork = (props) => {
  const [values, setUrl] = useState(props.location.query.values ? props.location.query.values : null);
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [getActionsEntry, setActionsEntry] = useState();
  const [getIsMain, setIsMain] = useState();
  const [setActionsEntryModalVisible, handleActionsEntryModalVisible] = useState();
  // 监控数据变化
  useEffect(() => {
  }, []);

  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },

    {
      title: '步骤名称',
      dataIndex: 'fryTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '炒锅动作',
      dataIndex: 'actions',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '持续时间(秒)',
      dataIndex: 'during',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '步骤排序',
      dataIndex: 'sort',
      hideInForm: true,
      hideInSearch: true,
    },


    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
         <Popconfirm
         type="primary"
         key="primary"
         title="确认删除吗？"
         okText="是"
         cancelText="否"
         onConfirm={() => {
           handleRemove(record);
           actionRef.current?.reloadAndRest();
         }}
         onCancel={() => { }}
       >
         <a href="#">删除</a>
       </Popconfirm>,
        <a
          key="config"
          onClick={() => {
            setActionsEntry(record);
            setIsMain(false);
            handleActionsEntryModalVisible(true);
          }}
        >
          辅料设置
        </a>,
        <a
          key="config"
          onClick={() => {
            setActionsEntry(record);
            setIsMain(true);
            handleActionsEntryModalVisible(true);
          }}
        >
          主料设置
        </a>,

      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        pagination={{ defaultPageSize: 50 }}
        headerTitle={props.location.query.values.name+"小炒步骤设置"}
        actionRef={actionRef}
        rowKey="id"
        search={false}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          params.GoodsId = props.location.query.values.id;
          var data = [];
          var total = 0;
          await api.getpage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      {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>
      )}
         {getActionsEntry && Object.keys(getActionsEntry).length ? (
        <ActionsEntry
          onCancel={() => {
            handleActionsEntryModalVisible(false);
            setActionsEntry({});
          }}
          IsMain={getIsMain}
          createModalVisible={setActionsEntryModalVisible}
          values={getActionsEntry}
        />

      ) : null}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            value.goodsId = props.location.query.values.id;
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default cookingwork;
