import { PlusOutlined } from '@ant-design/icons';
import { Tabs, Card, Pagination, Table, message, Button, Popconfirm, Modal } from 'antd';
const { TabPane } = Tabs;
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { GetStoreInfoPage, GetStoreGoods, AddStoreGood, UpdateStoreGoods, DelStoreGoods, UpdateStoreGoodsStatusAsync, stopgoods,StoreGoodsAllUpdate  } from "./services"
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import LogForm from './components/Logs';
import { UnorderedListOutlined } from '@ant-design/icons';
import { history } from 'umi';
const key = 'message';

//修改
const handleUpdate = async (fields) => {
  try {
    message.loading('正在修改', key);
    message.destroy(key);
    await UpdateStoreGoods(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 DelStoreGoods(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 storeGoodsInfo = (props) => {
  const actionLogRef = useRef();
  const [dataLsit, SetDataLsit] = useState([]);
  const [total, SetTotal] = useState(0);
  const [loading, SetLoading] = useState(false);
  const [storeId, SetstoreId] = useState();

  const [createModalVisible, handleModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState();
  const [currentTabRow, setCurrentTabRow] = useState();
  const actionRef = useRef();
  const [logVisible, SetLogVisible] = useState(false);

  useEffect(() => {
    getStoreInfoPageInfo(1);
  }, [])

  const [goods, setGoods] = useState([]);
  //初始化数据
  //添加
  const handleAdd = async (fields) => {
    try {
      fields.store_Id = currentTabRow;
      message.loading('正在添加', key);
      await AddStoreGood(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 getStoreInfoPageInfo = async (page) => {
    SetLoading(true);
    try {
      await GetStoreInfoPage({ current: page, pageSize: 10 }).then((r) => {
        SetTotal(1);
        SetDataLsit(r.data);
        SetLoading(false);
      });
    } catch {
      SetLoading(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: 'vipPrice',
      valueType: 'money',

    },

    {
      title: '是否设备制作',
      dataIndex: 'isDevice',
      valueEnum: {
        0: { text: '店铺', status: 'Processing' },
        1: { text: '设备', status: 'Success' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '上架', status: 'Processing' },
        1: { text: '下架', status: 'Success' },
      },
    },
    {
      title: '估清',
      dataIndex: 'stopSales',
      valueEnum: {
        0: { text: '销售', status: 'Processing' },
        1: { text: '估清', status: 'Success' },
      },
      // render: (record) => {
      //   const showText = record.stopSalesTime === null ? '估清' : '销售';
      //   return (
      //     <span>
      //       {showText}
      //     </span>
      //   )
      // }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          {' '}
          更新
        </a>,
        <a
          key="primary"
          onClick={() => {
            var stopSales = 0;
            if (record.stopSales == 0)
              stopSales = 1;
            else
              stopSales = 0;
            var goodss = [{ goodsId: record.foodId, storeId: storeId, StopSales: stopSales }];
            stopgoods(goodss).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.stopSales == 0 ? '估清' : '销售'}
        </a>,
        <a
          key="primary"
          onClick={() => {
            record.status = record.status == 0 ? 1 : 0;
            UpdateStoreGoodsStatusAsync(record).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.status == 0 ? '停用' : '正常'}
        </a>,
        <a
          key="primary"
          onClick={() => {
            record.isDevice = record.isDevice == 0 ? 1 : 0;
            UpdateStoreGoodsStatusAsync(record).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.isDevice == 0 ? '设备制作' : '门店制作'}
        </a>,
        <a
          key="config"
          onClick={() => {
            history.push({
              pathname: '/store/storeAddGoodsInfo',
              query: {
                isAdd: false,
                values: record,
                storeId: storeId
              },
            });
          }}
        >
          加购商品
        </a>,
      ],
    },
  ];


  return (
    <PageContainer>
      <Card ></Card>
      <Card headStyle={{ border: '0px ' }} title="店铺商品" style={{ marginTop: '17px' }}>
        <Tabs defaultActiveKey="1" tabPosition="left" onChange={(key) => {
          setCurrentTabRow(key);
        }}>
          {dataLsit?.map((item) => {
            return (
              <TabPane tab={item.name}
                key={item.id}>
                <ProTable
                  headerTitle=""
                  actionRef={actionRef}
                  rowKey="id"
                  search={false}
                  toolBarRender={() => [
                    <Popconfirm
                      type="primary"
                      key="primary"
                      title="确认估清门店所有商品"
                      okText="是"
                      cancelText="否"
                      onConfirm={() => {
                        StoreGoodsAllUpdate({ StoreId: item.id, UpdateType: 0 })
                        actionRef.current.reload();
                      }}
                      onCancel={() => { }}
                    >
                      <Button type="primary" key="primary"> 估清</Button>
                    </Popconfirm>,
                    <Popconfirm
                      type="primary"
                      key="primary"
                      title="确认停用门店所有商品"
                      okText="是"
                      cancelText="否"
                      onConfirm={() => {
                        StoreGoodsAllUpdate({ StoreId: item.id, UpdateType: 1 })
                        actionRef.current.reload();
                      }}
                      onCancel={() => { }}
                    >
                      <Button type="primary" key="primary"> 停用</Button>
                    </Popconfirm>,
                    <Popconfirm
                      type="primary"
                      key="primary"
                      title="确认修改门店所有商品制作状态"
                      okText="是"
                      cancelText="否"
                      onConfirm={() => {
                        StoreGoodsAllUpdate({ StoreId: item.id, UpdateType: 2 })
                        actionRef.current.reload();
                      }}
                      onCancel={() => { }}
                    >
                      <Button type="primary" key="primary"> 门店制作</Button>
                    </Popconfirm>,
                  ]}
                  loading={loading}
                  bordered
                  columns={columns}
                  key={item.id}
                  request={async (params) => {
                    var data = [];
                    var total = 0;
                    SetstoreId(item.id)
                    params.StoreId = item.id;
                    await GetStoreGoods(params).then((r) => {
                      data = r.data?.data;
                      total = r.data?.total;
                    });
                    return {
                      data: data,
                      success: true,
                      total: total,
                    };
                  }}
                />
              </TabPane>
            );

          })}
        </Tabs>
        <Pagination
          size='small'
          style={{ float: 'right' }}
          total={total}
          onChange={(page, pageSize) => { getStoreInfoPageInfo(page) }}
          showTotal={(total, range) => `总共 ${total} 条`}
          defaultPageSize={10}
          defaultCurrent={1}
        />
      </Card>

      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            value.store_Id = currentTabRow;
            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 || {}}
      />

      <Modal
        destroyOnClose={true}
        width={800}
        visible={logVisible}
        footer={null}
        onCancel={() => {
          SetLogVisible(false);
        }}>
        <LogForm
          storeId={currentTabRow}
          actionLogRef={actionLogRef}
        />
      </Modal>


    </PageContainer>);
};

export default storeGoodsInfo;
