import { Button, Modal, Form, Input, Drawer, Popconfirm, TreeSelect, Card, Descriptions, Divider } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import api from './service';
import { message } from 'antd/lib';
const app = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOrderModalOpen, setIsOrderModalOpen] = useState(false);
  const [form] = Form.useForm();
  //绑定
  const actionRef = useRef();
  const [current, setCurrent] = useState({});
  const [data, setData] = useState({});
  const [dataGoods, setDataGoods] = useState([]);
  const [dataDiningPlate, setDataDiningPlate] = useState([]);
  const [unbindOccupyData, setUnbindOccupyData] = useState([]);


  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '二维码',
      dataIndex: 'qrCode',
      ellipsis: {
        showTitle: false,
      },
      valueType: 'textarea',
    },
    {
      title: '芯片码',
      dataIndex: 'chipCode',
      ellipsis: {
        showTitle: false,
      },
      valueType: 'textarea',
    },
    {
      title: '是否收费',
      dataIndex: 'isPay',
      ellipsis: {
        showTitle: false,
      },
      search: false,
      valueEnum: {
        false: {
          text: '免费',
          status: 'Processing',
        },
        true: {
          text: '收费',
          status: 'Success',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Success',
        },
      },
    },
    {
      title: '是否绑定',
      dataIndex: 'isOccupy',
      valueEnum: {
        false: {
          text: '未绑定',
          status: 'Processing',
        },
        true: {
          text: '已绑定',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            form.setFieldsValue(record);
            setCurrent(record);
            setIsModalOpen(true);
          }}
        >
          更新
        </a>,
        <a
          key="config"
          onClick={() => {
            api.EnableDisable(record).then((re) => {
              if (re.data) {
                message.success('成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(re.errors || '失败');
              }
            });

          }}
        >
          {record.status == 0 ? "停用" : "正常"}
        </a>,
        <Popconfirm
          key="delete"
          title={`确定要删除吗？`}
          onConfirm={async () => {
            api.Del(record.id).then((re) => {
              if (re.data) {
                message.success('删除成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(re.errors || '修改失败');
              }
            });
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
        <a
          key="config"
          disabled={!record.isOccupy}
          onClick={() => {
            setIsOrderModalOpen(true);
            if (!record.isOccupy) {
              return;
            }

            api.GetWeighOrderByOrderId({ "orderId": record.weighOrderId })
              .then((res) => {
                if (res.statusCode == 200) {
                  setData(res.data);
                  setDataGoods(res.data.goodsInfo);
                  setDataDiningPlate(res.data.diningPlateInfo);
                }

              })
            var data = [];
            data.push({ diningPlateId: record.id, weighOrderId: record.weighOrderId });
            setUnbindOccupyData(data);


          }}
        >
          解绑
        </a>
      ],
    },
  ];

  const goodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
    },
    {
      title: '重量',
      dataIndex: 'goodsWeight',
      key: 'goodsWeight',
    },
    {
      title: '价格',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
    }
  ];

  const diningPlateColumns = [
    {
      title: '二维码',
      dataIndex: 'qrCode',
      key: 'qrCode',
    },
    {
      title: '芯片码',
      dataIndex: 'chipCode',
      key: 'chipCode',
    }
  ];


  return (
    <>
      <PageContainer header={{ title: '', breadcrumb: {} }}>
        <ProTable
          columns={columns}
          actionRef={actionRef}
          rowKey="id"
          pagination={{
            pageSize: 10
          }}
          scroll={{
            x: 1300,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrent({});
                form.setFieldsValue({ id: "", qrCode: "", chipCode: "" });
                setIsModalOpen(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ]}
          //数据绑定
          request={async (params) => {
            if (params.status) {
              params.status = Number(params.status)
            }
            var res = await api.Page(params);
            var datas = res.data.data;
            var total = res.data.total;
            return {
              data: datas,
              success: true,
              total: total,
            };
          }}></ProTable>

        {/* 餐盘管理 */}
        <Modal
          title={current.id ? "修改" : "新增"}
          width={600}
          open={isModalOpen}
          onOk={() => {
            form.submit();
          }}
          onCancel={() => {
            setIsModalOpen(false);
          }}>
          <Form
            form={form}
            labelCol={{ span: 4, }}
            wrapperCol={{ span: 16, }}
            style={{ maxWidth: 600, }}
            initialValues={{ remember: true }}
            onFinish={(value) => {
              if (value.id) {
                api.Update(value).then((re) => {
                  if (re.data) {
                    message.success('修改成功');
                    setIsModalOpen(false);
                    actionRef.current.reloadAndRest();
                  } else {
                    message.error(re.errors || '修改失败');
                  }
                });
              } else {
                api.Add(value).then((re) => {
                  if (re.data) {
                    setIsModalOpen(false);
                    message.success('添加成功');
                    actionRef.current.reloadAndRest();
                  } else {
                    message.error(re.errors || '添加失败');
                  }
                });
              }


            }}
            onFinishFailed={() => { }}
            autoComplete="off" >

            <Form.Item name="id" label="id" hidden>
              <Input />
            </Form.Item>
            <Form.Item label="二维码" name="qrCode"
              rules={[{ required: true, message: '二维码不能为空', },]}>
              <Input />
            </Form.Item>
            <Form.Item label="芯片码" name="chipCode"
              rules={[{ required: true, message: '芯片码不能为空', },]}>
              <Input />
            </Form.Item>
          </Form>
        </Modal>

        {/* 绑定订单 */}
        <Modal
          title={"解绑餐盘"}
          width={800}
          open={isOrderModalOpen}
          onOk={() => {
            api.UnbindOccupy(unbindOccupyData).then((re) => {
              if (re.data) {
                message.success('解绑成功');
                actionRef.current.reloadAndRest();
                setIsOrderModalOpen(false);
              } else {
                message.error(re.errors || '解绑失败');
              }
            });
          }}
          onCancel={() => {
            setIsOrderModalOpen(false);
          }} >
          <Card bordered={false}>
            <Descriptions
              title="订单信息"
              style={{
                marginBottom: 32,
              }}
            >
              <Descriptions.Item label="订单编号">{data.orderNumber}</Descriptions.Item>
              <Descriptions.Item label="OpenId">{data.createId}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{data.states == 0 ? "选菜中" : "已完成"}</Descriptions.Item>
              <Descriptions.Item label="支付状态">{data.payStates == 0 ? "待支付" : "已支付"}</Descriptions.Item>
              <Descriptions.Item label="总额">{data.totalAmount}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{data.createAt}</Descriptions.Item>
            </Descriptions>
            <Divider
              style={{
                marginBottom: 32,
              }}
            />
            <div >餐盘信息</div>
            <ProTable
              style={{
                marginBottom: 24,
              }}
              pagination={false}
              search={false}
              options={false}
              toolBarRender={false}
              dataSource={dataDiningPlate}
              columns={diningPlateColumns}
              rowKey="id"
            />
            <div >商品信息</div>
            <ProTable
              style={{
                marginBottom: 24,
              }}
              pagination={false}
              search={false}
              options={false}
              toolBarRender={false}
              dataSource={dataGoods}
              columns={goodsColumns}
              rowKey="id"
            />
          </Card>


        </Modal>
      </PageContainer>
    </>

  );
};

export default app;
