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, PlusOutlined} from "@ant-design/icons";
import type {FormInstance} from "antd";
import {Avatar, Button, Col, Menu, message, Modal, Row, Space, Spin, Tree} from "antd";
import useRequest from "@ahooksjs/use-request";
import {getFieldEnum, 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 {
  handleGetServerpartShopList,
  handleGetUSERDEFINEDTYPEList, handleSynchroUSERDEFINEDTYPE
} from "@/pages/reports/productControl/userDefinedType/service";
import {
  handleGetServerpartShopTrade,
  handleSynchroCOMMODITY
} from "@/pages/reports/productControl/commodityInfo/service";
import ProForm, {ProFormSelect, ProFormText, ProFormTreeSelect} from "@ant-design/pro-form";
import Draggable from "react-draggable";
import {getServerpartOption} from "@/pages/DataVerification/list/service";
import {handleGetNestingCOMMODITYTYPETree} from "@/pages/reports/productControl/commodityType/service";
import PageTitleBox from "@/components/PageTitleBox";


const userDefinedType: React.FC<{ currentUser: CurrentUser}> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const modalFormRef = 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 [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  const [commodityList,setCommodityList] = useState<any>()
  const [commoditySelectList,setCommoditySelectList] = useState<any>()
  const [showModal,setShowModal] = useState<boolean>(false)
  const [currentRow,setCurrentRow] = useState<any>()
  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
  const [selectShopName,setSelectShopName] = useState<string>('')// 选择的门店名称
  const columns: any = [

    {
      title:'商品业态',
      dataIndex:'BUSINESSTYPE',
      valueType: 'select',
      hideInTable: true,
      valueEnum: commodityList,
    },
    {
      title: '序号',
      valueType: 'index',
      hideInSearch: true
    },
    {
      title:'类别名称',
      dataIndex:'USERDEFINEDTYPE_NAME',
      hideInSearch: true,
      render:(_,record)=>{
        return <a onClick={()=>{
          console.log('record',record)
          setCurrentRow(
            {
              ...record,
              BUSINESSTYPE: record?.BUSINESSTYPE.toString()
            })
          setShowModal(true)
          handleGetCommityList(record.BUSINESSTYPE)
        }}>{record?.USERDEFINEDTYPE_NAME || '-'}</a>
      }
    },
    {
      title:'商品业态',
      dataIndex:'BUSINESSTYPE',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'BUSINESSTYPE', notformate: true });
      },
    },
    {
      title:'门店名称',
      dataIndex:'ShopNames',
      hideInSearch: true
    },
    {
      title:'类别索引',
      dataIndex:'USERDEFINEDTYPE_INDEX',
      hideInSearch: true
    },
    {
      title:'有效状态',
      dataIndex:'USERDEFINEDTYPE_STATE',
      valueType: 'select',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' } },
    },
    {
      title:'操作人员',
      dataIndex:'STAFF_NAME',
      hideInSearch: true
    },
    {
      title:'操作时间',
      dataIndex:'OPERATE_DATE',
      hideInSearch: true,
      sorter: (a, b) => new Date(a.OPERATE_DATE).getTime() - new Date(b.OPERATE_DATE).getTime(),
      defaultSortOrder: 'descend',
    },
  ]
  const draggleRef = React.createRef<any>()
  // 拖动开始
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const onDraggaleStart = (event, uiData) => {

    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
  // 拿到对应的商品业态
  const handleGetCommodity = async (id: any)=>{
    const req: any = {
      ProvinceCode: currentUser?.USER_PROVINCE,
      ServerpartId: id
    }
    const data = await handleGetServerpartShopTrade(req)
    setCommoditySelectList(data)
    console.log('data',data)
    const obj: any = {}
    if (data && data.length>0){
      data.forEach((item: any)=>{
        obj[item.value] = item.label
      })
    }
    setCommodityList(obj)
  }
  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-userDefinedType');                    // 给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)
    } else{
      setCurrenMenu('')
      setCommodityList([])
    }
  }

  const handleGetCommityList = async (SHOPTRADE: any)=>{
    const req = {
      SearchParameter:{
        ISVALID:1,
        SHOPTRADE,
        SERVERPART_ID:currenMenu
      }
    }
    const data = await handleGetServerpartShopList(req)
    console.log('data',data)
    let shopNames: string=''
    if (data && data.length>0){
      data.forEach((item: any)=>{
        if (shopNames){
          shopNames+=`,${item.SHOPNAME}`
        }else{
          shopNames = item.SHOPNAME
        }
      })
    }
    modalFormRef.current.setFieldsValue({
      ShopNames:shopNames
    })
  }


  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
            expandable={{
              expandRowByClick: true
            }}
            headerTitle={<PageTitleBox props={props} />}
            search={{span: 6}}
            request={async(params)=>{
              if (!currenMenu){
                return
              }
              const req = {
                SearchParameter:{
                  ...params,
                  SERVERPART_ID: currenMenu,
                },
                PageIndex: 1,
                PageSize: 999999,
                pageSize: 999999,
              }
              setSearchParams(params)
              const data = await handleGetUSERDEFINEDTYPEList(req)
              console.log('data',data)
              if (data && data.length>0){
                setReqDetailList(data)
                return {data,success: true}
              }
              return {data: [],success: true}
            }}
            toolbar={{
              actions: [
                <Button
                  key="new"
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={async (e) => {
                    setShowModal(true)
                    handleGetCommityList(1000)
                  }}
                >
                  添加类别
                </Button>
              ]
            }}
          />
        </div>
      </div>
      <Modal
        open={showModal}
        width={1000}
        destroyOnClose
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDraggleDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDraggleDisabled(true)
            }}
            onFocus={() => { }}
            onBlur={() => { }}
          >
            {currentRow?'编辑类型':'添加类型'}
          </div>
        }
        onOk={()=>{
          // handleSynchroUSERDEFINEDTYPE
          modalFormRef.current?.validateFields().then(async (res: any)=>{
            if (res){
              let req: any = {}
              if (currentRow){
                req = {
                  ...currentRow,
                  ...res,
                }
              }else{
                req= {
                  ...res,
                }
              }
              const data = await handleSynchroUSERDEFINEDTYPE(req)
              if (data.Result_Code===100){
                message.success(data.Result_Desc)
                actionRef.current?.reload()
                setShowModal(false)
                setCurrentRow(undefined)
              }else{
                message.error(data.Result_Desc)
              }
            }
          })
        }}
        onCancel={()=>{
          setShowModal(false)
          setCurrentRow(undefined)
          setSelectShopName('')
        }}
        modalRender={(modal) => {
          return <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        }}
      >
        <ProForm
          formRef={modalFormRef}
          submitter={false}
          initialValues={currentRow}
        >
          <Row gutter={32}>
            <Col span={12}>
              <ProFormSelect
                label="服务区名"
                name="SERVERPART_ID"
                disabled
                initialValue={currentRow?.SERVERPART_ID || Number(currenMenu)}
                request={async ()=>{
                  const data = await getServerpartOption()
                  console.log('服务区名',data)
                  return data
                }}
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                label="门店业态"
                name="BUSINESSTYPE"
                options={commoditySelectList}
                initialValue={currentRow?.BUSINESSTYPE || '1000'}
                rules={[
                  {
                    required: true,
                    message: '请选择门店业态',
                  },
                ]}
                fieldProps={{
                  onChange:async (e: any)=> {
                    if (e){
                      const req = {
                        SearchParameter:{
                          ISVALID:1,
                          SHOPTRADE:e,
                          SERVERPART_ID:currenMenu
                        }
                      }
                      const data = await handleGetServerpartShopList(req)
                      console.log('data',data)
                      let shopNames: string=''
                      if (data && data.length>0){
                        data.forEach((item: any)=>{
                          if (shopNames){
                            shopNames+=`,${item.SHOPNAME}`
                          }else{
                            shopNames = item.SHOPNAME
                          }
                        })
                      }
                      modalFormRef.current.setFieldsValue({
                        ShopNames:shopNames
                      })
                      // setSelectShopName(shopNames)
                    }else{
                      modalFormRef.current.setFieldsValue({
                        ShopNames:''
                      })
                    }
                  }
                }}
              />
            </Col>

            <Col span={12}>
              <ProFormTreeSelect
                label="父级类别"
                name="USERDEFINEDTYPE_PID"
                disabled
                initialValue={-1}
                request={async ()=>{
                  const req = {
                    PROVINCE_CODE: currentUser?.ProvinceCode,
                  }
                  const data = await handleGetNestingCOMMODITYTYPETree(req)
                  const list = [
                    {
                      title:'默认类别',
                      value: -1,
                      type:0,
                      children: data
                    }
                  ]
                  return list
                }}
              />
            </Col>
            <Col span={12}>
              <ProFormText
                label="门店名称"
                name="ShopNames"
                disabled
                initialValue={selectShopName}
              />
            </Col>

            <Col span={12}>
              <ProFormText
                label="类别名称"
                name="USERDEFINEDTYPE_NAME"
                rules={[
                  {
                    required: true,
                    message: '请输入类别名称',
                  },
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormText
                label="类别索引"
                name="USERDEFINEDTYPE_INDEX"
                rules={[
                  {
                    required: true,
                    message: '请输入类别索引',
                  },
                ]}
              />
            </Col>

            <Col span={12}>
              <ProFormSelect
                label="有效状态"
                name="USERDEFINEDTYPE_STATE"
                options={[{label:'无效',value:0},{label:'有效',value:1},{label:'不可选',value:2}]}
                rules={[
                  {
                    required: true,
                    message: '请选择有效状态',
                  },
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormText
                label="操作人员"
                name="STAFF_NAME"
                disabled
                initialValue={currentUser.Name}
              />
            </Col>
          </Row>
        </ProForm>
      </Modal>
    </div>
  )
}

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