import { Button, message, Table, Tabs, Tag, Typography } from 'antd'
import React, { useEffect, useState, useRef } from 'react'
import consts from '@/consts'
import { apiAddService } from '@/services/customer'
import { useDispatch } from '@umijs/max'
import ProTable from '@ant-design/pro-table'
import { renderBadge } from '@/pages/Workbench/Dashboard/components/RatioPanels'
import { longleSellStatusNum, longlePreserveStatusNum } from '@/pages/Product/Lock/LockStore/index'
import { ProductLabel } from '@/pages/Product/Lock/LockStore/index'
import { useModal } from '@/components/ModalStore'
import { Plus } from '@icon-park/react'
import classNames from 'classnames'
import { queryRoadPricingListWithParams } from '@/services/product'
import { cloudTitleEnum } from '@/pages/Product/Cloud/components/Detail/Form'
const { TabPane } = Tabs

const ClientTabList = ({ clientId, software, updatePayload }) => {
  const { Text } = Typography
  const dispatch = useDispatch()
  const dispatchModal = useModal()
  const [state, setState] = useState({
    params: {},
    cloud: [],
    loading: false // 云版表格loading
  })
  const clientHeight = (document.body.clientHeight - 124 - 78) / 2 - 54
  const columns = [
    {
      title: '锁号',
      dataIndex: 'keyNum',
      width: 90,
      render: (clientName, record) => (
        <span
          onClick={() =>
            dispatchModal('D_LOCK_DETAIL', {
              dataId: record.id,
              orderIds: software.longle.map(item => item.id)
            })
          }
          className={classNames('cursor-pointer hover:text-hex-967bbd', {
            'text-primary': record.preserveStatus !== 3
          })}>
          {record.preserveStatus === 3 ? (
            <Text delete type="secondary">
              {clientName}
            </Text>
          ) : (
            <span className="text-primary">{clientName}</span>
          )}
        </span>
      )
    },
    {
      title: '产品',
      dataIndex: 'product',
      width: 230,
      render: (_, record) =>
        record.preserveStatus === 3 ? (
          <Text delete type="secondary">
            {record.product}
          </Text>
        ) : (
          <ProductLabel data={record.product} />
        )
    },
    {
      title: '销售状态',
      dataIndex: 'sellStatus',
      width: 90,
      ellipsis: true,
      render: (_, record) =>
        record.preserveStatus === 3 ? (
          <Text delete type="secondary">
            {longleSellStatusNum[record.sellStatus]?.text}
          </Text>
        ) : (
          <>{longleSellStatusNum[record.sellStatus]?.text}</>
        )
    },
    {
      title: '维护状态',
      dataIndex: 'preserveStatus',
      key: 'preserveStatus',
      width: 90,
      ellipsis: true,
      render: (_, record) =>
        record.preserveStatus === 3 ? (
          <Text delete type="secondary">
            {longlePreserveStatusNum[record.preserveStatus]?.text}
          </Text>
        ) : (
          <>{longlePreserveStatusNum[record.preserveStatus]?.text}</>
        )
    },
    {
      title: '责任人',
      dataIndex: 'responsible',
      width: 70,
      ellipsis: true,
      render: (_, record) =>
        record.preserveStatus === 3 ? (
          <Text delete type="secondary">
            {record.responsible}
          </Text>
        ) : (
          <>{record.responsible}</>
        )
    }
  ]

  const cloudColumns = [
    {
      dataIndex: 'project_type',
      title: '云版名称',
      width: '20%',
      filters: Object.keys(cloudTitleEnum).map(item => ({ text: cloudTitleEnum[item], value: item })),
      onFilter: (projectType, record) => record.project_type.toString() === projectType,
      render: text => cloudTitleEnum[text]
    },
    {
      dataIndex: 'mobile',
      title: '账号',
      width: '20%',
      render: (text, record) => (
        <div
          className="text-primary cursor-pointer hover:text-hex-967bbd"
          onClick={() =>
            dispatchModal('D_CLOUD_DETAIL', {
              dataId: record.ssoId,
              projectType: record.project_type
            })
          }>
          {text}
        </div>
      )
    },
    {
      dataIndex: 'real_name',
      title: '姓名',
      width: '20%'
    },
    {
      dataIndex: 'upgrade_list',
      title: '已升级专业版',
      width: '40%',
      render: text => (
        <div className="children:m-2px">
          {text
            .filter(item => item.isUpgrade)
            .map(item => {
              return (
                <Tag color="purple" key={item.compilationID}>
                  {item.name}
                </Tag>
              )
            })}
        </div>
      )
    }
  ]

  const handleAddService = async values => {
    const { code = -1 } = await apiAddService({ ...values, clientId })
    if (code === consts.RET_CODE.SUCCESS) {
      message.success('新增成功')
      // 刷新数据
      dispatch({
        type: 'refresh/commitAction',
        payload: updatePayload
      })
    }
    // 请求完了
    return code === consts.RET_CODE.SUCCESS
  }

  const initCloudData = async () => {
    setState({ ...state, loading: true })
    const { data = [] } = await queryRoadPricingListWithParams({ clientId })
    setState({ ...state, cloud: data, loading: false })
  }

  const handleTabChange = activeKey => {
    if (activeKey === '2') {
      initCloudData()
    }
  }
  useEffect(() => {
    setState({ ...state, params: { ...state.params, clientId } })
  }, [clientId])

  return (
    <div>
      <div className="pl-15px">
        <Tabs onChange={handleTabChange}>
          <TabPane tab={<span>软件锁{renderBadge(software.total, true)}</span>} key="1">
            <div className="sheet-right-panel sheet-panel-has-btn">
            <ProTable
              size="small"
              columns={columns}
              search={false}
              toolBarRender={false}
              params={state.params}
              rowKey={record => record.id}
              dataSource={software.longle}
              pagination={false}
              scroll={{ y: clientHeight }}
            />
            </div>

          </TabPane>
          <TabPane tab="云版" key="2">
            <Table
              className="sheet-right-panel sheet-panel-has-btn"
              loading={state.loading}
              size="small"
              columns={cloudColumns}
              rowKey="_id"
              pagination={false}
              scroll={{ y: clientHeight }}
              dataSource={state.cloud}
            />
          </TabPane>
        </Tabs>
      </div>
      <div className="sheet-btns pl-15px pt-15px :not-first:ml-1">
        <Button
          type="primary"
          ghost
          size="small"
          className="mr-1"
          onClick={() => dispatchModal('M_RECORD_ADD', { onConfirm: handleAddService })}>
          <Plus className="mr-1" /> 添加服务记录
        </Button>
      </div>
    </div>
  )
}

export default ClientTabList
