import { Button, Popconfirm, Tabs } from 'antd'
import React, { useMemo } from 'react'
import { dayjsFormat } from '@/utils/utils'
import classNames from 'classnames'
import { isDevMode } from '@/utils/env'
import { VList } from 'virtuallist-antd'
import consts from '@/consts'
import type { ProColumns } from '@ant-design/pro-table'
import ProTable from '@ant-design/pro-table'
import {
  updateCustomerService,
  delCustomerService,
  updateClientService,
  delClientService
} from '@/services/customer'
import { useModal } from '@/components/ModalStore'
import { useDispatch, useRequest } from '@umijs/max'
const { TabPane } = Tabs

export enum Servicelog {
  /** 上门服务 */
  VISIT = '1',
  /** 电话拜访 */
  CALL = '2',
  /** 其他事项 */
  OTHER = '3',
  /** 在线服务 */
  ONLINE = '4'
}

export enum ServiceLogType {
  CLIENT,
  COMPANY
}

export const servicelogEnum = {
  [Servicelog.VISIT]: {
    title: '上门服务',
    bg: 'bg-hex-886ab5',
    text: 'text-hex-886ab5',
    border: 'border-hex-886ab5'
  },
  [Servicelog.CALL]: {
    title: '电话拜访',
    bg: 'bg-hex-246daf',
    text: 'text-hex-246daf',
    border: 'border-hex-246daf'
  },
  [Servicelog.OTHER]: {
    title: '其他事项',
    bg: 'bg-hex-1ca081',
    text: 'text-hex-1ca081',
    border: 'border-hex-1ca081'
  },
  [Servicelog.ONLINE]: {
    title: '在线服务',
    bg: 'bg-hex-b8795e',
    text: 'text-hex-b8795e ',
    border: 'border-hex-b8795e'
  }
}

type ClientLowerListProps = {
  logList: {
    log: any[]
  }
  serviceList: API.ServiceLogItem[]
  updatePayload: { main: string; target: string }
}

type ServiceLogItemProps = {
  item: API.ServiceLogItem
  logType: ServiceLogType
  updatePayload: { main: string; target: string }
}
export const ServiceLogItem: React.FC<ServiceLogItemProps> = ({ item, logType, updatePayload }) => {
  const dispatchModal = useModal()
  const dispatch = useDispatch()
  const { run: truUpdate } = useRequest(
    logType === ServiceLogType.COMPANY ? updateCustomerService : updateClientService,
    {
      manual: true,
      onSuccess: () => {
        dispatch({
          type: 'refresh/commitAction',
          payload: updatePayload
        })
      }
    }
  )
  const { run: truDel } = useRequest(
    logType === ServiceLogType.COMPANY ? delCustomerService : delClientService,
    {
      manual: true,
      onSuccess: () => {
        dispatch({
          type: 'refresh/commitAction',
          payload: updatePayload
        })
      }
    }
  )

  const handleOnEdit = async (defaultValues: API.ServiceLogItem) => {
    dispatchModal('M_RECORD_ADD', { defaultValues, onConfirm: truUpdate })
  }
  return (
    <div
      className={classNames(
        'w-full rounded border-l-2px bg-opacity-6',
        servicelogEnum[item.status]?.bg,
        servicelogEnum[item.status]?.border
      )}>
      <div className="p-3 flex flex-col">
        <div className="flex justify-between">
          <div className="flex">
            <div
              className="rounded-1/2 w-8 h-8"
              style={{
                backgroundImage: `url(${
                  (isDevMode() ? 'http://cld2qa.com' : 'http://127.0.0.1') +
                  (item.avatar ?? consts.DEFAULT_AVATAR)
                })`,
                backgroundSize: 'cover'
              }}
            />
            <div className="flex flex-col items-center ml-2">
              <div className="text-sm font-medium text-opacity-80 text-black">{item.staffName}</div>
              <div className="text-xs text-opacity-40 text-black h-4">
                {dayjsFormat(item.createTime, 'HH:mm:ss')}
              </div>
            </div>
          </div>
          <div className="flex flex-nowrap">
            <div className={classNames(servicelogEnum[item.status]?.text, 'font-medium text-sm')}>
              {servicelogEnum[item.status]?.title}
            </div>
            <div
              className={classNames(
                'ml-1 text-xs bg-opacity-16 rounded-sm h-5 leading-5 px-1',
                servicelogEnum[item.status]?.text,
                servicelogEnum[item.status]?.bg
              )}>
              {dayjsFormat(item.date, 'YYYY-MM-DD')}
            </div>
          </div>
        </div>
        <div className="bg-white bg-opacity-80 rounded-sm text-black text-opacity-60 text-sm mt-3 p-2">
          {item.mark}
        </div>
        {item.isOperation ? (
          <div className="mt-2">
            <Button size="small" onClick={() => handleOnEdit(item)}>
              编辑
            </Button>
            <Popconfirm title="确认删除该服务记录吗？" onConfirm={() => truDel({ id: item.id })}>
              <Button size="small" danger className="ml-1">
                删除
              </Button>
            </Popconfirm>
          </div>
        ) : null}
      </div>
    </div>
  )
}

const ClientLowerList: React.FC<ClientLowerListProps> = ({
  logList: { log: logs = [] },
  serviceList,
  updatePayload
}) => {
  const tableHeight = (document.body.clientHeight - 124 - 78) / 2
  const columns: ProColumns<API.LogItem>[] = [
    {
      title: '日期',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160
    },
    {
      title: '操作人',
      dataIndex: 'operatorName',
      key: 'operatorName',
      ellipsis: true,
      width: 115
    },
    {
      title: '操作',
      dataIndex: 'operationType',
      key: 'operationType',
      ellipsis: true,
      width: 120
    },
    {
      title: '操作内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true
    }
  ]

  const vList = useMemo(() => {
    return VList({
      height: tableHeight,
      vid: 'client_log_list'
    })
  }, [])

  return (
    <div>
      <div className="pl-4">
        <Tabs>
          <TabPane tab="客户服务记录" key="客户服务记录">
            <div className="sheet-panel-record">
              {serviceList.map(item => (
                <div className="mb-3" key={item.id}>
                  <ServiceLogItem item={item} logType={ServiceLogType.CLIENT} updatePayload={updatePayload} />
                </div>
              ))}
            </div>
          </TabPane>
          <TabPane tab="日志" key="日志">
            <div className="sheet-panel-record">
              <ProTable<API.LogItem>
                search={false}
                toolBarRender={false}
                rowKey="id"
                size="small"
                columns={columns}
                dataSource={logs}
                pagination={false}
                scroll={{ y: tableHeight }}
                components={vList}
              />
            </div>
          </TabPane>
        </Tabs>
      </div>
    </div>
  )
}

export default ClientLowerList
