import { PlusOutlined } from '@ant-design/icons';
import { Popconfirm, Modal, Button, message, Input, Drawer } from 'antd';
import React, { useEffect, useState, useRef } 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, Delete, GetPage } from './services';

const key = 'message';

const StockLocManager = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  //添加
  const handleAdd = async (fields) => {
    try {
      message.loading('正在添加', key);
      await Add(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('添加成功');
          actionRef.current.reload();
          return true;
        } else {
          message.error('添加失败' + r.errors);
          actionRef.current.reload();
          return false;
        }
      });
    } catch (error) {
      message.error('添加失败请重试！');
      actionRef.current.reload();
      return false;
    }
  };
  //删除
  const handleRemoveSingle = async (value) => {
    try {
      await Delete(value).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
          //刷新数据
          actionRef.current.reload();
        } else {
          message.error('删除失败，请重试');
          actionRef.current.reload();
        }
      });
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
      actionRef.current.reload();
    }
  };
  //修改
  const handleUpdate = async (fields) => {
    try {
      message.loading('正在修改', key);
      message.destroy(key);
      fields.DeviceId = props.values.key;
      await Update(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
          return true;
        } else {
          message.error('修改失败' + r.errors);
          return false;
        }
      });
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '库位值',
      dataIndex: 'loc',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            handleRemoveSingle(record);
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title={(props.values == undefined ? '' : props.values.value) + '库存位置设置'}
      search={false}
      visible={props.createModalVisible}
      footer={false}
      onCancel={() => props.onCancel()}
      maskClosable={false}
    >
      <PageContainer
        header={{
          title: '',
          breadcrumb: {},
        }}
      >
        <ProTable
          headerTitle=""
          actionRef={actionRef}
          rowKey="id"
          search={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 添加设备库存位置
            </Button>
          ]}
          request={async (params) => {
            var data = [];
            var total = 0;
            await GetPage(props.values.id).then((r) => {
              data = r.data;
              total = 0;
            });
            return {
              data: data,
              success: true,
              total: total,
            };
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />

        <CreateForm
          onFinish={async (value) => {
            value.id = props.values.id;
            var success = false;
            success = handleAdd(value);
            if (success) {
              handleModalVisible(false);
              setCurrentRow(undefined);
              actionRef.current.reload();
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }}
          createModalVisible={createModalVisible}
          values={currentRow || {}}
        />
      </PageContainer>
    </Modal>
  );
};

export default StockLocManager;
