import {
  Modal, Typography, Table, Button, Input,
  Statistic, Card, Row, Col, Space,
  DatePicker, Select
} from 'antd';

import React, { useState, useRef, useEffect, Suspense } from 'react';
import { ProFormSelect } from '@ant-design/pro-form';
import { GridContent } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import api from '../services';
import './finance.css';

const DetailManage = (props) => {
  console.log('props', props);
  const actionRef = useRef();
  const { Text } = Typography;
  const { TextArea } = Input;
  //获取店铺类型(店铺类型)
  const [srdTypeList, setsrdTypeList] = useState([]);
  //获得店铺名称(店铺名称)
  const [srdList, setsrdList] = useState([]);
  /** 流水金额*/
  const [getorderOriginalMoney, setorderOriginalMoney] = useState({});
  /** 优惠金额*/
  const [getdiscountMoney, setdiscountMoney] = useState({});
  /** 顾客实付*/
  const [getorderRealMoney, setorderRealMoney] = useState({});
  /** 平台费用*/
  const [getbusinessPrice, setbusinessPrice] = useState({});
  /** 退款金额*/
  const [getrefundMoney, setrefundMoney] = useState({});
  /** 结算金额*/
  const [getsettlementMoney, settlementMoney] = useState({});
  /** 店铺类型ID*/
  const [storetypeID, setStoretypeID] = useState('');
  /** 店铺名称ID*/
  const [storeID, setstoreID] = useState('');
  /** 订单时间*/
  const [createdAt, setcreatedAt] = useState('');
  /** 分账时间*/
  const [businessAt, setbusinessAt] = useState('');
  useEffect(() => {
    //店铺分类（店铺类型）
    function initDateList() {
      api.srdTypeList().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.storeTypeId = element.id;
          element.text = element.name;
        });
        setsrdTypeList(arr);
      });
      //店铺名称（店铺信息）
      api.srdList().then((r) => {
        var arr1 = r.data;
        arr1.forEach((element) => {
          element.storeId = element.id;
          element.text = element.name;
        });
        setsrdList(arr1);
      });
    }
    setorderOriginalMoney(props.values.orderOriginalMoney);
    setdiscountMoney(props.values.discountMoney);
    setorderRealMoney(props.values.orderRealMoney);
    setbusinessPrice(props.values.businessPrice);
    setrefundMoney(props.values.refundMoney);
    settlementMoney(props.values.settlementMoney);
    initDateList();
  }, []);

  //复购率
  const SumInitFinance = async (fields) => {
    //店铺分类
    if (storetypeID == '') {
      fields.storeTypeId = props.values.storeTypeId;
    } else {
      fields.storeTypeId = storetypeID;
    }
    //店铺名称
    if (storeID == '') {
      fields.storeId = props.values.storeId;
    } else {
      fields.storeId = storeID;
    }
    //订单时间
    if (createdAt == '') {
      fields.createdAt = props.values.createdAt;
    } else {
      fields.createdAt = createdAt;
    }
    //预计分账时间
    if (businessAt != '') {
      fields.businessAt = businessAt;
    }
    await api.sumFinance(fields).then((r) => {

      if (r.data) {
        setorderOriginalMoney(r.data.orderOriginalMoney);
        setdiscountMoney(r.data.discountMoney);
        setorderRealMoney(r.data.orderRealMoney);
        setbusinessPrice(r.data.businessPrice);
        setrefundMoney(r.data.refundMoney);
        settlementMoney(r.data.settlementMoney);
      }
    });
  };
  const columns = [
    {
      title: '订单时间',
      dataIndex: 'createdAt',
      valueType: 'date',
    },
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      hideInSearch: true,
    },
    {
      title: '订单类型',
      dataIndex: 'orderType',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '正常订单',
          status: 'Processing',
        },
        1: {
          text: '立即吃面',
          status: 'Error',
        },
        2: {
          text: '盲盒',
          status: 'Error',
        },
        2: {
          text: '其他',
          status: 'Error',
        },
      },
    },
    {
      title: '流水金额',
      dataIndex: 'orderOriginalMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '优惠金额',
      dataIndex: 'discountMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '顾客实付',
      dataIndex: 'orderRealMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '平台费用',
      dataIndex: 'businessPrice',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
            onClick={() => {
            }}
          >
            详情
          </a>,
        ];
        return template;
      },
    },
  ];
  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="账单详情"
      visible={true}
      footer={false}
      onCancel={() => props.onCancel()}
      maskClosable={false}
    >
      <GridContent>
        <Suspense>
          <Row >
            <Col>
              <Space size="middle">
                店铺分类:<Select placeholder="请选择店铺分类" label="店铺分类"
                  name="storeTypeId" style={{ width: 150 }} onChange={(e) => {
                    setStoretypeID(e);
                    actionRef.current.reload();
                  }}>
                  {srdTypeList.map(item => {
                    return (
                      <Option value={item.id}>{item.name}</Option>
                    );
                  })}
                </Select>
                &nbsp;
              </Space>
              <Space size="middle">
                店铺名称:<Select placeholder="请选择店铺名称" label="店铺名称"
                  name="storeId" style={{ width: 150 }} onChange={(e) => {
                    setstoreID(e);
                    actionRef.current.reload();
                  }}>
                  {srdList.map(item => {
                    return (
                      <Option value={item.id}>{item.name}</Option>
                    );
                  })}
                </Select>
              </Space>
            </Col>
          </Row>
          <br />
          <Row >
            <Col>
              订单日期:<Space size="small"><DatePicker size={32} style={{ left: 15 }} onChange={(e) => {
                setcreatedAt(e);
                actionRef.current.reload();
              }} /></Space>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <Space size="small"><div>预计分账:<DatePicker size={32} style={{ left: 15 }} onChange={(e) => {
                setbusinessAt(e);
                actionRef.current.reload();
              }} /></div></Space>
            </Col>
          </Row>
          <Row >
            <Col>
              <Card title="" bordered={false} style={{ width: '100%' }}>
                <div>
                  <div style={{ float: 'center' }}>
                    {/* 分账金额 */}
                    <Statistic style={{ float: 'center' }} title="" value={getbusinessPrice} />
                  </div>
                  <Space size="large">
                    <Statistic title="流水金额" value={getorderOriginalMoney} style={{ float: 'left' }} xl={18} />
                    <Statistic title="优惠金额" value={getdiscountMoney} style={{ float: 'left' }} />
                    <Statistic title="顾客实付" value={getorderRealMoney} style={{ float: 'left' }} />
                    <Statistic title="平台费用" value={getbusinessPrice} style={{ float: 'left' }} />
                    <Statistic title="退款金额" value={getrefundMoney} style={{ float: 'left' }} />
                    <Statistic title="结算金额" value={getsettlementMoney} style={{ float: 'left' }} />
                  </Space>
                </div>
              </Card>
            </Col>
          </Row>
        </Suspense>
        <Suspense>
          <Row>
            <Col span={24}>
              <ProTable
                headerTitle="账单详情信息"
                actionRef={actionRef}
                rowKey="id"
                //pagination={{ defaultPageSize: 20 }}
                search={false}
                pagination={{
                  showQuickJumper: true,
                }}
                toolBarRender={false}
                //数据绑定
                request={async (params, sorter, filter) => {

                  var financeDetailData = [];
                  var total = 0;
                  //店铺分类
                  if (storetypeID == "") {
                    params.storeTypeId = props.values.storeTypeId;
                  } else {
                    params.storeTypeId = storetypeID;
                  }
                  //店铺名称
                  if (storeID == "") {
                    params.storeId = props.values.storeId;
                  } else {
                    params.storeId = storeID;
                  }
                  //订单时间
                  if (createdAt == "") {
                    params.createdAt = props.values.createdAt;
                  } else {
                    params.createdAt = createdAt;
                  }
                  //预计分账时间
                  if (businessAt != "") {
                    params.businessAt = businessAt;
                  }
                  //SumInitFinance(params);
                  await api.finaceDeatal(params).then((r) => {
                    financeDetailData = r.data.data;
                    total = r.data.total;
                  });
                  return {
                    data: financeDetailData,
                    // success 请返回 true，
                    // 不然 table 会停止解析数据，即使有数据
                    success: true,
                    // 不传会使用 data 的长度，如果是分页一定要传
                    total: total,
                  };
                }}
                summary={pageData => {
                  var totalorderOriginalMoney = 0;
                  var totaldiscountMoney = 0;
                  var totalorderRealMoney = 0;
                  var totalbusinessPrice = 0;
                  var totalrefundMoney = 0;
                  var totalsettlementMoney = 0;
                  pageData.forEach((x) => {
                    totalorderOriginalMoney += x.orderOriginalMoney;
                    totaldiscountMoney += x.discountMoney;
                    totalorderRealMoney += x.orderRealMoney;
                    totalrefundMoney += x.refundMoney;
                    totalsettlementMoney += x.settlementMoney;
                  })
                  return (
                    <ProTable.Summary.Row>
                      <ProTable.Summary.Cell>总计</ProTable.Summary.Cell>
                      <ProTable.Summary.Cell colSpan={2}>
                        <Text type="danger"></Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalorderOriginalMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totaldiscountMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalorderRealMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalbusinessPrice}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalrefundMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell colSpan={2}>
                        <Text>{totalsettlementMoney}¥</Text>
                      </ProTable.Summary.Cell>
                    </ProTable.Summary.Row>
                  );
                }}
                columns={columns}>
              </ProTable>
            </Col>
          </Row>
        </Suspense>
      </GridContent>
    </Modal>
  );
};

export default DetailManage;
