// 商品自定义归类
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 { Modal, Popconfirm } from "antd";
import { Button, Menu, message, Space, Spin, Tree, Avatar, Select } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnumTree, getServerpartTree } 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 SubMenu from "antd/lib/menu/SubMenu";
import {
  handleDeleteRTUDType,
  handleGetCommodityList,
  handleGetServerpartUDTypeTree, handleRelateUDType, handleSynchroCOMMODITY
} from "@/pages/reports/productControl/setUserDefinedType/service";
import { handleGetShopTypeTree } from "@/pages/DataVerification/list/service";
import { handleGetUSERDEFINEDTYPEList } from "@/pages/reports/productControl/userDefinedType/service";
import { handleGetNestingCOMMODITYTYPETree, handleGetServerpartShopTrade } from "@/pages/reports/productControl/commodityInfo/service";
import './style.less'
import PageTitleBox from "@/components/PageTitleBox";
import session from "@/utils/session";

const setUserDefinedType: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const actionModalRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formModalRef = 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 req: any = {
      ProvinceCode: '734100',
      UserDefinedTypeState: 1
    }
    const data = await handleGetServerpartUDTypeTree(req)
    setTreeView(data)
    return data
  })
  const [commodityList, setCommodityList] = useState<any>()

  // 加载弹出框里面的关联商品的树状选择
  const { loading: modalTreeLoading, data: ModalTreeViews } = useRequest(async () => {
    const req = {
      PROVINCE_CODE: currentUser?.ProvinceCode,
      COMMODITYTYPE_VALID: 1,
      ShowCode: true
    }
    const data = await handleGetNestingCOMMODITYTYPETree(req)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点 type为1时
  const [modalCurrenMenu, setModalCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点 type为1时
  const [selectBusiness, setSelectBusiness] = useState<any>()
  const [customClassList, setCustomClassList] = useState<any>()
  const [correlationModal, setCorrelationModal] = useState<boolean>(false)
  const columns: any = [
    {
      title: '自定义类别',
      dataIndex: 'USERDEFINEDTYPE_ID',
      hideInSearch: true,
      width: 200,
      valueType: 'select',
      render: (_, record) => {
        return <Select
          style={{ width: '180px' }}
          options={customClassList}
          value={record?.USERDEFINEDTYPE_ID || ''}
          onChange={async (e: any) => {
            console.log('e', e)
            console.log('record', record)
            record.USERDEFINEDTYPE_ID = e
            if (e) {
              const req = {
                ...record,
                USERDEFINEDTYPE_ID: e
              }
              const data = await handleSynchroCOMMODITY(req)
              if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                actionRef.current?.reload()
              } else {
                message.error(data.Result_Desc)
              }
            }
          }}
        ></Select>
      }
    },
    {
      title: '商品类型',
      dataIndex: 'COMMODITY_TYPE',
      hideInSearch: true,
      valueType: 'treeSelect',
      request: async () => {
        const data = await handleGetShopTypeTree({ PROVINCE_CODE: currentUser?.ProvinceCode });
        console.log('data', data)
        return data
      },
    },
    {
      title: '商品条码',
      dataIndex: 'COMMODITY_BARCODE',
      hideInSearch: true,
    },
    {
      title: '商品名称',
      dataIndex: 'COMMODITY_NAME',
      hideInSearch: true,
    },
    {
      title: '零售价格',
      dataIndex: 'COMMODITY_RETAILPRICE',
      hideInSearch: true,
    },
    {
      title: '商品单位',
      dataIndex: 'COMMODITY_UNIT',
      hideInSearch: true,
    },
    {
      title: '商品规格',
      dataIndex: 'COMMODITY_RULE',
      hideInSearch: true,
    },
    {
      title: '商品业态',
      dataIndex: 'BUSINESSTYPE',
      valueType: 'select',
      valueEnum: commodityList,
      fieldProps: {
        showSearch: true,
        filterOption: (input: any, option: any) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
      },
      // request: async () => {
      //   const data = await getFieldEnumTree({ FieldExplainField: 'BUSINESSTYPE' })
      //   return data
      // }
    },
    {
      title: '商品状态',
      dataIndex: 'COMMODITY_STATE',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
    },
    {
      title: '审核时间',
      dataIndex: 'OPERATE_DATE',
      hideInSearch: true,
    },
  ]
  const commodityTree = session.get('CommodityTypeIdsTree')

  const toLabelValueMapSimple = (tree: any[]) => {
    const map: Record<string, any> = {};
    const dfs = (nodes: any[]) => {
      if (!nodes) {
        return
      }
      nodes.forEach(n => {
        map[n.value.toString()] = n.label;
        if (n.children?.length) dfs(n.children);
      });
    };
    dfs(tree);
    return map;
  }

  console.log('fdskfsd', toLabelValueMapSimple(commodityTree));



  const modalColumns: any = [
    {
      title: '商品类型',
      width: 120,
      dataIndex: 'COMMODITY_TYPE',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: toLabelValueMapSimple(commodityTree)
    },
    {
      title: '商品条码',
      width: 150,
      dataIndex: 'COMMODITY_BARCODE',
      hideInSearch: true,
    },
    {
      title: '商品名称',
      width: 150,
      ellipsis: true,
      dataIndex: 'COMMODITY_NAME',
      hideInSearch: true,
    },
    {
      title: '零售价格',
      width: 100,
      dataIndex: 'COMMODITY_RETAILPRICE',
      hideInSearch: true,
    },
    {
      title: '商品单位',
      width: 100,
      dataIndex: 'COMMODITY_UNIT',
      hideInSearch: true,
    },
    {
      title: '商品规格',
      width: 120,
      ellipsis: true,
      dataIndex: 'COMMODITY_RULE',
      hideInSearch: true,
    },
    {
      title: '商品业态',
      width: 100,
      dataIndex: 'BUSINESSTYPE',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const data = await getFieldEnumTree({ FieldExplainField: 'BUSINESSTYPE' })
        return data
      }
    },
    {
      title: '商品状态',
      width: 100,
      dataIndex: 'COMMODITY_STATE',
      hideInSearch: true,
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
    },
    {
      title: '商品状态',
      dataIndex: 'CommodityState',
      hideInTable: true,
      initialValue: '1',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
    },
    {
      title: '审核时间',
      width: 180,
      dataIndex: 'OPERATE_DATE',
      hideInSearch: true,
    },
  ]

  const [modalTreeSelect, setModalTreeSelect] = useState<any>()

  // 请求自定义类的选择列表
  const handleGetCustomClassList = async (id: any) => {
    const req: any = {
      SearchParameter: {
        USERDEFINEDTYPE_STATE: 1,
        SERVERPART_ID: currenMenu || '',
        // BUSINESSTYPE: selectBusiness || ''
      },
      PageIndex: 1,
      PageSize: 999999,
      pageSize: 999999,
    }
    const data = await handleGetUSERDEFINEDTYPEList(req)
    if (data && data.length > 0) {
      const list: any = []
      data.forEach((item: any) => {
        list.push({ label: item.USERDEFINEDTYPE_NAME, value: item.USERDEFINEDTYPE_ID })
      })
      setCustomClassList(list)
    }
    console.log('data', data)
  }
  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-setUserDefinedType');                    // 给table添加id，值与按钮上的table字段对应

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

    setShowLoading(false)

    downloadBtnRef.current.handleDownload();
    setShowExportTable(false)
    tempTable.remove() // 防止重复打印一个内容
  }
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()
  // 选中的行数据
  const [selectModalRowList, setSelectModalRowList] = useState<any>()
  // 选中的行
  const [selectedModalOrderRowKeys, setSelectedModalOrderRowKeys] = useState<any>()
  // 选中的行数据
  const [selectRowList, setSelectRowList] = useState<any>()
  // 选中的行
  const [selectedOrderRowKeys, setSelectedOrderRowKeys] = 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('itemitemitem', item);

    // 选中的子菜单key
    const [type, value] = item.key.split('-')
    if (type === '1') {
      setCurrenMenu(value)
      setSelectBusiness(undefined)
      // actionRef?.current?.reload()
    } else if (type === '2') {
      // setCurrenMenu(undefined)
      setSelectBusiness(value)
      // type 为2  那就说明是选择门店了
      let serverpartId: string = item.keyPath[1].split('-')[1]
      handleGetCommodity(serverpartId)
    } else {
      setCurrenMenu(undefined)
      setSelectBusiness(undefined)
    }
  }

  const modalLoadSelectedId = (item?: any) => {
    console.log('item', item)
    // 选中的子菜单key
    const [type, value] = item.key.split('-')
    if (type === '1') {
      if (value === modalTreeSelect) {
        setModalTreeSelect(undefined)
      } else {
        setModalTreeSelect(value)
      }
    } else {
      setModalTreeSelect('')
    }
    // actionModalRef?.current?.reload()
  }

  // 拿到对应的商品业态
  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)
  }

  const modalRowSelection: any = {
    selectedRowKeys: selectedModalOrderRowKeys,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectModalRowList(selectedRows)
      setSelectedModalOrderRowKeys(selectedRowKeys)
    },
  };
  const rowSelection: any = {
    selectedRowKeys: selectedOrderRowKeys,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectRowList(selectedRows)
      setSelectedOrderRowKeys(selectedRowKeys)
    },
  };

  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={[selectBusiness ? `2-${selectBusiness}` : currenMenu ? `1-${currenMenu}` : '']}
            onSelect={(item) => {
              loadSelectedId(item)
            }}
          >
            {getMenuDom(treeViews, loadSelectedId)}
          </Menu>}
        </ProCard>
        <div className={'bigPageTable'} style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            rowKey="COMMODITY_ID"
            bordered
            expandable={{
              expandRowByClick: true
            }}
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            headerTitle={<PageTitleBox props={props} />}
            search={{ span: 6 }}
            request={async (params) => {
              if (!currenMenu && !selectBusiness) {
                return
              }
              setCustomClassList([])
              handleGetCustomClassList()

              const req: any = {
                ...params,
                SearchType: 4,
                ShowJustUDType: true,
                ServerpartID: selectBusiness ? '' : currenMenu,
                UserDefinedTypeId: selectBusiness || '',
                PageSize: 999999,
                pageSize: 999999,
              }
              setSearchParams(params)
              const data = await handleGetCommodityList(req)
              console.log('data', data)
              if (data && data.length > 0) {
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                selectBusiness ?
                  <div>
                    <Button
                      key="new"
                      type="primary"
                      onClick={(e) => {
                        setCorrelationModal(true)
                      }}
                    >
                      关联商品
                    </Button>
                    <Popconfirm  // 删除按钮功能
                      title="确认删除?"
                      onConfirm={async () => {
                        console.log('selectRowList', selectRowList)
                        console.log('selectedOrderRowKeys', selectedOrderRowKeys)
                        if (selectRowList && selectRowList.length > 0) {
                          const list: any = []
                          selectRowList.forEach((item: any) => {
                            list.push({ label: item.USERDEFINEDTYPE_ID, value: item.COMMODITY_ID })
                          })
                          const data = await handleDeleteRTUDType(list)
                          if (data.Result_Code === 100) {
                            message.success(data.Result_Desc)
                            setSelectRowList([])
                            setSelectedOrderRowKeys([])
                            actionRef?.current?.reload()
                          } else {
                            message.error(data.Result_Desc)
                          }
                        } else {
                          message.error('请选择')
                        }
                      }}
                    >
                      <Button style={{ marginLeft: '8px' }}>删除关联</Button>
                    </Popconfirm>

                  </div>
                  : ''
              ]
            }}
          />
        </div>
      </div>

      <Modal
        open={correlationModal}
        width={1400}
        wrapClassName={'shopModal'}
        destroyOnClose
        title={'关联商品'}
        onCancel={() => {
          setCorrelationModal(false)
          setModalTreeSelect(undefined)
        }}
        onOk={async () => {
          // console.log('selectModalRowList',selectModalRowList)
          console.log('selectedModalOrderRowKeys', selectedModalOrderRowKeys)
          console.log('selectBusiness', selectBusiness)
          if (selectedModalOrderRowKeys && selectedModalOrderRowKeys.length > 0) {
            const req: any = []
            selectedModalOrderRowKeys.forEach((item: any) => {
              req.push({ label: selectBusiness, value: item })
            })
            const data = await handleRelateUDType(req)
            if (data.Result_Code === 100) {
              message.success(data.Result_Desc)
              setSelectModalRowList([])
              setSelectedModalOrderRowKeys([])
              setModalTreeSelect(undefined)
              actionRef?.current?.reload()
              setCorrelationModal(false)
            } else {
              message.error(data.Result_Desc)
            }
          } else {
            message.error('请选择要关联的商品')
          }


        }}
      >
        <div style={{ width: '100%', height: '650px', backgroundColor: '#fff', display: 'flex' }}>
          <ProCard
            style={{ width: "300px" }}
            className="pageTable-leftnav"
            bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: "280px" }}
            extra={<MenuFoldOutlined onClick={() => { }} />}
            headerBordered
          >
            {!modalTreeLoading && <Menu
              mode="inline"
              style={{ height: 'calc(100% - 80px)', overflowY: 'auto', overflowX: 'hidden' }}
              selectedKeys={`1-${modalTreeSelect}`}
              onSelect={(item) => {
                modalLoadSelectedId(item)
              }}
            >
              {getMenuDom(ModalTreeViews, modalLoadSelectedId)}
            </Menu>}
          </ProCard>
          <div style={{
            width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
            paddingTop: 0,
            paddingBottom: 0,
            paddingRight: 0
          }}>
            <ProTable
              actionRef={actionModalRef}
              formRef={formModalRef}
              columns={modalColumns}
              rowKey="COMMODITY_ID"
              bordered
              expandable={{
                expandRowByClick: true
              }}
              rowSelection={{
                type: 'checkbox',
                ...modalRowSelection,
              }}
              scroll={{ x: 1000, y: 400 }}
              headerTitle={'未关联商品列表'}
              search={{ span: 6 }}
              request={async (params) => {
                const req: any = {
                  ...params,
                  SearchType: 4,
                  ShowJustUDType: false,
                  ServerpartID: currenMenu || '',
                  // UserDefinedTypeId: selectBusiness || '',
                  CommodityTypeId: modalTreeSelect,
                  PageSize: 999999,
                  pageSize: 999999,
                }
                setSearchParams(params)
                const data = await handleGetCommodityList(req)
                console.log('data', data)
                if (data && data.length > 0) {
                  return { data, success: true }
                }
                return { data: [], success: true }
              }}
            />
          </div>
        </div>
      </Modal>
    </div>
  )
}

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