import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree, handleCallLogs } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import { handleGetYsabnormalityReport } from "@/pages/reports/audit/spAbnormalReport/service";
import moment from "moment/moment";
import PageTitleBox from "@/components/PageTitleBox";
import LeftSelectTree from "../../settlementAccount/component/leftSelectTree";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";


const spAbnormalReport: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [treeView, setTreeView] = useState<any>()
  // 加载服务区树
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)
    setTreeView(data)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  // 门店还是服务区
  const [ShowShop, setShowShop] = useState<any>(1)


  const columns: any = [
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      initialValue: [moment().subtract(7, 'days'), moment().add(-1, 'day')],
      search: {
        transform: (value) => {
          return {
            startDate: value[0],
            endDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day')
      }
    },
    {
      dataIndex: 'ShowShop',
      valueType: "radioButton",
      hideInTable: true,
      initialValue: '1',
      valueEnum: {
        1: { text: '门店' },
        2: { text: '服务区' },
      },
      fieldProps: {
        onChange: (e: any) => {
          setShowShop(Number(e.target.value))
        },
        labelCol: { span: 0 },
        wrapperCol: { span: 24 }
      },
    },
    {
      title: '服务区信息',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: '序号',
          width: 120,
          align: 'center',
          dataIndex: 'index',
          valueType: "index"
        },
        {
          title: '服务区名称',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'Name',
        },
        {
          title: <div style={{ textAlign: 'center' }}>异常总数</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE',
        },
      ]
    },
    {
      title: '稽核必查',
      dataIndex: 'EXCEPTIONTYPEA',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>连续单清</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_B',
        },
        {
          title: <div style={{ textAlign: 'center' }}>整单清除</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_C',
        },
        {
          title: <div style={{ textAlign: 'center' }}>每单必打</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_Z',
        },
        {
          title: <div style={{ textAlign: 'center' }}>销售退货</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_F',
        },
        {
          title: <div style={{ textAlign: 'center' }}>异常交易</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_G',
        },
        {
          title: <div style={{ textAlign: 'center' }}>单品数量超限</div>,
          width: 150,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_L',
        },
        {
          title: <div style={{ textAlign: 'center' }}>单品金额超限</div>,
          width: 150,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_M',
        },
        {
          title: <div style={{ textAlign: 'center' }}>数量及金额超限</div>,
          width: 170,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_R',
        },
        {
          title: <div style={{ textAlign: 'center' }}>总数</div>,
          width: 100,
          align: 'right',
          dataIndex: 'TotalMust',
        }
      ]
    },
    {
      title: '稽核抽查',
      dataIndex: 'EXCEPTIONTYPEB',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>单行清除</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_A',
        },
        {
          title: <div style={{ textAlign: 'center' }}>小票重打</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_H',
        },
        {
          title: <div style={{ textAlign: 'center' }}>异常重打小票</div>,
          width: 150,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_I',
        },
        {
          title: <div style={{ textAlign: 'center' }}>非销售开钱箱</div>,
          width: 150,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_J',
        },
        {
          title: <div style={{ textAlign: 'center' }}>单价修改</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_N',
        },
        {
          title: <div style={{ textAlign: 'center' }}>整单折扣</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_O',
        },
        {
          title: <div style={{ textAlign: 'center' }}>单项折扣</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_P',
        },
        {
          title: <div style={{ textAlign: 'center' }}>单项优惠</div>,
          width: 120,
          align: 'right',
          dataIndex: 'EXCEPTIONTYPE_Q',
        },
        {
          title: <div style={{ textAlign: 'center' }}>总数</div>,
          width: 100,
          align: 'right',
          dataIndex: 'TotalMay',
        },
      ]
    }
  ]

  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName('spAbnormalReportHideBox')[0]
    const thead = main.querySelector('thead').cloneNode(true);  // 深克隆DOM节点
    const tbody = main.querySelector('tbody').cloneNode(true);  // 深克隆DOM节点
    const container = document.querySelector('#hiddenBox');

    const tempTable = document.createElement('table');
    tempTable.appendChild(thead);
    tempTable.appendChild(tbody);

    tempTable.setAttribute('id', 'table-to-xls-spAbnormalReport');                    // 给table添加id，值与按钮上的table字段对应

    container.appendChild(tempTable);                                // 把创建的节点添加到页面容器中

    setShowLoading(false)

    downloadBtnRef.current.handleDownload();
    setShowExportTable(false)
    tempTable.remove() // 防止重复打印一个内容
  }
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()

  return (
    <div ref={(el) => {
      // 打印报表
      if (!reqDetailList || reqDetailList.length === 0) return;
      setPrintOut(el);
    }} >

      {
        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={'spAbnormalReportHideBox'} 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 }} />

      <div style={{ backgroundColor: '#fff', display: 'flex' }}>
        {/* <ProCard
          style={{ width: !collapsible ? "300px" : "60px" }}
          className="pageTable-leftnav"
          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}
        >
          {treeView && treeView.length > 0 ? <Tree
            checkable
            treeData={[{
              label: '全部',
              value: 0,
              key: '0-0',
              children: treeView
            }]}
            fieldNames={{
              title: "label",
              key: "key"
            }}
            blockNode
            defaultExpandedKeys={['0-0']}
            onCheck={(checkedKeys: React.Key[] | any, info) => {
              const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
              setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
              // actionRef?.current?.reload()
              // getData(selectedIds.map(n => n?.value)?.toString() || '')
            }}
          // switcherIcon={<PlusOutlined />}
          /> : ''}
        </ProCard> */}
        <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            rowKey={(record) => record?.Id + record?.Name}
            bordered
            scroll={{ x: '100%', y: 'calc(100vh - 470px)' }}
            headerTitle={<PageTitleBox props={props} />}
            search={{ span: 6 }}
            request={async (params) => {
              if (!selectedId) {
                return
              }
              const req = {
                ...params,
                ServerpartIds: selectedId,
                ShowShop: ShowShop === 1
              }
              handleCallLogs()
              setSearchParams(params)

              const data = await handleGetYsabnormalityReport(req)
              console.log('data', data)
              if (data && data.length > 0) {
                const list: any = JSON.parse(JSON.stringify(data))
                list.forEach((item: any, index: number) => {
                  item.index = index + 1
                  if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any, subIndex: number) => {
                      subItem.index = subIndex + 1
                      if (subItem.children && subItem.children.length > 0) {
                        subItem.children.forEach((thirdItem: any, thirdIndex: number) => {
                          thirdItem.index = thirdIndex + 1
                        })
                      }
                    })
                  }
                })

                let fieldData: any = [
                  "EXCEPTIONTYPE",
                  "EXCEPTIONTYPE_B",
                  "EXCEPTIONTYPE_C",
                  "EXCEPTIONTYPE_Z",
                  "EXCEPTIONTYPE_F",
                  "EXCEPTIONTYPE_G",
                  "EXCEPTIONTYPE_L",
                  "EXCEPTIONTYPE_M",
                  "EXCEPTIONTYPE_R",
                  "TotalMust",
                  "EXCEPTIONTYPE_A",
                  "EXCEPTIONTYPE_H",
                  "EXCEPTIONTYPE_I",
                  "EXCEPTIONTYPE_J",
                  "EXCEPTIONTYPE_N",
                  "EXCEPTIONTYPE_O",
                  "EXCEPTIONTYPE_P",
                  "EXCEPTIONTYPE_Q",
                  "TotalMay",
                ]
                let enumList: any = []


                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(list)), fieldData, enumList, [], [])
                setReqDetailList(newPrintData)

                return { data: list, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                // <span style={{ visibility: 'hidden' }}>
                //   <ReactHTMLTableToExcel
                //     buttonText={'导出excel'}
                //     ref={downloadBtnRef}
                //     table="table-to-xls-spAbnormalReport"
                //     filename={`异常稽查报表${searchParams?.startDate}-${searchParams?.endDate}`}
                //     sheet="sheet1"
                //   />
                // </span>,
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    if (reqDetailList && reqDetailList.length > 0) {
                      // 尝试一下 导出新方法 
                      exportXlsxFromProColumnsExcelJS(columns,
                        reqDetailList,
                        `异常稽查报表${searchParams?.startDate}-${searchParams?.endDate}`,
                        // {
                        //   topTitle: `进销存类别报表`, // 顶部大标题
                        // }
                      )
                    } else {
                      message.error('暂无数据可导出！')
                    }
                  }}
                >
                  导出excel
                </Button>
              ]
            }}
          />
        </div>
      </div>
    </div>
  )
}

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