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 {
  getFieldEnum,
  getFieldEnumTree,
  getServerpartTree,
  getSPRegionShopTree,
  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 { handleGetCommodityList } from "../commodityInfo/service";
import moment from "moment";
import session from "@/utils/session";
import PageTitleBox from "@/components/PageTitleBox";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";
import LeftSelectTree from "../../settlementAccount/component/leftSelectTree";


const shopCommodity: 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 () => {
    // 734100 是建工 他要显示多一点
    const data = await getSPRegionShopTree(currentUser?.ProvinceCode, '', '', '', '1000,2000,3000', currentUser?.ProvinceCode === '734100' ? '' : '2000,3000,4000', true, true, true, 'SERVERPARTSHOP_INDEX,BUSINESS_STATE,SHOPSHORTNAME', false, true);
    setTreeView(data)
    console.log('data222', data)
    return data
  })

  const { loading: CommodityLoading, data: CommodityData } = useRequest(async () => {
    const data = await getFieldEnumTree({ FieldExplainField: 'CommodityTypeIds' })
    const obj: any = {}
    if (data && data.length > 0) {
      data.forEach((item: any) => {
        obj[item.value] = item.label
        if (item.children && item.children.length > 0) {
          item.children.forEach((subItem: any) => {
            obj[subItem.value] = subItem.label
            if (subItem.children && subItem.children.length > 0) {
              subItem.children.forEach((thirdItem: any) => {
                obj[thirdItem.value] = thirdItem.label
              })
            }
          })
        }
      })
    }
    return obj
  })

  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const ServerpartIdsList: any = session.get('ServerpartIdsList')
  const SHOPTRADEObj: any = session.get('SHOPTRADEObj')

  const columns: any = [
    {
      title: '商品状态',
      dataIndex: 'COMMODITY_STATE',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: [{ label: "有效", value: '1' }, { label: "无效", value: '0' }]
      },
      // valueEnum: {
      //   0: { text: '无效' },
      //   1: { text: '有效' }
      // },
      initialValue: '1'
    },
    {
      title: '审核时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      initialValue: [moment().subtract(1, 'day').format('YYYY-MM-DD'), moment().subtract(1, 'day').format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            OperateDate_Start: value[0],
            OperateDate_End: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day')
      }
    },
    {
      title: "查询内容",
      dataIndex: "SearchValue",
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入商品名称/商品条码',
      }
    },
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 70,
      align: 'center',
      hideInSearch: true
    },
    {
      title: <div style={{ textAlign: 'center' }}>服务区</div>,
      width: 150,
      dataIndex: 'SERVERPART_ID',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return record?.SERVERPART_ID ? ServerpartIdsList[record?.SERVERPART_ID] : '-'
      }
    },
    {
      title: '商品业态',
      dataIndex: 'BUSINESSTYPE',
      width: 120,
      hideInSearch: true,
      valueType: 'select',
      ellipsis: true,
      align: 'center',
      request: async () => {
        return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'SHOPTRADE', notformate: true })
      }
    },
    {
      title: '商品类型',
      dataIndex: 'COMMODITY_TYPE',
      width: 120,
      hideInSearch: true,
      ellipsis: true,
      align: 'center',
      valueEnum: CommodityData
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品条码</div>,
      width: 150,
      dataIndex: 'COMMODITY_BARCODE',
      ellipsis: true,
      hideInSearch: true,
      align: 'left',
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品名称</div>,
      dataIndex: 'COMMODITY_NAME',
      width: 200,
      ellipsis: true,
      align: 'left',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>零售价</div>,
      width: 120,
      dataIndex: 'COMMODITY_RETAILPRICE',
      align: 'right',
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>进货价</div>,
      width: 120,
      dataIndex: 'COMMODITY_PURCHASEPRICE',
      align: 'right',
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品单位</div>,
      width: 120,
      dataIndex: 'COMMODITY_UNIT',
      align: 'center',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品规格</div>,
      width: 120,
      dataIndex: 'COMMODITY_RULE',
      align: 'center',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>状态</div>,
      width: 120,
      dataIndex: 'COMMODITY_STATE',
      hideInSearch: true,
      align: 'center',
      valueType: 'select',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' } },

    },
    {
      title: '审核时间',
      width: 170,
      align: 'center',
      ellipsis: true,
      dataIndex: 'OPERATE_DATE',
      hideInSearch: true,
      sorter: true,
      defaultSortOrder: 'descend',
    },
  ]

  // 查询的条件
  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 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 === 2)
              setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
              // actionRef?.current?.reload()
              // getData(selectedIds.map(n => n?.value)?.toString() || '')
            }}
          // switcherIcon={<PlusOutlined />}
          /> : ''}
        </ProCard>
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            bordered
            headerTitle={<PageTitleBox props={props} />}
            search={{ span: 6 }}
            scroll={{ x: '100%', y: 'calc(100vh - 450px)' }}
            request={async (params, sorter) => {
              if (!selectedId) {
                return
              }

              const sortArr: string[] = Object.keys(sorter).map(n => {
                const value = sorter[n]
                return value ? `${n} ${value.replace('end', '')}` : ''
              }).filter(Boolean)

              let sortstr = sortArr.join(',')

              if (sortArr.length > 0) {
                const firstSort = sortArr[0]        // 例如 "OPERATE_DATE desc"
                const dir = firstSort.split(/\s+/)[1] || 'desc' // 提取排序方向
                sortstr += `,COMMODITY_ID ${dir}`
              }


              const req: any = {
                ...params,
                SearchType: 4,
                ProvinceCode: currentUser?.ProvinceCode,
                ServerpartShopID: selectedId,
                CommodityState: params?.COMMODITY_STATE,
                PageIndex: 1,
                PageSize: 999999,
                pageSize: 999999,
                SearchKey: "COMMODITY_NAME,COMMODITY_BARCODE",
                SearchValue: params?.SearchValue || '',
                SortStr: sortstr ? sortstr : ""
              }
              console.log('req', req)
              handleCallLogs()
              setSearchParams(params)
              const data = await handleGetCommodityList(req)
              if (data.List && data.List.length > 0) {
                console.log('data', data)
                // setAllTotal(data.TotalCount)

                let fieldData: any = [
                  "COMMODITY_RETAILPRICE",
                  "COMMODITY_PURCHASEPRICE"
                ]

                let enumList: any = ["SERVERPART_ID",
                  "BUSINESSTYPE",
                  "COMMODITY_TYPE",]
                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(data.List)), fieldData, enumList, [ServerpartIdsList, SHOPTRADEObj, CommodityData], [])

                setReqDetailList(newPrintData)
                return { data: data.List, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                // <span style={{ visibility: 'hidden' }}>
                //   <ReactHTMLTableToExcel
                //     buttonText={'导出excel'}
                //     ref={downloadBtnRef}
                //     table="table-to-xls-shopCommodity"
                //     filename={`门店商品查询${searchParams?.StartDate}-${searchParams?.EndDate}`}
                //     sheet="sheet1"
                //   />
                // </span>,
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    if (reqDetailList && reqDetailList.length > 0) {
                      // 尝试一下 导出新方法 
                      exportXlsxFromProColumnsExcelJS(columns,
                        reqDetailList,
                        `门店商品查询${searchParams?.OperateDate_Start}-${searchParams?.OperateDate_End}`,
                         {
                          footerMaker: currentUser?.Name,
                          footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                          footerStatsTime: `${searchParams?.OperateDate_Start}-${searchParams?.OperateDate_End}`
                        }
                      )
                    } else {
                      message.error('暂无数据可导出！')
                    }

                    // if (reqDetailList && reqDetailList.length > 0) {
                    //   setShowLoading(true)
                    //   setTimeout(() => {
                    //     setShowExportTable(true)
                    //     setTimeout(() => {
                    //       exportTable(e)
                    //     }, 100)
                    //   }, 100)
                    // } else {
                    //   message.error('暂无数据可导出！')
                    // }
                  }}
                >
                  导出excel
                </Button>
              ]
            }}
          />
        </div>
      </div>
    </div>
  )
}

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