import { DropboxOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, message, Select, Input, Drawer } 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 FinanceDetail from './components/financeDetail';
import ExportJsonExcel from 'js-export-excel';
// import moment from 'moment';
import api from './services';
import { add } from 'lodash';
//页面 相当于 class
const Manage = () => {
  //获取店铺类型(店铺类型)
  const [srdTypeList, setsrdTypeList] = useState([]);
  //获得店铺名称(店铺名称)
  const [srdList, setsrdList] = useState([]);
  /** 店铺选中值*/
  const [srdValue, setSrdValue] = useState([]);
  /** 财务详情调整*/
  const [getfinanceDetail, setfinanceDetail] = useState();
  /** 财务详情调整新建/更新财务详情调整 */
  const [setfinanceDetailVisible, handlefinanceDetailVisible] = useState();
  //订单开始时间
  const [getCreatedAt, setcreatedAt] = useState('');
  //订单结束时间时间
  const [getendTime, setendTime] = useState('');
  //记录查询条件
  const [Selectparams, setparams] = useState([]);
  //记录查询条件店铺分类
  const [selectTypeId, setselectTypeId] = useState([]);
  //绑定
  const actionRef = useRef();

  useEffect(() => {
    //店铺分类（店铺类型）
    function initsrdTypeList() {
      api.srdTypeList().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.value = element.id;
          element.label = element.name;
        });
        setsrdTypeList(arr);
      });
    }
    //店铺名称（店铺信息）
    function initsrdList() {
      api.srdList().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.value = element.id;
          element.label = element.name;
        });
        setsrdList(arr);
      });
    }
    initsrdTypeList();
    initsrdList();
  }, []);

  /** 下载财务详情信息*/
  function handleDownLoad(fields) {
    //
    const columnsDetail = [
      {
        title: '店铺分类',
        dataIndex: 'storeTypeName',
        hideInSearch: true,
      },
      {
        title: '店铺名称',
        dataIndex: 'storeName',
        hideInSearch: true,
      },
      {
        title: '订单时间',
        dataIndex: 'createdAt',
        valueType: 'date',
      },
      {
        title: '订单编号',
        dataIndex: 'orderNumber',
        hideInSearch: true,
      },
      {
        title: '订单类型',
        dataIndex: 'orderType',
        hideInSearch: true,
      },
      {
        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;
        },
      },
    ];
    const option = {};
    var Excelcolumns = [];
    columnsDetail.map((item, index) => {
      if (index < 11) {
        Excelcolumns.push(item);
      }
    });
    option.fileName = '财务账单详情';
    option.datas = [
      {
        sheetData: fields.map((item) => {
          const result = {};
          columnsDetail.forEach((c, index) => {
            if (index < 11) {
              if (index == 4) {
                if (item[c.dataIndex] == 0) {
                  result[c.dataIndex] = "正常订单";
                }
                else if (item[c.dataIndex] == "1") {
                  result[c.dataIndex] = "立即吃面";
                }
                else if (item[c.dataIndex] == "2") {
                  result[c.dataIndex] = "盲盒";
                }
                else if (item[c.dataIndex] == "3") {
                  result[c.dataIndex] = "其他";
                }
                else if (item[c.dataIndex] == "-1") {
                  result[c.dataIndex] = "退款";
                }
                else if (item[c.dataIndex] == "-2") {
                  result[c.dataIndex] = "合计";
                }
                else {
                  result[c.dataIndex] = "其他";
                }
              } else {
                result[c.dataIndex] = item[c.dataIndex];
              }
            }
          });
          return result;
        }),
        sheetName: '财务账单详情', // Excel文件名称
        sheetFilter: Excelcolumns.map((item) => item.dataIndex),
        sheetHeader: Excelcolumns.map((item) => item.title),
        columnWidths: Excelcolumns.map(() => 10),
      },
    ];
    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }
  /** 国际化配置 */
  const columns = [
    {
      title: '店铺分类',
      dataIndex: 'storeTypeId',
      hideInTable: true,
      // fixed: 'left',
      width: 120,
      renderFormItem: () => (
        <Select
          mode="multiple"
          showArrow
          placeholder="请选择店铺分类"
          style={{ width: '100%' }}
          options={srdTypeList}
          onChange={(e) => {
            //记录选择的店铺分类
            setselectTypeId(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([]);
                    }
                  }
                }
              });
            } else {
              setselectTypeId([]);
              setSrdValue([]);
              api.srdList().then((r) => {
                var arr = r.data;
                arr.forEach((element) => {
                  element.value = element.id;
                  element.label = element.name;
                });
                setsrdList(arr);
              });
            }
          }}
        />
      ),
    },
    {
      title: '店铺分类',
      dataIndex: 'storeTypeName',
      hideInForm: true,
      hideInSearch: true,
      //fixed: 'left',
    },
    {
      title: '店铺名称',
      dataIndex: 'storeId',
      hideInTable: true,
      //fixed: 'left',
      width: 120,
      renderFormItem: () => (
        <Select
          mode="multiple"
          showArrow
          placeholder="请选择店铺"
          style={{ width: '100%' }}
          options={srdList}
          value={srdValue}
          onChange={(res) => {
            setSrdValue(res);
          }}
          onClear={(res) => {
            setSrdValue(res);
          }}
        />
      ),
    },
    {
      title: '店铺名称',
      dataIndex: 'storeName',
      hideInForm: true,
      hideInSearch: true,
      //fixed: 'left',
      // width: 120,
    },
    {
      title: '订单时间',
      dataIndex: 'createdAt',
      valueType: 'date',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '订单时间',
      dataIndex: 'createdAt',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            createdAt: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '结算金额',
      dataIndex: 'settlementMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '分账金额',
      dataIndex: 'businessPrice',
      hideInSearch: true,
      renderText: (val) => `${val}¥`,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
            onClick={() => {
              handlefinanceDetailVisible(true);
              setfinanceDetail(record);
            }}
          >
            查看
          </a>,
          <a
            key="primary"
            type="primary"
            onClick={() => {
              record.storeTypeId = [record.storeTypeId] == "" ? null : [record.storeTypeId];
              record.storeId = [record.storeId];
              api.financeSummaryList(record).then((r) => {
                if (r.data) {
                  handleDownLoad(r.data);
                }
              });
            }}
          >
            下载
          </a>,
        ];
        return template;
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="财务账单查询"
        actionRef={actionRef}
        // rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => {
            if (Selectparams != undefined && Selectparams != '') {
              api.financeSummaryList(Selectparams).then((r) => {
                handleDownLoad(r.data);
              });
            }
          }}>
            <DownloadOutlined /> 下载
          </Button>,
        ]}
        columns={columns}
        //数据绑定
        request={async (params, sorter, filter) => {
          var financeData = [];
          var total = 0;
          if (selectTypeId != undefined && selectTypeId.length > 0) {
            params.storeTypeId = selectTypeId;
          }
          //订单时间范围
          if (params.createdAt != undefined) {
            setcreatedAt(params.createdAt)
          }
          if (params.endTime != undefined) {
            setendTime(params.endTime)
          }
          if (srdValue != undefined && srdValue.length > 0) {
            params.storeId = srdValue;
          }
          setparams(params);
          //必选选择店铺
          if (srdValue != undefined && srdValue.length > 0) {
            //setStoreId(params.storeId);
            await api.finaceList(params).then((r) => {
              financeData = r.data.data;
              total = r.data.total;
            });
          }
          return {
            data: financeData,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: total,
          };
        }}
      ></ProTable>
      {/* 财务详情*/}
      {getfinanceDetail && Object.keys(getfinanceDetail).length ? (
        <FinanceDetail
          onCancel={() => {
            handlefinanceDetailVisible(true);
            setfinanceDetail({});
          }}
          setfinanceDetailVisible={setfinanceDetailVisible}
          values={getfinanceDetail}
        />
      ) : null}
    </PageContainer>
  );
};

export default Manage;
