import React, { useEffect, useState, useRef } from 'react'
import { Tag, Tooltip, Input, Button } from 'antd'
import consts from '@/consts'
import { useModel, connect } from 'umi'
import { queryLock } from '@/services/product'
import LocksDetail from '@/pages/Product/Lock/LockStore/components/LocksDetail'
import ContactDetail from '@/pages/Customer/Client/components/ClientDetail'
import SoftwareDetail from '@/pages/Product/Lock/LockStore/components/SoftwareDetail'
import { useModal } from '@/components/Modal'
import CompanyDetail from '@/pages/Customer/Company/components/CompanyDetail'
import { refactorSortField } from '@/utils/utils'
import ReceiveLock from './components/ReceiveLock'
// import ReceiveNewLock from './components/ReceiveNewLock'
import { PermDataTypeEunm } from '@/pages/Customer/Company/components/PermSelect'
import BasicTable from '@/components/Table'
import { getPermAuthCache } from '@/utils/auth'
import FilterDatePicker from '@/components/Table/src/components/FilterDatePicker'
// import { DownOutlined } from '@ant-design/icons'

// 渲染产品标签
export const ProductLabel = ({ data }) => {
  if (!data) return null
  let newData
  if (!Array.isArray(data)) {
    newData = data.split('+')
  }
  return (
    <div className="children:m-2px">
      {newData.map((item, idx) => (
        <Tag color="purple" key={item + idx}>
          {item}
        </Tag>
      ))}
    </div>
  )
}

// const longleStatusNum = {
//   1: {
//     text: '生成'
//   },
//   2: {
//     text: '接收'
//   },
//   3: {
//     text: '借出'
//   },
//   4: {
//     text: '销售'
//   },
//   5: {
//     text: '升级'
//   },
//   6: {
//     text: '更换'
//   },
//   7: {
//     text: '收回'
//   },
//   8: {
//     text: '备注'
//   },
//   9: {
//     text: '赠送'
//   }
// }

// 出库状态
const longleStockStatusNum = {
  1: { text: '生成' },
  2: { text: '接收' }
}
// 销售状态
export const longleSellStatusNum = {
  1: { text: '借出' },
  2: { text: '销售' },
  3: { text: '赠送' }
}
// 维护状态
const longlePreserveStatusNum = {
  1: { text: '升级' },
  2: { text: '更换' },
  3: { text: '收回' }
}

