import { DropboxOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, message, Select, Input, Drawer,TreeSelect } 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 { gettree } from '../../sys/org/service';
import moment from 'moment';
//页面 相当于 class
const Manage = () => {
  //获取店铺类型(店铺类型)
  const [srdTypeList, setsrdTypeList] = useState([]);
  //获得店铺名称(店铺名称)
  const [srdList, setsrdList] = useState([]);
  //商品名称
  const [goodList, setgoodList] = useState([]);
  // //加盟商
  // const [franchList, setfranchList] = useState([]);
  //商品类型
  const [goodsTypeList, setgoodsTypeList] = useState([]);
  const [dataList, setdataList] = useState([]);
  //绑定
  const actionRef = useRef();

  const [OrgList, setOrgList] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);
  // 获取店铺分类、商品名称信息
  useEffect(() => {


    function initOrgList() {
      gettree().then((r) => {
        inittree(r.data);
        function inittree(datas) {
          for (var i in datas) {
            if(  datas[i]['type']==2||  datas[i]['type']==3){
              datas[i]['disabled']=false;
            }else{
              datas[i]['disabled']=true;
            }

            if (datas[i].children) {
              inittree(datas[i].children);
            }
          }
        }
        setOrgList(r.data);
        let list = {};
        formateData(r.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['disabled']]=true;
            list[datas[i]['value']] = { text: datas[i]['title'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setOrgListArray(list);
      });
    }
    //店铺分类（店铺类型）
    function initsrdTypeList() {
      api.srdTypeList().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.storeTypeId = element.id;
          element.text = 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);
      });
    }
    //商品信息
    function initgoodsList() {
      api.goodsList().then((r) => {
        var arr1 = r.data;
        arr1.forEach((element) => {
          element.label = element.name;
          element.value = element.id;
        });
        setgoodList(arr1);
      });
    }

    //查询商品类型
    function initgoodsTypeList() {
      api.goodsTypeList().then((r) => {
        var arr2 = r.data;
        arr2.forEach((element) => {
          element.label = element.name;
          element.value = element.id;
        });
        setgoodsTypeList(arr2);
      });
    }
    //initfranchList();
    initsrdList();
    initsrdTypeList();
    initgoodsList();
    initgoodsTypeList();
    initOrgList();
  }, []);
  function handleExport() {
    const { ReqDetailList } = dataList; // 网络请求命名空间
    const option = {};
    var Excelcolumns = [];
    //debugger
    columns.map((item, index) => {
      if (index > 2) {
        Excelcolumns.push(item);
      }
    });
    option.fileName = '订单汇总';
    option.datas = [
      {
        sheetData: dataList.map((item) => {
          const result = {};
          columns.forEach((c, index) => {
            if (index > 2) {
              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(() => 9),
      },
    ];

    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }
  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '店铺名称',
      dataIndex: 'storeId',
      hideInTable: true,
      width: 120,
      renderFormItem: () => (
        <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={OrgList}
            placeholder="归属门店"
            treeDefaultExpandAll
          />
      ),
    },
    {
      title: '日期范围',
      dataIndex: 'startTime',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [],
    },
    {
      title: '店铺名称',
      dataIndex: 'storeName',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '应付款金额',
      dataIndex: 'orderOriginalMoney',
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
      width: 160,
    },
    {
      title: '实际付款金额',
      dataIndex: 'orderRealMoney',
      hideInSearch: true,
      renderText: (val) => `${val}¥`,
      width: 160,
    },
    {
      title: '退款金额',
      dataIndex: 'refundRealMoney',
      hideInSearch: true,
      renderText: (val) => `${val}¥`,
      width: 120,
    },
    {
      title: '总订单',
      dataIndex: 'sumOrder',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '正常订单',
      dataIndex: 'successfulCount',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '退款订单',
      dataIndex: 'refundCount',
      hideInSearch: true,
      width: 120,
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="订单汇总查询"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 1300 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => handleExport()}>
            <DownloadOutlined /> 导出
          </Button>,
        ]}
        columns={columns}
        //数据绑定
        request={async (params, sorter, filter) => {
          var orderSummayData = [];
          var total = 0;
          if (params.storeTypeId != undefined) {
            //店铺分类
            params.storeTypeId = srdTypeList[params.storeTypeId].storeTypeId;
          }
          var obj=
          {
            current:params.current,
            pageSize:params.pageSize,
            storeId:[params.storeId],
            Order_CreateTime:params.startTime[0],
           Order_EndTime:params.startTime[1]

          }
          await api.orderSummaryList(obj).then((r) => {
            orderSummayData = r.data.data;
            total = r.data.total;
            setdataList(r.data.data);
          });
          return {
            data: orderSummayData,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: total,
          };
        }}
      ></ProTable>
    </PageContainer>
  );
};

export default Manage;
