// 商品快捷键管理
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 { Avatar, Button, Drawer, Menu, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnum, 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 {
  handleGetCommodityList,
  handleGetNestingCOMMODITYTYPETree,
  handleGetServerpartShopTrade,
  handleSynchroCOMMODITY
} from "@/pages/reports/productControl/commodityInfo/service";
import SubMenu from "antd/lib/menu/SubMenu";
import Detail from "@/pages/reports/productControl/components/detail";
import PageTitleBox from "@/components/PageTitleBox";
import session from "@/utils/session";
import { formatTreeData } from "@/utils/format";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import moment from 'moment'


const hotkeyset: 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 [detailTreeView, setDetailTreeView] = 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 SHOPTRADEObj = session.get('SHOPTRADEObj')

  const { loading: treeViewsLoading, data: detailTreeViews } = useRequest(async () => {
    const req = {
      PROVINCE_CODE: currentUser?.ProvinceCode,
      COMMODITYTYPE_VALID: 1,
      ShowCode: true
    }
    const data = await handleGetNestingCOMMODITYTYPETree(req)
    setDetailTreeView(data)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  const [commodityList, setCommodityList] = useState<any>()
  const [showDetail, setShowDetail] = useState<boolean>(false)
  const [currentRow, setCurrentRow] = useState<any>()
  // 显示快捷键值的编辑
  const [showHotKeyEdit, setShowHotKeyEdit] = useState<boolean>(false)
  // 编辑的快捷键值
  const [getNewHotKey, setGetNewHotKey] = useState<string>('')

  const columns: any = [
    {
      title: '商品业态',
      dataIndex: 'ShopTrade',
      hideInTable: true,
      valueType: 'select',
      // initialValue: '1000',
      valueEnum: commodityList,
      fieldProps: {
        showSearch: true,
        filterOption: (input: any, option: any) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
      },
      // request: async () => {
      //   return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'SHOPTRADE', notformate: true })
      // }
    },
    {
      title: '商品状态',
      dataIndex: 'CommodityState',
      hideInTable: true,
      valueType: 'select',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },

      initialValue: '1'
    },
    {
      title: '序号',
      width: 70,
      dataIndex: 'index',
      valueType: 'index',
      hieInSearch: true
    },
    {
      title: <div style={{ textAlign: 'center' }}>快捷键</div>,
      dataIndex: 'COMMODITY_HOTKEY',
      width: 90,
      align: 'left',
      hideInSearch: true,
      render: (_, record) => {
        return record?.COMMODITY_HOTKEY && record?.COMMODITY_HOTKEY !== "" ?
          <a style={{ cursor: 'pointer' }} onClick={() => {
            setCurrentRow(record)
            setShowHotKeyEdit(true)
            setShowDetail(true)
          }}>{record?.COMMODITY_HOTKEY}</a> :
          <span onClick={() => {
            setCurrentRow(record)
            setShowHotKeyEdit(true)
            setShowDetail(true)
          }} style={{ color: 'red', cursor: 'pointer' }}>未设置</span>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品条码</div>,
      dataIndex: 'COMMODITY_BARCODE',
      hideInSearch: true,
      width: 120,
      align: 'left',
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品名称</div>,
      dataIndex: 'COMMODITY_NAME',
      width: 200,
      ellipsis: true,
      align: 'left',
      hideInSearch: true,
      render: (_, record) => {
        return <a onClick={() => {
          setCurrentRow(record)
          setShowDetail(true)
        }}>
          {record?.COMMODITY_NAME || '-'}
        </a>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品单位</div>,
      dataIndex: 'COMMODITY_UNIT',
      width: 100,
      ellipsis: true,
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品规格</div>,
      dataIndex: 'COMMODITY_RULE',
      width: 100,
      ellipsis: true,
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>零售价格</div>,
      dataIndex: 'COMMODITY_RETAILPRICE',
      width: 100,
      ellipsis: true,
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品业态</div>,
      dataIndex: 'BUSINESSTYPE',
      width: 100,
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
      valueType: 'select',
      request: async () => {
        return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'SHOPTRADE', notformate: true })
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>商品状态</div>,
      dataIndex: 'COMMODITY_STATE',
      width: 100,
      ellipsis: true,
      align: 'center',
      valueType: 'select',
      hideInSearch: true,
      valueEnum: {
        0: { text: '无效' },
        1: { text: '有效' }
      },
      initialValue: '1'
    },
    {
      title: <div style={{ textAlign: 'center' }}>审核时间</div>,
      dataIndex: 'OPERATE_DATE',
      width: 140,
      ellipsis: true,
      align: 'left',
      hideInSearch: true,
    },
  ]

  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName('saleReportHideBox')[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-hotkeyset');                    // 给table添加id，值与按钮上的table字段对应

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

    setShowLoading(false)

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

  const getMenuDom = (data: any[], callback: (item: any) => void) => {
    return (data.map((element: any) => {
      // 绑定嵌套树的子节点
      if (element.children && element.children.length > 0) {
        return (
          <SubMenu title={<span>{element.label}</span>}
            icon={element.ico ? <Avatar src={element.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
            key={`${element.key || element.value}`}
            onTitleClick={(item) => {
              // 选中一级菜单
              if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                callback.call(callback, item)
              }
              item.domEvent.stopPropagation();
            }}
          >
            {element.children && element.children.length > 0 && getMenuDom(element.children, callback)}
          </SubMenu>
        )
      }
      return (<Menu.Item icon={element.ico ? <Avatar src={element.ico} size={16} shape="square" /> : null}
        key={`${element.key || element.value}`}>{element.desc && element.desc !== '0/0' ? <><span>{element.label}</span>
          <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px' }}>
            [<span style={{ color: 'red' }}>{element.desc.split('/')[0]}</span>/<span style={{ color: '#1890ff' }}>{element.desc.split('/')[1]}</span>]</span></> : element.label}</Menu.Item>)
    }))
  }

  const loadSelectedId = (item?: any) => {
    console.log('item', item)
    // 选中的子菜单key
    const [type, value] = item.key.split('-')
    if (type === '1') {
      setCurrenMenu(value)
      handleGetCommodity(value)
      // actionRef?.current?.reload()
    } else {
      setCurrenMenu('')
      setCommodityList([])
    }
  }

  // 拿到对应的商品业态
  const handleGetCommodity = async (id: any) => {
    const req: any = {
      ProvinceCode: currentUser?.ProvinceCode,
      ServerpartId: id
    }
    const data = await handleGetServerpartShopTrade(req)
    console.log('data', data)
    const obj: any = {}
    if (data && data.length > 0) {
      data.forEach((item: any) => {
        obj[item.value] = item.label
      })
    }
    setCommodityList(obj)
  }

  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={'saleReportHideBox'} 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}
        >
          {!treeLoading && <Menu
            mode="inline"
            style={{ height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
            selectedKeys={`1-${currenMenu}`}
            onSelect={(item) => {
              console.log('item', item)
              loadSelectedId(item)
            }}
          >
            {getMenuDom(treeViews, loadSelectedId)}
          </Menu>}
        </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) => {
              if (!currenMenu) {
                return
              }

              const req: any = {
                SearchType: 4,
                ProvinceCode: currentUser?.ProvinceCode,
                ServerpartID: currenMenu,
                CommodityState: params.CommodityState,
                ShopTrade: params.ShopTrade,
                PageIndex: 1,
                PageSize: 999999
              }
              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",
                ]
                let enumList: any = [
                  "BUSINESSTYPE",
                  "COMMODITY_STATE"
                ]
                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(data.List)), fieldData, enumList, [SHOPTRADEObj, { 0: "无效", 1: "有效" }], [])

                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-hotkeyset"
                //     filename={`商品快捷键管理报表`}
                //     sheet="sheet1"
                //   />
                // </span>,
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    if (reqDetailList && reqDetailList.length > 0) {
                      // 尝试一下 导出新方法 
                      exportXlsxFromProColumnsExcelJS(columns,
                        reqDetailList,
                        `商品快捷键管理报表`,
                        {
                          footerMaker: currentUser?.Name,
                          footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                          footerStatsTime: ""
                        }
                      )
                    } 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>

      <Drawer
        width={'60%'}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined)
          setShowDetail(false)
          setShowHotKeyEdit(false)
        }}
        bodyStyle={{ padding: '24px' }}
        closable={false}
        destroyOnClose
        footer={
          <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
            <Button type={'primary'} onClick={async () => {
              const req: any = {
                ...currentRow,
                COMMODITY_HOTKEY: getNewHotKey
              }
              console.log('req', req)
              const data = await handleSynchroCOMMODITY(req)
              if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                actionRef.current?.reload()
                setCurrentRow(undefined)
                setShowDetail(false)
                setShowHotKeyEdit(false)
              } else {
                message.error(data.Result_Desc)
              }
            }}>确认</Button>
          </div>
        }
      >
        <Detail showHotKeyEdit={showHotKeyEdit} currentRow={currentRow} currentUser={currentUser} treeView={detailTreeView} setGetNewHotKey={setGetNewHotKey} />
      </Drawer>
    </div>
  )
}

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