import { LinkOutlined, MailOutlined, PhoneOutlined, UserOutlined, WhatsAppOutlined } from '@ant-design/icons'
import { App, Button, Card, Empty, Flex, Select, Spin, Typography } from 'antd'
import { useEffect, useState } from 'react'

import { copy, isNotEmpty } from '@/utils/commons'
import { Conditional } from '@/components/Conditional'
import useConversationStore from '@/stores/ConversationStore'
import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions } from '@/stores/OrderStore'
import QuotesHistory from './QuotesHistory'

const CustomerProfile = (() => {
  const { notification, message } = App.useApp()
  const [loading, setLoading] = useState(false)
  const currentOrder = useConversationStore((state) => state.currentConversation?.coli_sn || '')
  const { orderDetail, customerDetail, lastQuotation, quotationList,
    fetchOrderDetail, setOrderPropValue
  } = useOrderStore()

  const orderLabelOptions = copy(OrderLabelDefaultOptions)
  orderLabelOptions.unshift({ value: 0, label: '未设置', disabled: true, })

  const orderStatusOptions = copy(OrderStatusDefaultOptions)

  useEffect(() => {
    if (currentOrder) {
      setLoading(true)
      fetchOrderDetail(currentOrder)
        .finally(() => setLoading(false))
        .catch(reason => {
          notification.error({
            message: '查询出错',
            description: reason.message,
            placement: 'top',
            duration: 60,
          })
        })
    }
  }, [currentOrder])

  let regularText = ''
  if (orderDetail.buytime > 0) regularText = '(R' + orderDetail.buytime + ')'

  if (currentOrder) {
    return (
      <div className='divide-x-0 divide-y divide-dashed divide-gray-300'>
        <Spin spinning={loading}>
        <Card className='p-2 '
          bordered={false}
          title={orderDetail.order_no}
          actions={[
            <Select
              style={{
                width: '100%'
              }}
              variant='borderless'
              onSelect={(value) => {
                setOrderPropValue(currentOrder, 'orderlabel', value)
                  .then(() => {
                    message.success('设置成功')
                  })
                  .catch(reason => {
                    notification.error({
                      message: '设置出错',
                      description: reason.message,
                      placement: 'top',
                      duration: 60,
                    })
                  })
              }}
              value={orderDetail.tags}
              options={orderLabelOptions}
            />,
            <Select
              style={{
                width: '100%'
              }}
              variant='borderless'
              onSelect={(value) => {
                setOrderPropValue(currentOrder,'orderstatus',  value)
                  .then(() => {
                    message.success('设置成功')
                  })
                  .catch(reason => {
                    notification.error({
                      message: '设置出错',
                      description: reason.message,
                      placement: 'top',
                      duration: 60,
                    })
                  })
              }}
              value={orderDetail.states}
              options={orderStatusOptions}
            />
          ]}
          >
          <Flex gap={10}>
            <Flex vertical={true} justify='space-between'>
              <Typography.Text ><UserOutlined className=' pr-1' />{customerDetail.name + regularText}</Typography.Text>
              <Typography.Text ><PhoneOutlined className=' pr-1' />{customerDetail.phone}</Typography.Text>
              <Typography.Text ><MailOutlined className=' pr-1' />{customerDetail.email}</Typography.Text>
              <Typography.Text ><WhatsAppOutlined className='pr-1' />{customerDetail.whatsapp_phone_number}</Typography.Text>
            </Flex>
          </Flex>
        </Card>
        <Flex vertical={true} className='p-2 '>
          <Typography.Text strong>最新报价</Typography.Text>
          <Conditional
            condition={quotationList.length > 0}
            whenFalse={<Empty description={<span>暂无报价</span>}></Empty>}
            whenTrue={
            <>
              <p className='m-0 py-2 line-clamp-2 '><a target='_blank' href={lastQuotation.letterurl}><LinkOutlined />&nbsp;{lastQuotation.lettertitle}</a></p>
              <Flex justify={'space-between'} >
                <QuotesHistory dataSource={quotationList} />
              </Flex>
            </>
          }/>
        </Flex>
        <p className='p-2 shadow-inner overflow-auto m-0 break-words whitespace-pre-wrap' dangerouslySetInnerHTML={{__html: orderDetail.order_detail}}></p>
        </Spin>
      </div>
    )
  } else {
    return (
      <Empty
        description={<span>暂无相关订单</span>}
      >
        <Button type='primary' onClick={() => {
          notification.info({
            message: '温馨提示',
            description: '功能还在开发中，敬请期待',
            placement: 'top',
            duration: 60,
          })
        }}>现在关联</Button>
      </Empty>
    )
  }
})

export default CustomerProfile
