/*
 * @Author: cclu
 * @Date: 2022-03-10 16:59:45
 * @LastEditTime: 2024-12-16 11:23:25
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 销售流水页面
 * @FilePath: \cloud-platform\src\pages\merchantManagement\reports\SalesFlow\index.tsx
 */
import { connect } from 'umi';
import useRequest from '@ahooksjs/use-request';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { MenuFoldOutlined } from '@ant-design/icons';
import { Avatar, Button, Descriptions, Menu, message, Modal, Space, Spin, Tree, Typography } from 'antd';
import React, { useRef, useState } from 'react';

import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { YSSELLMASTERModel } from './data';
import type { CurrentUser } from '@/models/user';

import moment from 'moment';
import numeral from 'numeral';

import { exportExcel } from '@/utils/utils';
import { getYSSellMasterList, getYSSellMasterListAllData } from './service';
import { getMoney, handleCallLogs, handleGetServiceShopTreeList } from '@/services/options';
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import './style.less';
import './salesFlow.less'
import FlowDetail from "@/pages/merchantManagement/reports/SalesFlow/components/FlowDetail";
import SubMenu from "antd/lib/menu/SubMenu";
import PageTitleBox from '@/components/PageTitleBox';
import { exportXlsxFromProColumnsExcelJS } from '@/utils/exportExcelFun';
import { formatTreeData } from '@/utils/format';

const { Text } = Typography;

/**
 * @description: 商户销售流水查询
 * @param {CurrentUser} CurrentUser 当前登录的用户信息
 * @return {React.FC} 页面主题
 */
