import { PlusOutlined } from '@ant-design/icons';
import { Tabs, message, Button } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { AddAsync, UpdateAsync, DelAsync, GetPageAsync } from "./services"
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';

const key = 'message';

//添加
const handleAdd = async (fields) => {
  try {
    message.loading('正在添加', key);
    await AddAsync(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('添加成功');
        return true;
      } else {
        message.error('添加失败');
        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 DelAsync(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.success('删除失败');
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};
const storeAddGoodsInfo = (props) => {
  /** 新建/更新窗口的弹窗 */
  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: 'price',
      valueType: 'money',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '启用', status: 'Processing' },
        1: { text: '停用', status: 'Success' },
      },
    },
    //   {
    //     title: '操作',
    //     dataIndex: 'option',
    //     valueType: 'option',
    //     render: (_, record) => [
    //       <a
    //         key="primary"
    //         onClick={() => {
    //           record.status = record.status == 0 ? 1 : 0;
    //           UpdateAsync(record).then((r) => {
    //             if (r.data) {
    //               actionRef.current.reload();
    //             }
    //           });
    //         }}
    //       >
    //         {' '}
    //         {record.status == 0 ? '停用' : '正常'}
    //       </a>
    //     ],
    //   },
  ];

  return (
    <PageContainer>
      <ProTable
        search={false}
        headerTitle={(props.location.query.values.goods_Name ? props.location.query.values.goods_Name : '') + '加购商品'}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }} >
            <PlusOutlined /> 添加加购商品
          </Button>,
        ]}
        request={async (params) => {
          if (props.location.query.values.goodsId == undefined || props.location.query.values.goodsId == null) {

          } else {
            params.GoodsId = props.location.query.values.goodsId;
            params.StoreId = props.location.query.storeId;
            var total = 0;
            const msg = await GetPageAsync(params);
            return {
              data: msg.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;
              {/* <span>
                 服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
               </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        onFinish={async (value) => {
          var success = false;
          value.GoodsId = props.location.query.values.goodsId;
          value.StoreId = props.location.query.storeId;
          success = handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current.reload();
          }

          actionRef.current.reload();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default storeAddGoodsInfo;
