import { PlusOutlined } from '@ant-design/icons';
import { Modal, Button, message, Input, Drawer } from 'antd';
import React, { 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 {
  GetStoreGoodsAsync,
  UpdateStoreGoodsAsync,
  UpdateStoreGoodsStatusAsync,
  AddStoreGoodAsync,
  DelStoreGoodAsync,
} from './services';

const key = 'message';

//修改
const handleUpdate = async (fields) => {
  try {
    message.loading('正在修改', key);
    message.destroy(key);
    await UpdateStoreGoodsAsync(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('修改成功');
        return true;
      } else {
        message.success('修改失败');
        return false;
      }
    });
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
};

//删除
const handleRemove = async (selectedRows) => {
  try {
    message.loading('正在删除', key);
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await DelStoreGoodAsync(ids).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.success('删除失败');
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};

const storeGoods = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 国际化配置 */

  //添加
  const handleAdd = async (fields) => {
    try {
      fields.store_Id = props.values.id;
      message.loading('正在添加', key);
      await AddStoreGoodAsync(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 columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '商品',
      dataIndex: 'goods_Name',
      valueType: 'textarea',
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      valueType: 'money',
    },
    {
      title: '状态',
      dataIndex: 'goods_Enable',
      valueEnum: {
        1: { text: '正常', status: 'Processing' },
        0: { text: '停用', status: 'Success' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInForm: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          {' '}
          更新
        </a>,
        <a
          key="primary"
          onClick={() => {
            record.goods_Enable = record.goods_Enable == 0 ? 1 : 0;
            UpdateStoreGoodsStatusAsync(record).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.goods_Enable == 0 ? '停用' : '正常'}
        </a>,
        ,
        <a
          key="config"
          onClick={() => {
            handleRemove([record]);
            actionRef.current.reload();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="商品上架"
      visible={props.storeGoodsModalVisible}
      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;
            params.StoreId = props.values.id;
            await GetStoreGoodsAsync(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);
            },
          }}
        />

        <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.reload();
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }}
          createModalVisible={createModalVisible}
          values={currentRow || {}}
        />
      </PageContainer>
    </Modal>
  );
};

export default storeGoods;