const saleFlow: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
  const { currentUser } = props
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const [currentRow, setCurrentRow] = useState<YSSELLMASTERModel | undefined>(); // 选中的流水
  const [visible, setVisible] = useState<boolean>(); // 流水明显弹出框
  const [reqDetailList, setReqDetailList] = useState<YSSELLMASTERModel[]>();
  const [otherData, setOtherData] = useState<any>()
  const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())

  const [collapsible, setCollapsible] = useState<boolean>(false)  // 是否隐藏门店服务区筛选
  const { loading: shopLoading, data: shopTree } = useRequest(async () => {
    const data = await handleGetServiceShopTreeList({
      ProvinceCode: currentUser?.ProvinceCode,
      BusinessState: "1000,2000,3000",
      ShowState: true,
      SortStr: 'BUSINESS_STATE,SHOPSHORTNAME'
    });
    return data
  })
  const defaultShops = currentUser?.ServerpartShopIds ? currentUser?.ServerpartShopIds.split(',').map(Number) : []
  const [shopId, setShopId] = useState<[]>(); // 选择的门店 根据选择的门店筛选数据结果
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  const [selectedId, setSelectedId] = useState<any>(); // 当前选中左侧菜单的门店节点
  const [currenType, setCurrenType] = useState<any>(); // 当前选中左侧菜单的门店节点
  const [searchParams, setSearchParams] = useState<any>()

  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)


  const columns: any = [
    {
      dataIndex: 'index',
      title: '序号',
      hideInSearch: true,
      valueType: 'index',
      // fixed: true,
      align: 'center',
      width: 70,
      // render:(_,reocrd)=>{
      //   return reocrd?.index
      // }
    },


    // {
    //   dataIndex: 'SELLMASTER_DATE',
    //   valueType: "date",
    //   width: 150,
    //   title: '销售时间',
    //   align: 'center',
    //   initialValue: moment().add(-1, 'day'),
    //   sorter: (a, b) => new Date(a.SELLMASTER_DATE).getTime() - new Date(b.SELLMASTER_DATE).getTime(),
    //   defaultSortOrder: 'descend',
    //   render: (_, record) => {
    //     return record?.SELLMASTER_DATE
    //   },
    //   fieldProps: {
    //     disabledDate: (current: any) => current && current > moment().endOf('day').add(-1, 'day')
    //   }
    // },
    {
      title: '交易时间',
      dataIndex: 'SELLMASTER_DATE',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      search: {
        transform: (value) => {
          return {
            SELLMASTER_DATE_Start: value[0],
            SELLMASTER_DATE_End: value[1],
          };
        },
      },
      fieldProps: {
        ranges: {
          "本月": [moment().startOf('M'), moment()],
          "上月": [moment().subtract(1, 'M').startOf('M'), moment().subtract(1, 'M').endOf('M')],
          "近三月": [moment().subtract(3, 'M').startOf('M'), moment().endOf('M')]
        }
      },
      initialValue: [moment(), moment()],
    },
    {
      title: "查询内容",
      dataIndex: "searchValue",
      hideInTable: true,
      fieldProps: {
        placeholder: "请输入商品名称/商品条码"
      }
    },
    {
      dataIndex: 'TICKET_CODE',
      title: '小票编号',
      width: 120,
      hideInSearch: true,
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        return record?.TICKET_CODE ? <a>{record?.TICKET_CODE}</a> : "-"
      }
    },
    {
      dataIndex: 'SELLMASTER_DATE',
      title: <div style={{ textAlign: 'center' }}>销售时间</div>,
      hideInSearch: true,
      width: 150,
      align: 'center',
      ellipsis: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品明细</div>,
      dataIndex: 'SaleDetail',
      width: 350,
      hideInSearch: true,
      align: 'left',
      ellipsis: true,
    },
    {
      dataIndex: 'SELLMASTER_COUNT',
      title: <div style={{ textAlign: 'center' }}>销售数量</div>,
      hideInSearch: true,
      width: 120,
      align: 'right',
      ellipsis: true,
      valueType: "digit",
      sorter: (a, b) => a.SELLMASTER_COUNT - b.SELLMASTER_COUNT
    },


    {
      dataIndex: 'SELLMASTER_AMOUNT',
      title: <div style={{ textAlign: 'center' }}>实收金额</div>,
      width: 120,
      hideInSearch: true,
      ellipsis: true,
      valueType: "money",
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_AMOUNT - b.SELLMASTER_AMOUNT
    },
    {
      dataIndex: 'SELLMASTER_OFFPRICE',
      title: <div style={{ textAlign: 'center' }}>优惠金额</div>,
      width: 120,
      hideInSearch: true,
      valueType: "money",
      ellipsis: true,
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_OFFPRICE - b.SELLMASTER_OFFPRICE
    },
    {
      dataIndex: 'PAYMENT_TYPE_TEXT',
      width: 120,
      title: '支付方式',
      ellipsis: true,
      hideInSearch: true,
      align: 'center',
    },

    {
      dataIndex: 'SHOPNAME',
      hideInSearch: true,
      title: '门店名称',
      ellipsis: true,
      align: 'center',
      width: 150,
    },
    {
      dataIndex: 'MACHINECODE',
      hideInSearch: true,
      title: '收银机号',
      ellipsis: true,
      align: 'center',
      width: 120,
    },
    {
      dataIndex: 'SELLWORKER_NAME',
      hideInSearch: true,
      ellipsis: true,
      title: '收银人员',
      align: 'center',
      width: 120,
    }

  ];


  return (
    <div style={{ backgroundColor: '#fff', display: 'flex' }}>
      {
        showLoading ?
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0,0,0,0.1)',
              position: 'fixed',
              zIndex: 5,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '15px 20px 10px',
              background: '#fff',
              borderRadius: '8px',
              width: '200px'
            }}>
              <Spin />
              <span style={{ marginLeft: '5px' }}>数据导出中...</span>
            </div>
          </div> : ''
      }

      <div className={`saleReportHideBox${printIndex}`} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
        {
          showExportTable && reqDetailList && reqDetailList.length > 0 ?
            <ProTable
              columns={columns}
              dataSource={reqDetailList}
              pagination={false}
              expandable={{
                defaultExpandAllRows: true
              }}
            /> : ''
        }
      </div>
      <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />



      <ProCard
        className="pageTable-leftnav"
        style={{ width: !collapsible ? "300px" : "60px" }}
        bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
        extra={<MenuFoldOutlined onClick={() => {
          setCollapsible(!collapsible)
        }} />}
        colSpan={!collapsible ? "300px" : "60px"}
        title={!collapsible ? "可筛选门店" : ""}
        headerBordered
        collapsed={collapsible}
      >
        {shopTree && shopTree.length > 0 ? <Tree
          checkable
          treeData={[{
            label: '全部',
            value: 0,
            key: '0-0',
            children: shopTree
          }]}
          fieldNames={{
            title: "label",
            key: "key"
          }}
          blockNode
          defaultExpandedKeys={['0-0']}
          onCheck={(checkedKeys: React.Key[] | any, info) => {
            const selectedIds = info.checkedNodes.filter(n => n?.type === 2)
            setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
            // actionRef?.current?.reload()
            // getData(selectedIds.map(n => n?.value)?.toString() || '')
          }}
        /> : ''}
      </ProCard>
      <div style={{
        width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
        paddingTop: 0,
        paddingBottom: 0,
        paddingRight: 0
      }}>
        <ProTable<YSSELLMASTERModel>
          rowKey="SELLMASTER_CODE"
          headerTitle={<PageTitleBox props={props} />}
          formRef={formRef}
          actionRef={actionRef}
          search={{ span: 6 }}
          pagination={{ pageSize: 20 }}
          scroll={{ x: '100%', y: 'calc(100vh - 590px)' }}
          request={async (params) => {
            console.log('paramsparamsparams', params);

            if (selectedId || currenMenu) {
              handleCallLogs()
              const req: any = {
                SearchParameter: {
                  ...params,
                  // SERVERPART_ID: currenType === 1 ? currenMenu && currenMenu.length > 0 ? currenMenu.toString() : currentUser?.ServerpartIds : '',
                  SERVERPARTSHOP_ID: selectedId || '',
                },
                PageIndex: 1,
                PageSize: 999999,
                keyWord: {
                  Key: "COMMODITY_NAME,COMMODITY_BARCODE,TICKET_CODE",
                  Value: params?.searchValue
                },
                SortStr: "SELLMASTER_DATE desc"
              }
              setSearchParams(params)
              const data = await getYSSellMasterListAllData(req);
              if (data.List && data.List.length > 0) {
                const list: any = JSON.parse(JSON.stringify(data.List))

                let fieldData: any = [
                  "SELLMASTER_COUNT",
                  "SELLMASTER_AMOUNT",
                  "SELLMASTER_OFFPRICE"
                ]
                let enumList: any = []
                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(list)), fieldData, enumList, [], [])

                setReqDetailList(newPrintData);
                setOtherData(data.OtherData)
                return { data: list, success: true }
              }
              setReqDetailList([]);
              return { data: [], success: true }

            }
          }}
          rowClassName="saleflow-row"
          bordered
          columns={columns}
          toolbar={{
            actions: [
              <Button
                key="new"
                type="primary"
                onClick={async (e) => {
                  if (reqDetailList && reqDetailList.length > 0) {
                    // 尝试一下 导出新方法 
                    exportXlsxFromProColumnsExcelJS(columns,
                      reqDetailList,
                      // `销售流水查询${searchParams?.SELLMASTER_DATE}`,
                      `销售流水查询${searchParams?.SELLMASTER_DATE_Start}-${searchParams?.SELLMASTER_DATE_End}`,
                      {
                        footerMaker: currentUser?.Name,
                        footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                        footerStatsTime: `${searchParams?.SELLMASTER_DATE_Start}-${searchParams?.SELLMASTER_DATE_End}`
                      }
                    )
                  } else {
                    message.error('暂无数据可导出！')
                  }
                }}
              >
                导出excel
              </Button>
            ],
          }}
          tableExtraRender={
            (_, data) => {
              if (data) {
                const devicesList: any = []
                const reduceData = data.reduce((
                  p: {
                    SELLMASTER_OFFPRICE: number,
                    SELLMASTER_COUNT: number,
                    SELLMASTER_AMOUNT: number,
                    MACHINECODE: string[],
                    payway: {},
                    mobilePay: {}
                  },

                  currentValue: YSSELLMASTERModel) => {
                  const previousValue = { ...p }
                  previousValue.SELLMASTER_COUNT += currentValue.SELLMASTER_COUNT || 0; // 销售数量
                  previousValue.SELLMASTER_OFFPRICE += currentValue.SELLMASTER_OFFPRICE || 0; // 优惠金额
                  previousValue.SELLMASTER_AMOUNT += currentValue.SELLMASTER_AMOUNT || 0; // 实收金额 

                  if (devicesList.indexOf(currentValue.MACHINECODE) === -1) {
                    devicesList.push(currentValue.MACHINECODE)
                  }

                  if (currentValue.PAYMENT_TYPE === 1010 || currentValue.PAYMENT_TYPE === 1020) {
                    previousValue.payway['移动'] += currentValue.SELLMASTER_AMOUNT
                    if (!previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT]) { // 移动支付方式
                      previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT] = 0
                    }
                    previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT] += currentValue.SELLMASTER_AMOUNT
                  } else {
                    if (!previousValue.payway[currentValue.PAYMENT_TYPE_TEXT]) { // 支付方式
                      previousValue.payway[currentValue.PAYMENT_TYPE_TEXT] = 0
                    }
                    previousValue.payway[currentValue.PAYMENT_TYPE_TEXT] += currentValue.SELLMASTER_AMOUNT
                  }
                  if (!previousValue.MACHINECODE.includes(currentValue.MACHINECODE)) {

                    previousValue.MACHINECODE.push(currentValue.MACHINECODE); // 收银机号
                  }
                  return previousValue
                }, {
                  SELLMASTER_OFFPRICE: 0,
                  SELLMASTER_COUNT: 0,
                  SELLMASTER_AMOUNT: 0,
                  MACHINECODE: [],
                  payway: { '移动': 0, '现金': 0, },
                  mobilePay: {}
                });
                return <div style={{ paddingLeft: 24 }}>
                  <Descriptions
                    title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>合计信息</Text>}
                    size="small" column={7}
                    className="commity-sale-description"
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                  >
                    <Descriptions.Item label="客单数量">{numeral(data.length).format('0,0')}<Text
                      type="secondary"> 笔</Text></Descriptions.Item>
                    <Descriptions.Item
                      label="实收金额">¥{numeral(reduceData.SELLMASTER_AMOUNT).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item
                      label="优惠金额">¥{numeral(reduceData.SELLMASTER_OFFPRICE).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item
                      label="客单均价">¥{numeral(reduceData.SELLMASTER_AMOUNT / data.length).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item label="销售数量">{numeral(reduceData.SELLMASTER_COUNT).format('0,0')}<Text
                      type="secondary"> 件</Text></Descriptions.Item>
                    <Descriptions.Item label="设备数量">{devicesList && devicesList.length > 0 ? devicesList.length : '-'}台</Descriptions.Item>
                    <Descriptions.Item label="统计时间">{moment().format('YYYY-MM-DD')}</Descriptions.Item>
                  </Descriptions>

                  <Descriptions
                    title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>支付明细</Text>}
                    size="small" column={7}
                    className="commity-sale-description"
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                  >
                    <Descriptions.Item
                      label="现金支付">{otherData?.CASH ? `¥${numeral(getMoney(otherData?.CASH)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item
                      label="微信支付">{otherData?.TICKETBILL ? `¥${numeral(getMoney(otherData?.TICKETBILL)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="支付宝支付">{otherData?.OTHERPAY ? `¥${numeral(getMoney(otherData?.OTHERPAY)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="云闪付">{otherData?.CREDITCARD ? `¥${numeral(getMoney(otherData?.CREDITCARD)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="银联记账">{otherData?.YUNSHANFU ? `¥${numeral(getMoney(otherData?.YUNSHANFU)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="企业会员">{otherData?.COUPONTYPE_2010 ? `¥${numeral(getMoney(otherData?.COUPONTYPE_2010)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="电子优惠券">{otherData?.COUPONTYPE_2020 ? `¥${numeral(getMoney(otherData?.COUPONTYPE_2020)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                  </Descriptions>
                  <Descriptions size="small" className="commity-sale-description" column={7}
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}>
                    <Descriptions.Item label="大巴优惠券">{otherData?.COUPONTYPE_2030 ? `¥${numeral(getMoney(otherData?.COUPONTYPE_2030)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="团购餐券">{otherData?.COUPONTYPE_2040 ? `¥${numeral(getMoney(otherData?.COUPONTYPE_2040)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="促销流水">{otherData?.SELLMASTERTYPE_1010 ? `¥${numeral(getMoney(otherData?.SELLMASTERTYPE_1010)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="香烟销售">{otherData?.SELLMASTERTYPE_1020 ? `¥${numeral(getMoney(otherData?.SELLMASTERTYPE_1020)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="在线订单">{otherData?.SELLMASTERTYPE_1030 ? `¥${numeral(getMoney(otherData?.SELLMASTERTYPE_1030)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                    <Descriptions.Item label="稽核补录">{otherData?.SELLMASTERTYPE_1040 ? `¥${numeral(getMoney(otherData?.SELLMASTERTYPE_1040)).format('0,0.00')}` : '¥0.00'}</Descriptions.Item>
                  </Descriptions>
                </div>
              }
              return <></>
            }
          }
          onRow={(record) => {
            return {
              onClick: () => {
                setCurrentRow(record)
                setVisible(true)
              }
            }
          }}
        />
      </div>
      <Modal
        title={currentRow ? `${currentRow?.SERVERPART_NAME + currentRow?.SHOPNAME}销售流水明细` : '销售流水明细'}
        centered
        visible={visible}
        onOk={() => {
          setCurrentRow(undefined)
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
        width={1024}
        bodyStyle={{ padding: 0 }}
        destroyOnClose
      >
        {currentRow && <FlowDetail id={currentRow?.SELLMASTER_CODE} />}
      </Modal>
    </div >
  );
};

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser
}))(saleFlow);
