
import { Modal,Button, message,Popconfirm,Typography    } from 'antd';
import React, { useState, useRef } 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 { GetProductPage, AddProduct, DelProduct, UpdateProduct,UpdateStatus } 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 columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '产品标识',
      dataIndex: 'code',
      valueType: 'textarea',
    },
    {
      title: '产品key',
      dataIndex: 'key',
      valueType: 'textarea',
      render: (text) => <Paragraph style={{display:'inline'}} copyable>{text}</Paragraph>,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      width: 450,
    },
    
    {
      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={() => {
                DelProduct([record.id]).then((r) => {
  
                  message.success('删除成功，即将刷新');
                  actionRef.current.reloadAndRest();
                });
              }}
              onCancel={() => { }}
            >
              <a href="#">删除</a>
            </Popconfirm>,
             
      ],
    },
  ];
  //添加
  const handleAdd = async (fields) => {
    try {
      message.loading('正在添加', key);
      await AddProduct(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.succeeded) {
          message.success('添加成功');
          actionRef.current.reloadAndRest();
          return true;
        } else {
          message.error(r.errors);
          return false;
        }
      });
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  };
  
  
  //修改
  const handleUpdate = async (fields) => {
    try {
      message.loading('正在修改', key);
      message.destroy(key);
      await UpdateProduct(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.succeeded) {
          message.success('修改成功',);
          actionRef.current.reloadAndRest();
          return true;
        } else {
          message.error(r.errors);
          return false;
        }
      });
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  };
  
  
  //删除
  const handleRemove = async (selectedRows) => {
    try {
      message.loading('正在删除');
      let ids = [];
      selectedRows.forEach((item) => {
        ids.push(item.id);
      });
      await DelProduct(ids).then((r) => {
        if (r.data) {
          message.success('删除成功');
          actionRef.current.reloadAndRest();
          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 GetProductPage(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
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = handleUpdate(value);
          } else {
            success = handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }
          actionRef.current.reloadAndRest();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default GoodsTypeManage;