const LockStore = ({ prodList = [], dispatch, shouldUpdate }) => {
  const tRef = useRef()
  const { toggleDrawer, setDrawerProps, toggleModal, setModalProps } = useModal()
  // 刷新
  const refreshData = () => {
    tRef.current?.reload()
  }
  const showReceiveLockModal = () => {
    setModalProps({
      width: '60vw',
      modalRender: () => <ReceiveLock refresh={refreshData} />,
      onCancel: () => toggleModal()
    })
    toggleModal()
  }
  // const showReceiveNewLockModal = () => {
  //   setModalProps({
  //     width: '60vw',
  //     modalRender: () => <ReceiveNewLock refresh={refreshData} />,
  //     onCancel: () => toggleModal()
  //   })
  //   toggleModal()
  // }
  const { initialState: { permData } = { permData: {} } } = useModel('@@initialState')
  const [state, setState] = useState({
    data: [],
    totalOld: 0, // 待接收锁总数
    totalNew: 0,
    orderIds: []
  })

  const handleSearch = value => {
    setState({ ...state, params: { ...state.params, search: value } })
  }

  useEffect(() => {
    // 获取软件锁产品列表
    function fetchSoftProducts() {
      dispatch({
        type: 'lock/fetchProdList'
      })
    }
    if (!prodList?.length) {
      fetchSoftProducts()
    }
    if (shouldUpdate) {
      tRef.current.reload()
    }
  }, [shouldUpdate])

  // 展示drawer
  const showDrawer = id => {
    setDrawerProps({
      closable: true,
      onClose: () => toggleDrawer(),
      bodyStyle: {
        height: '100vh'
        // overflowY: 'hidden'
      },
      children: <LocksDetail dataId={id} orderIds={state.orderIds} />
    })
    toggleDrawer()
  }
  // 展示DrawerClient
  const showDrawerClient = id => {
    setDrawerProps({
      closable: true,
      onClose: () => toggleDrawer(),
      bodyStyle: {
        height: '100vh',
        overflowY: 'hidden'
      },
      children: <ContactDetail dataId={id} />
    })
    toggleDrawer()
  }
  // 展示DrawerResponsible
  const showDrawerResponsible = id => {
    setDrawerProps({
      closable: true,
      onClose: () => toggleDrawer(),
      bodyStyle: {
        height: '100vh',
        overflowY: 'hidden'
      },
      children: <SoftwareDetail dataId={id} />
    })
    toggleDrawer()
  }

  // 展示单位详情抽屉
  const showCompanyDrawer = id => {
    setDrawerProps({
      closable: true,
      onClose: () => toggleDrawer(),
      bodyStyle: {
        height: '100vh',
        overflowY: 'hidden'
      },
      children: <CompanyDetail dataId={id} updateKey="longle" />
    })
    toggleDrawer()
  }

  const columns = [
    {
      title: '锁号',
      dataIndex: 'keyNum',
      width: 90,
      fixed: 'left',
      render: (keyNum, record) => (
        <span
          onClick={() => showDrawer(record.id)}
          className="text-primary cursor-pointer hover:text-[#967bbd]"
        >
          {keyNum}
        </span>
      )
    },
    {
      title: '产品',
      dataIndex: 'product',
      key: 'product',
      width: 200,
      fixed: 'left',
      filters: true,
      filterMultiple: false,
      valueEnum: prodList.reduce((prev, curr) => {
        const obj = { ...prev }
        obj[curr.title] = {
          text: curr.title
        }
        return obj
      }, {}),
      render: (_, record) => <ProductLabel data={record.product} />
    },
    {
      title: '出库状态',
      dataIndex: 'stockStatus',
      key: 'stockStatus',
      width: 70,
      render: (_, { stockStatus }) => {
        return <>{longleStockStatusNum[stockStatus]?.text}</>
      }
    },
    {
      title: '出库时间',
      dataIndex: 'stockTime',
      valueType: 'date',
      key: 'stockTime',
      filterDropdown: filterDropdownProps => <FilterDatePicker {...filterDropdownProps} />,
      filters: true,
      sorter: true,
      width: 100
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   width: 60,
    //   filters: true,
    //   onFilter: true,
    //   valueType: 'select',
    //   valueEnum: longleStatusNum,
    //   renderText: (_, { status }) => longleStatusNum[status]?.text
    // },
    {
      title: '销售状态',
      dataIndex: 'sellStatus',
      key: 'sellStatus',
      width: 70,
      render: (_, { sellStatus }) => {
        return <>{longleSellStatusNum[sellStatus]?.text}</>
      }
    },
    {
      title: '销售时间',
      dataIndex: 'sellTime',
      valueType: 'date',
      key: 'sellTime',
      width: 90
    },
    {
      title: '维护状态',
      dataIndex: 'preserveStatus',
      key: 'preserveStatus',
      width: 60,
      render: (_, { preserveStatus }) => {
        return <>{longlePreserveStatusNum[preserveStatus]?.text}</>
      }
    },
    {
      title: '维护时间',
      dataIndex: 'preserveTime',
      key: 'preserveTime',
      valueType: 'date',
      width: 90
    },
    {
      title: '客户',
      dataIndex: 'client',
      key: 'client',
      sorter: true,
      width: 150,
      render: (text, record) => (
        <span
          onClick={() => showDrawerClient(record.clientId)}
          className="text-primary cursor-pointer hover:text-[#967bbd]"
        >
          {text}
        </span>
      )
    },
    {
      title: '单位名称',
      dataIndex: 'customerName',
      key: 'customerName',
      sorter: true,
      width: 300,
      render: (text, record) => (
        <span
          onClick={() => showCompanyDrawer(record.customerId)}
          className="text-primary cursor-pointer hover:text-[#967bbd]"
        >
          {text}
        </span>
      )
    },
    {
      title: '负责人',
      dataIndex: 'responsible',
      width: 80,
      render: (text, record) => (
        <span
          onClick={() => showDrawerResponsible(record.responsibleId)}
          className="text-primary cursor-pointer hover:text-[#967bbd]"
        >
          {text}
        </span>
      )
    },
    {
      title: '期限',
      dataIndex: 'allotedTime',
      width: 90
    },
    {
      title: '办事处',
      dataIndex: 'category',
      width: 90
    },
    {
      title: '纵横部门',
      dataIndex: 'departmentName',
      width: 90
    }
  ]
  const columnsStateMap = {
    preserveStatus: {
      show: false
    },
    preserveTime: {
      show: false
    }
  }

  // const dropDownMenClick = ({ key }) => {
  //   if (key === '1') {
  //     showReceiveLockModal()
  //   } else {
  //     showReceiveNewLockModal()
  //   }
  // }

  const [defaultPermAuthCache] = getPermAuthCache(PermDataTypeEunm.PRODUCT)
  return (
    <BasicTable
      rowKey={record => record.id}
      mainMenuType="product"
      columnStateType="LOCKSTORE"
      search={false}
      actionRef={tRef}
      params={state.params}
      columns={columns}
      request={async (params, sort, filter) => {
        const srotOrder = refactorSortField(sort)
        const {
          code = -1,
          data: { longle = [], total = 0, totalOld = 0, totalNew = 0 } = {
            longle: [],
            total: 0,
            totalOld: 0,
            totalNew: 0
          }
        } = await queryLock({ ...params, ...srotOrder, ...filter })
        setState({ ...state, totalOld, totalNew, orderIds: longle.map(item => item.id) })
        return {
          data: longle,
          success: code === consts.RET_CODE.SUCCESS,
          total
        }
      }}
      columnsStateMap={columnsStateMap}
      headerTitle={
        // <Dropdown
        //   trigger="click"
        //   overlay={
        //     <Menu onClick={dropDownMenClick}>
        //       {state.totalOld ? <Menu.Item key="1">接收旧锁</Menu.Item> : null}

        //       {state.totalNew ? <Menu.Item key="2">接收新锁</Menu.Item> : null}
        //     </Menu>
        //   }>
        //   <Button>
        //     接收锁
        //     <DownOutlined />
        //   </Button>
        // </Dropdown>
        state.totalOld ? (
          <Button type="primary" onClick={showReceiveLockModal}>
            接收旧锁({state.totalOld})
          </Button>
        ) : null
      }
      toolbar={{
        search: (
          <Tooltip placement="bottom" title="输入软件锁号">
            <Input.Search
              style={{ width: '300px' }}
              allowClear={true}
              placeholder={`在${
                permData[PermDataTypeEunm.PRODUCT]?.find(
                  item => item.value === defaultPermAuthCache
                )?.label
              }下搜索`}
              onSearch={handleSearch}
            />
          </Tooltip>
        )
        // actions: [
        //   <Tooltip title="产品出库时间" key="date">
        //     <DatePicker.RangePicker
        //       bordered={false}
        //       onChange={time => {
        //         const [time1, time2] = time || [null, null]
        //         setState({
        //           ...state,
        //           params: {
        //             ...state.params,
        //             beginTime: time1 ? time1.format('YYYY-MM-DD') : null,
        //             endTime: time2 ? time2.format('YYYY-MM-DD') : null
        //           }
        //         })
        //       }}
        //     />
        //   </Tooltip>
        // ]
      }}
    />
  )
}

export default connect(({ lock, refresh }) => ({
  prodList: lock.prodList,
  shouldUpdate: refresh.longle
}))(LockStore)
