import { Conditional } from '@/components/Conditional'
import { useAuthContext } from '@/stores/AuthContext'
import {
  App,
  Badge,
  Button,
  DatePicker,
  Divider,
  Flex, Form,
  Input,
  Radio, Select,
  Space,
  Switch,
  Table,
  Tag
} from 'antd'
import { memo, useCallback, useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom'

const { RangePicker } = DatePicker

const AdvanceSearchForm = memo(function ({ onSubmit }) {
  const [form] = Form.useForm()
  function handleSubmit(values) {
    onSubmit?.(values)
  }
  return (
    <Form
      layout={'inline'}
      form={form}
      initialValues={{ orderLabel: '全部', orderStatus: '全部' }}
      onFinish={handleSubmit}
      style={{
        maxWidth: 'none',
      }}
    >
      <Form.Item label='标签' name='orderLabel'>
        <Select
          style={{
            width: 100,
          }}
          options={[
            { value: '240003', label: '重点' },
            { value: '240002', label: '潜力' },
            { value: '240001', label: '休眠' }
          ]}
        />
      </Form.Item>
      <Form.Item label='状态' name='orderStatus'>
        <Select
          style={{
            width: 100,
          }}
          options={[
            {
              value: '新订单',
              label: '新订单',
            },
            {
              value: '报价中',
              label: '报价中',
            },
            {
              value: '丢失',
              label: '丢失',
            },
            {
              value: '一催',
              label: '一催',
            },
            {
              value: '二催',
              label: '二催',
            },
            {
              value: '三催',
              label: '三催',
            },
          ]}
        />
      </Form.Item>
      <Form.Item label='订单号' name='orderNumber'>
        <Input placeholder='订单号' allowClear />
      </Form.Item>
      <Form.Item label='出发日期' name='startDateRange'>
        <RangePicker />
      </Form.Item>
      <Form.Item >
        <Button type='primary' htmlType='submit'>搜索</Button>
      </Form.Item>
    </Form>
  )
})

function OrderList({ formValues }) {

  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'COLI_ID',
      width: 222,
      render: (text, record) => {
        if (record.COLI_LineGrade === 240003) return <Space>{text}<Tag color='red'>重点</Tag></Space>
        else if (record.COLI_LineGrade === 240002) return <Space>{text}<Tag color='green'>潜力</Tag></Space>
        else if (record.COLI_LineGrade === 240001) return <Space>{text}<Tag color='blue'>休眠</Tag></Space>
        else return <Space>{text}</Space>
      }
    },
    {
      title: '客人姓名',
      dataIndex: 'coli_guest',
      render: (text, record) => {
        let regularText = ''
        if (record.buytime > 0) regularText = '(R' + record.buytime + ')'
        return (
          <Space>
            <NavLink to={`/order/chat/${record.COLI_ID}`}>{text + regularText}</NavLink>
            <Badge
              count={record.unread_msg}
              style={{
                backgroundColor: '#52c41a',
              }}
            />
          </Space>
        )
      }
    },
    {
      title: '订单状态',
      dataIndex: 'COLI_State',
      width: 120,
      render: (text, record) => {
        let extra = ''
        if (record.RemindState === 1) extra = '(一催)'
        if (record.RemindState === 2) extra = '(二催)'
        if (record.RemindState === 3) extra = '(三催)'
        return text + extra
      }
    },
    {
      title: '报价title',
      dataIndex: 'lettertitle',
      ellipsis: true,
    },
    {
      title: '客人最后一次回复时间',
      dataIndex: 'last_received_time',
    },
    {
      title: '附加信息',
      dataIndex: 'COLI_Introduction',
    },
  ]
  const { notification } = App.useApp()
  const [orderData, setOrderData] = useState([])
  const [loading, setLoading] = useState(false)  
  const { loginUser } = useAuthContext()

  useEffect(() => {
    setLoading(true)
    fetch(`http://202.103.68.157:8888/gettodayorder?opisn=${loginUser.userId}`)
      .then(response => response.json())
      .then(json => {
        if (json.errcode === 0) {
          setOrderData(json.result.map((order) => { return {...order, key: order.COLI_ID}}))
        } else {
          notification.error({
            message: '查询出错',
            description: json?.errmsg,
            placement: 'top',
            duration: 60,
          })
        }
      })
      .finally(() => setLoading(false))
      .catch(reason => {
        notification.error({
          message: '查询出错',
          description: reason.message,
          placement: 'top',
          duration: 60,
        })
      })
  }, [formValues])

  return (
    <Table key='Order Table' loading={loading} dataSource={orderData} columns={orderColumns} />
  )
}
function OrderFollow() {

  const [advanceChecked, toggleAdvance] = useState(false)
  const [formValues, setFormValues] = useState({
    type: 'today',
    orderStatus: '新状态',
    orderNumber: '订单号',
    orderLabel: '订单标签',
    startDate: '走团时间'
  })

  const handleSubmit = useCallback((values) => {
    setFormValues({...values, type: 'advance'})
  }, [])

  return (
    <>
      <Space direction='vertical' size='large' style={{ width: '100%' }}>
        <Flex gap='large' justify='start' align='center' horizontal='true'>
          <Radio.Group
            options={[
              { label: '今日任务', value: 'today' },
              { label: '潜力客户', value: 'star' },
              { label: '重点订单', value: 'important' },
              { label: '成行', value: 'myfavorites' },
              { label: '走团中', value: 'ing' },
              { label: '走团后一月', value: 'lastMonth' }
            ]}
            value={formValues.type}
            onChange={({ target: { value } }) => {
              setFormValues({
                ...formValues,
                type: value
              })
            }}
            optionType='button'
            buttonStyle='solid'
            disabled={advanceChecked}
          />

          <Switch checkedChildren='高级查询' unCheckedChildren='高级查询'
            defaultChecked={false}
            onChange={() => { toggleAdvance(!advanceChecked) }} />
        </Flex>
        <Conditional condition={advanceChecked} whenTrue={<AdvanceSearchForm onSubmit={handleSubmit} />}
        />
      </Space>
      <Divider plain orientation='left'></Divider>
      <OrderList formValues={formValues} />
    </>
  )
}

export default OrderFollow
