import { DropboxOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, message, Select, Input, Drawer, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } 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 ExportJsonExcel from 'js-export-excel';
import api from './service';
import OrderflowDetail from './orderflowDetail';

const handlerefund = async (value) => {
  var data = { number: value };
  const hide = message.loading('正在发起退款');
  try {
    api.StartRefund(data);
    hide();
    message.success('发起退款成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('发起退款失败，请重试');
    return false;
  }
};
const Manage = () => {
  const [row, setRow] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  //获取店铺(店铺信息)
  const [srdList, setsrdList] = useState([]);
  const [dataList, setdataList] = useState([]);
  //绑定
  const actionRef = useRef();
  const [Selectparams, setparams] = useState([]);
  // 获取店铺分类、商品名称信息
  useEffect(() => {
    //店铺名称（店铺信息）
    function initsrdList() {
      api.srdList().then((r) => {
        var arr = r.data;
        arr?.forEach((element) => {
          element.value = element.id;
          element.label = element.name;
        });
        setsrdList(arr);
      });
    }

    initsrdList();
  }, []);
  /**导出 */
  function handleExport() {
    api.GetFlowExport(Selectparams).then((res) => {
      let url = URL.createObjectURL(new Blob([res]));
      let filename = '订单流水.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  }
  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '订单时间',
      dataIndex: 'order_CreateTime',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            order_CreateTime: value[0],
            order_EndTime: value[1],
          };
        },
      },
    },
    {
      title: '手机号',
      dataIndex: 'Customer_Tel',
      hideInTable: true,
    },
    {
      title: '店铺名称',
      dataIndex: 'storeId',
      hideInTable: true,
      valueType: 'select',
      renderFormItem: () => (
        <Select
          mode="multiple"
          showArrow
          optionFilterProp="label"
          placeholder="请选择店铺"
          style={{ width: '100%' }}
          options={srdList}
        />
      ),
    },
    {
      title: '交易单号',
      dataIndex: 'order_Number',
      hideInSearch: true,
    },

    {
      title: '店铺名称',
      dataIndex: 'storeName',
      hideInSearch: true,
    },

    {
      title: '应付金额',
      dataIndex: 'order_OriginalMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '实付金额',
      dataIndex: 'order_RealMoney',
      hideInSearch: true,
      renderText: (val) => `${val}¥`,
    },
    {
      title: '应付金额(退)',
      dataIndex: 'refundOriginalMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '实付金额(退)',
      dataIndex: 'refundRealMoney',
      hideInSearch: true,
      renderText: (val) => `${val}¥`,
    },
    {
      title: '数量',
      dataIndex: 'order_Count',
      hideInSearch: true,
    },
    {
      title: '支付类型',
      dataIndex: 'payMode',
      valueEnum: {
        0: {
          text: '微信支付',
        },
        1: {
          text: '支付宝',
        },
        2: {
          text: '余额',
        },
        3: {
          text: '银联',
        },
        4: {
          text: '现金',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'order_CreateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const status = form.getFieldValue('status');

        if (`${status}` === '0') {
          return false;
        }

        if (`${status}` === '3') {
          return <Input {...rest} placeholder="请输入异常原因！" />;
        }

        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setRow(record), handleModalVisible(true);
          }}
        >
          查看详情
        </a>,
        // <a
        //   key="config"
        //   onClick={() => {
        //     api.printsmallticket({ "orderId": record.id })
        //       .then(re => {
        //         if (re.data) {
        //           message.success('打印成功');
        //         } else {
        //           message.error('打印失败');
        //         }

        //       })

        //   }} >
        //   打印小票
        // </a>,
      ],
    },
  ];

  //下载Excel
  const onDownloadExcel =  async () => {
    const response = await api.GetFlowExport(Selectparams)
    if (response.isSuccess) {
        let option = {};  //option代表的就是excel文件
        const date = new Date();
        const excelName = "订单流水" + date.toLocaleString().replaceAll('\/', '-');
        option.fileName = excelName;  //excel文件名称
        const sheetHeader = ['storeTypeName','storeName','order_Number','order_OriginalMoney','order_RealMoney','refundOriginalMoney','refundRealMoney','order_Count','order_CreateTime'];;
        // Object.keys(response.data[0]).forEach(item => {
        //     sheetHeader.push(item);
        // });
        option.datas = [
            {
                sheetData: response.data,            //excel文件中的数据源
                sheetName: excelName,       //excel文件中sheet页名称
                sheetFilter: sheetHeader,   //excel文件中需显示的列数据
                sheetHeader: ['店铺分类', '店铺名称', '交易单号', '应付金额', '实付金额',
                    '应付金额(退)', '实付金额(退)', '子订单数量', '创建时间',
                ]    //excel文件中每列的表头名称
            }
        ]
        let toExcel = new ExportJsonExcel(option);  //生成excel文件
        toExcel.saveExcel();
    } else {
        message.error(response.errors || '导出失败');
    }
}

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="订单流水"
        actionRef={actionRef}
        rowKey="orderFlowId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          // <Button type="primary" key="create" onClick={onDownloadExcel}>
          //   <DownloadOutlined /> 导出
          // </Button>,
        ]}
        columns={columns}
        //数据绑定
        request={async (params, sorter, filter) => {
          if (params.storeTypeId != undefined) {
            //店铺分类
            params.storeTypeId = srdTypeList[params.storeTypeId].storeTypeId;
          }
          const msg = await api.orderList(params);
          setparams(params);
          setdataList(msg.data.data);
          return {
            data: msg.data.data,
            success: true,
            total: msg.data.total,
          };
        }}
      ></ProTable>

      {!!row && (
        <OrderflowDetail
          // onFinish={async (value) => {
          //   var success = false;

          // }}
          onCancel={() => {
            setRow(undefined);
            handleModalVisible(false);
          }}
          createModalVisible={createModalVisible}
          values={row || {}}
        />
      )}
    </PageContainer>
  );
};

export default Manage;
