import {
  Modal, Typography, Table, Button, Input,
  Statistic, Card, Row, Col, Space,
  DatePicker, Select, message
} 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 SecondDetail from './secondDetail';
import moment from 'moment';
import api from '../services';
import './finance.css';

const DetailManage = (props) => {
  const dateFormat = 'YYYY-MM-DD';
  const actionRef = useRef();
  const { Text } = Typography;
  const { TextArea } = Input;
  const { RangePicker } = DatePicker;
  //获取店铺类型(店铺类型)
  const [srdTypeList, setsrdTypeList] = useState([]);
  //获得店铺名称(店铺名称)
  const [srdList, setsrdList] = useState([]);
  /** 流水金额*/
  const [getorderOriginalMoney, setorderOriginalMoney] = useState(0);
  /** 优惠金额*/
  const [getdiscountMoney, setdiscountMoney] = useState(0);
  /** 顾客实付*/
  const [getorderRealMoney, setorderRealMoney] = useState(0);
  /** 平台费用*/
  const [getbusinessPrice, setbusinessPrice] = useState(0);
  /** 退款金额*/
  const [getrefundMoney, setrefundMoney] = useState(0);
  /** 结算金额*/
  const [getsettlementMoney, settlementMoney] = useState(0);
  /** 预计分账金额*/
  const [getsplittingMoney, setSplittingMoney] = useState(0);
  /** 店铺类型选中值ID*/
  const [storetypeID, setStoretypeID] = useState([]);
  /** 店铺名称选中值*/
  const [srdValue, setSrdValue] = useState([]);
  /** 订单开始时间*/
  const [createdAt, setcreatedAt] = useState('');
  /** 订单结束时间*/
  const [endTime, setendTime] = useState('');
  /** 预计分账时间*/
  const [splittingDate, setSplittingDate] = useState('');
  /** 财务明细详情*/
  const [getsecondDetail, setsecondDetail] = useState();
  /** 结算详情调整 */
  const [setsecondDetailVisible, handlesecondDetailVisible] = useState();
  /** 结算详情调整*/
  const [row, setRow] = useState([]);

  useEffect(() => {
    setSrdValue([props.values.storeId]);
    setStoretypeID([props.values.storeTypeId]);
    //店铺分类（店铺类型）
    function initDateList() {
      api.srdTypeList().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.value = element.id;
          element.label = element.name;
        });
        setsrdTypeList(arr);
      });

      //店铺名称（店铺信息）
      if (props.values.storeTypeId != '' && props.values.storeTypeId != undefined) {
        api.StoreList([props.values.storeTypeId]).then((r) => {
          var arr = r.data;
          arr.forEach((element) => {
            element.value = element.id;
            element.label = element.name;
          });
          setsrdList(arr);
        });
      } else {
        api.srdList().then((r) => {
          var arr1 = r.data;
          arr1.forEach((element) => {
            element.value = element.id;
            element.label = element.name;
          });
          setsrdList(arr1);
        });
      }
    }
    initDateList();
  }, []);
  /** 查询总的汇总金额*/
  const SumInitFinance = async (fields) => {
    await api.sumFinance(fields).then((r) => {
      if (r.data) {
        setorderOriginalMoney(r.data.orderOriginalMoney);
        setdiscountMoney(r.data.discountMoney);
        setorderRealMoney(r.data.orderRealMoney);
        setrefundMoney(r.data.refundMoney);
        settlementMoney(r.data.settlementMoney);
        setSplittingDate(r.data.splittingDate);
        setSplittingMoney(r.data.splittingMoney);
      }
    });
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'orderId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '订单时间',
      dataIndex: 'createdAt',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      hideInSearch: true,
    },
    {
      title: '订单类型',
      dataIndex: 'orderType',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '正常订单',
          status: 'Processing',
        },
        1: {
          text: '立即吃面',
          status: 'Error',
        },
        2: {
          text: '盲盒',
          status: 'Error',
        },
        3: {
          text: '其他',
          status: 'Error',
        },
        '-1': {
          text: '退款',
          status: 'Error',
        },
      },
    },
    {
      title: '流水金额',
      dataIndex: 'orderOriginalMoney',
      key: 'orderOriginalMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '优惠金额',
      dataIndex: 'discountMoney',
      key: 'discountMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '顾客实付',
      dataIndex: 'orderRealMoney',
      key: 'orderRealMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '平台费用',
      dataIndex: 'businessPrice',
      key: 'businessPrice',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundMoney',
      key: 'refundMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementMoney',
      key: 'settlementMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
            onClick={() => {
              handlesecondDetailVisible(true);
              api.setSettlementDetail(record, record.orderId, record.orderType).then((r) => {
                setRow(r.data);
                setsecondDetail(record);
              });
            }}
          >
            详情
          </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 mode="multiple" showArrow placeholder="请选择店铺分类" label="店铺分类"
                  defaultValue={props.values.storeTypeId != null && props.values.storeTypeId != "" ? props.values.storeTypeId : []}
                  name="storeTypeId" style={{ width: 285 }}
                  onChange={(e) => {

                    setStoretypeID(e);
                    if (e.length > 0) {
                      //根据选择的店铺分类刷新店铺信息
                      api.StoreList(e).then((r) => {
                        var arr = r.data;
                        arr.forEach((element) => {
                          element.value = element.id;
                          element.label = element.name;
                        });
                        setsrdList(arr);
                        // 查找一次SrdValue在arr里面有没有id值，没有就删除掉。
                        if (arr.length == 0) {
                          setSrdValue([]);
                        } else {
                          if (arr.length) {
                            var list = [];
                            arr.forEach((e) => {
                              if (srdValue.length > 0) {
                                srdValue.forEach((m) => {
                                  if (m == e.id) {
                                    list.push(e.id);
                                  }
                                });
                              }
                            });
                            if (list.length > 0) {
                              setSrdValue(list);
                            } else {
                              setSrdValue([]);
                            }
                          }
                        }
                        if (srdValue != "") {
                          actionRef.current.reload();
                        }
                      });
                    } else {
                      //店铺名称清空
                      setSrdValue([]);
                      setStoretypeID([]);
                      //清空店铺分类信息，重新绑定所有店铺信息
                      api.srdList().then((r) => {
                        var arr = r.data;
                        arr.forEach((element) => {
                          element.value = element.id;
                          element.label = element.name;
                        });
                        setsrdList(arr);
                        if (srdValue != "") {
                          actionRef.current.reload();
                        }
                      });
                    }
                  }}
                >
                  {srdTypeList.map(item => {
                    return (
                      <Option value={item.id}>{item.name}</Option>
                    );
                  })}
                </Select>
                &nbsp; &nbsp;
              </Space>
              <Space size="middle">
                店铺名称:<Select mode="multiple" showArrow placeholder="请选择店铺名称" label="店铺名称" value={srdValue}
                  name="storeId" style={{ width: 285 }}
                  onChange={(e) => {

                    setSrdValue(e);
                    actionRef.current.reload();
                  }}
                  onClear={(res) => {
                    setSrdValue(res);
                  }}
                >
                  {srdList.map(item => {
                    return (
                      <Option value={item.id}>{item.name}</Option>
                    );
                  })}
                </Select>
              </Space>
            </Col>
          </Row>
          <br />
          <Row >
            <Col>
              订单日期:<Space size="small"><RangePicker defaultValue={[moment(props.values.createdAt, dateFormat), moment(props.values.endTime, dateFormat)]}
                size={32} style={{ left: 15 }} onChange={(e) => {
                  if (e != null) {
                    setcreatedAt(e[0].format('YYYY-MM-DD'));
                    setendTime(e[1].format('YYYY-MM-DD'));
                  } else {
                    setcreatedAt(moment(new Date(), dateFormat));
                    setendTime(moment(new Date(), dateFormat));
                  }
                  actionRef.current.reload();
                }} /></Space>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <Space size="middle">
                预计分账:<Input title='' disabled={false} value={`预计${splittingDate != null ? splittingDate : moment(new Date(), dateFormat)}分账`} style={{ float: 'right', width: 285 }} ></Input>
                {/* <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={getsplittingMoney != 0 ? getsplittingMoney.toFixed(2) : getsplittingMoney} prefix="¥" />
                  </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
                actionRef={actionRef}
                rowKey="id"
                search={{
                  optionRender: false,
                  collapsed: false,
                }}
                pagination={{
                  showQuickJumper: true,
                }}
                toolBarRender={false}
                //数据绑定
                request={async (params, sorter, filter) => {

                  var financeDetailData = [];
                  var total = 0;
                  if (storetypeID != "") {
                    params.storeTypeId = storetypeID;
                  }
                  if (srdValue != "") {
                    params.storeId = srdValue;
                  }
                  //订单开始时间
                  if (createdAt == undefined || createdAt == "") {
                    params.createdAt = props.values.createdAt;
                  } else {
                    params.createdAt = createdAt;
                  }
                  //订单结束时间
                  if (endTime == undefined || endTime == "") {
                    params.endTime = props.values.endTime;
                  } else {
                    params.endTime = endTime;
                  }
                  SumInitFinance(params);
                  //必须选择店铺菜单刷新数据
                  if (srdValue != ""){
                    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 => {
                  let totalorderOriginalMoney = 0;
                  let totaldiscountMoney = 0;
                  let totalorderRealMoney = 0;
                  let totalbusinessPrice = 0;
                  let totalrefundMoney = 0;
                  let 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 != 0 ? totalorderOriginalMoney.toFixed(2) : totalorderOriginalMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totaldiscountMoney != 0 ? totaldiscountMoney.toFixed(2) : totaldiscountMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalorderRealMoney != 0 ? totalorderRealMoney.toFixed(2) : totalorderRealMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalbusinessPrice != 0 ? totalbusinessPrice.toFixed(2) : totalbusinessPrice}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell>
                        <Text>{totalrefundMoney != 0 ? totalrefundMoney.toFixed(2) : totalrefundMoney}¥</Text>
                      </ProTable.Summary.Cell>
                      <ProTable.Summary.Cell colSpan={2}>
                        <Text>{totalsettlementMoney != 0 ? totalsettlementMoney.toFixed(2) : totalsettlementMoney}¥</Text>
                      </ProTable.Summary.Cell>
                    </ProTable.Summary.Row>
                  );
                }}
                columns={columns}>
              </ProTable>
            </Col>
          </Row>
        </Suspense>
      </GridContent>
      {/* 结算详情*/}
      {getsecondDetail && Object.keys(getsecondDetail).length ? (
        <SecondDetail
          onCancel={() => {
            handlesecondDetailVisible(true);
            setsecondDetail({});
          }}
          setsecondDetailVisible={setsecondDetailVisible}
          values={row}
        />
      ) : null}
    </Modal>
  );
};

export default DetailManage;
