
import { Modal,Button, message,Popconfirm,Typography    } from 'antd';
import React, { useState, useRef,useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { GetWarehousetemplatePage, WarehousetemplateAdd, WarehousetemplateDel, WarehousetemplateUpdate,Getdevice,GetBatching } from "./services"

const key = 'message';
const { Paragraph, Text } = Typography;
const GoodsTypeManage = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [devicedata, setdevicedata] = useState([]);
  const [devicevalueEnumdata, setdevicevalueEnumdata] = useState([]);
  const [matedata, setMatedata] = useState([]);
  useEffect(() => {
    Getdevice().then((r)=>{
      let list = {};
      r.data.forEach((item) => {
        list[item.id] = { text: item.name };
      })
      setdevicevalueEnumdata(list)
        setdevicedata(r.data)
    })
   
    GetBatching().then((r) => {
        setMatedata(r.data);
    });
    
  },[])
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
      title: '模板名称',
      dataIndex: 'templateName',
      valueType: 'textarea',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      valueEnum:devicevalueEnumdata
    },
    {
      title: '仓位数',
      dataIndex: 'productNumber',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 450,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }} > 更新</a>,
              <Popconfirm
              type="primary"
              key="primary"
              title="确认删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                WarehousetemplateDel([record.id]).then((r) => {
  
                  message.success('删除成功，即将刷新');
                  actionRef.current.reloadAndRest();
                });
              }}
              onCancel={() => { }}
            >
              <a href="#">删除</a>
            </Popconfirm>,
             
      ],
    },
  ];
  //添加
  const handleAdd = async (fields) => {
    try {
      await WarehousetemplateAdd(JSON.stringify(fields)).then((r) => {
        if (r.succeeded) {
          message.success('添加成功');
          actionRef.current.reload();
          handleModalVisible(false);
        } else {
          message.error(r.errors);
        }
      });
    } catch (error) {
      message.error('添加失败请重试！');
      
    }
  };
  
  
  //修改
  const handleUpdate = async (fields) => {
    try {
      message.loading('正在修改', key);
      message.destroy(key);
      await WarehousetemplateUpdate(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.succeeded) {
          message.success('修改成功',);
          actionRef.current.reload();
          handleModalVisible(false);
        } else {
          message.error(r.errors);
        }
      });
    } catch (error) {
      message.error('修改失败请重试！');
    }
  };
  
  
  //删除
  const handleRemove = async (selectedRows) => {
    try {
      message.loading('正在删除');
      let ids = [];
      selectedRows.forEach((item) => {
        ids.push(item.id);
      });
      await WarehousetemplateDel(ids).then((r) => {
        if (r.data) {
          message.success('删除成功');
          actionRef.current.reload();
          return true;
        } else {
          message.error(r.errors);
          return false;
        }
      });
    } catch (error) {
      message.error('删除失败请重试！');
      return false;
    }
  };
  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }} >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetWarehousetemplatePage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            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
        handleAdd={async (value) => {
          var success = false;
          if (value.id) {
             handleUpdate(value);
          } else {
            handleAdd(value);
          }
          
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
        devicedata={devicedata}
        matedata={matedata}
      />
    </PageContainer>
  );
};

export default GoodsTypeManage;
