import React, { useEffect, useState, useRef } from 'react'
import { Tag, Tooltip, Input, Button } from 'antd'
import consts from '@/consts'
import { connect } from '@@/plugin-dva'
import { useModel } from '@umijs/max'
import { queryLock } from '@/services/product'
import { generateSortField } from '@/utils/utils'
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 { useModal } from '@/components/ModalStore'
import { PageContainer } from '@ant-design/pro-layout'

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

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

const LockStore = ({ prodList = [], dispatch, shouldUpdate }) => {
  const tRef = useRef()
  const dispatchModal = useModal()
  const refreshData = () => {
    tRef.current?.reload()
  }

  const { initialState: { permData } = { permData: {} } } = useModel('@@initialState')
  const [state, setState] = useState({
    data: [],
    totalOld: 0, // 待接收锁总数
    totalNew: 0,
    orderIds: []
  })

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

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

  const columns = [
    {
      title: '锁号',
      dataIndex: 'keyNum',
      width: 90,
      fixed: 'left',
      render: (keyNum, record) => (
        <span
          onClick={() => dispatchModal('D_LOCK_DETAIL', { dataId: record.id, orderIds: state.orderIds })}
          className="text-primary cursor-pointer hover:text-hex-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: 95,
      filters: true,
      filterMultiple: false,
      valueEnum: {
        1: { text: '生成' },
        2: { text: '接收' }
      },
      render: (_, { stockStatus }) => {
        return <>{longleStockStatusNum[stockStatus]?.text}</>
      }
    },
    {
      title: '出库时间',
      dataIndex: 'stockTime',
      valueType: 'date',
      key: 'stockTime',
      filterDropdown: filterDropdownProps => <FilterDatePicker {...filterDropdownProps} />,
      filters: true,
      sorter: true,
      width: 110
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   width: 60,
    //   filters: true,
    //   onFilter: true,
    //   valueType: 'select',
    //   valueEnum: longleStatusNum,
    //   renderText: (_, { status }) => longleStatusNum[status]?.text
    // },
    {
      title: '销售状态',
      dataIndex: 'sellStatus',
      key: 'sellStatus',
      width: 95,
      filters: true,
      filterMultiple: false,
      valueEnum: {
        99: { text: '未销售' },
        1: { text: '借出' },
        2: { text: '销售' },
        3: { text: '赠送' }
      },
      render: (_, { sellStatus }) => {
        return <>{longleSellStatusNum[sellStatus]?.text}</>
      }
    },
    {
      title: '销售时间',
      dataIndex: 'sellTime',
      key: 'sellTime',
      filterDropdown: filterDropdownProps => <FilterDatePicker {...filterDropdownProps} />,
      filters: true,
      sorter: true,
      width: 110
    },
    {
      title: '维护状态',
      dataIndex: 'preserveStatus',
      key: 'preserveStatus',
      width: 95,
      filters: true,
      filterMultiple: false,
      valueEnum: {
        1: { text: '升级' },
        2: { text: '更换' },
        3: { text: '收回' },
        99: { text: '无维护' }
      },
      render: (_, { preserveStatus }) => {
        return <>{longlePreserveStatusNum[preserveStatus]?.text}</>
      }
    },
    {
      title: '维护时间',
      dataIndex: 'preserveTime',
      key: 'preserveTime',
      valueType: 'date',
      width: 95
    },
    {
      title: '客户',
      dataIndex: 'client',
      key: 'client',
      sorter: true,
      width: 150,
      render: (text, record) => (
        <span
          onClick={() => dispatchModal('D_CLIENT_DETAIL', { updateKey: 'longle', dataId: record.clientId })}
          className="text-primary cursor-pointer hover:text-hex-967bbd">
          {text}
        </span>
      )
    },
    {
      title: '单位名称',
      dataIndex: 'customerName',
      key: 'customerName',
      sorter: true,
      width: 300,
      render: (text, record) => (
        <span
          onClick={() =>
            record.customerId &&
            dispatchModal('D_COMPANY_DETAIL', { updateKey: 'longle', dataId: record.customerId })
          }
          className="text-primary cursor-pointer hover:text-hex-967bbd">
          {text}
        </span>
      )
    },
    {
      title: '负责人',
      dataIndex: 'responsible',
      width: 80,
      render: (text, record) => (
        <span
          onClick={() =>
            dispatchModal('D_SOFTWARE_DETAIL', {
              updateKey: 'longle',
              dataId: record.responsibleId
            })
          }
          className="text-primary cursor-pointer hover:text-hex-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 [defaultPermAuthCache] = getPermAuthCache(PermDataTypeEunm.PRODUCT)
  return (
    <PageContainer title={false} breadcrumb={false}>
      <BasicTable
        rowKey={record => record.id}
        mainMenuType="product"
        columnStateType="LOCKSTORE"
        search={false}
        actionRef={tRef}
        params={state.params}
        columns={columns}
        request={async (params, sort, filter) => {
          const {
            code = -1,
            data: { longle = [], total = 0, totalOld = 0, totalNew = 0 } = {
              longle: [],
              total: 0,
              totalOld: 0,
              totalNew: 0
            }
          } = await queryLock({ ...params, ...sort, ...filter })
          setState({ ...state, totalOld, totalNew, orderIds: longle.map(item => item.id) })
          return {
            data: longle,
            success: code === consts.RET_CODE.SUCCESS,
            total
          }
        }}
        columnsStateMap={columnsStateMap}
        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>
          // ]
        }}
      />
    </PageContainer>
  )
}

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