import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Tag, Divider} from '@nutui/nutui-react-taro'
import {Del, Edit} from '@nutui/icons-react-taro'
import {View, Text} from '@tarojs/components'
import {ClinicPrescription} from "@/api/clinic/clinicPrescription/model";
import {
  pageClinicPrescription,
  removeClinicPrescription
} from "@/api/clinic/clinicPrescription";
import FixedButton from "@/components/FixedButton";

const ClinicPrescriptionList = () => {
  const [list, setList] = useState<ClinicPrescription[]>([])
  const [loading, setLoading] = useState<boolean>(false)

  const reload = () => {
    setLoading(true)
    pageClinicPrescription({
      // 添加查询条件
    })
      .then(data => {
        setList(data?.list || [])
      })
      .catch(() => {
        Taro.showToast({
          title: '获取数据失败',
          icon: 'error'
        });
      })
      .finally(() => {
        setLoading(false)
      })
  }

  const onDel = async (item: ClinicPrescription) => {
    const res = await Taro.showModal({
      title: '确认删除',
      content: `确定要删除处方编号「${item.orderNo}」吗？`,
    })

    if (res.confirm) {
      try {
        await removeClinicPrescription(item.id)
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        });
        reload();
      } catch (error) {
        Taro.showToast({
          title: '删除失败',
          icon: 'error'
        });
      }
    }
  }

  const onEdit = (item: ClinicPrescription) => {
    Taro.navigateTo({
      url: `/clinic/clinicPrescription/add?id=${item.id}`
    })
  }

  // 获取处方类型文本
  const getPrescriptionTypeText = (type?: number) => {
    return type === 0 ? '中药' : type === 1 ? '西药' : '未知'
  }

  // 获取状态文本
  const getStatusText = (status?: number) => {
    switch (status) {
      case 0:
        return '正常'
      case 1:
        return '已完成'
      case 2:
        return '已支付'
      case 3:
        return '已取消'
      default:
        return '未知'
    }
  }

  // 获取状态颜色
  const getStatusType = (status?: number): 'primary' | 'success' | 'danger' | 'warning' | 'default' => {
    switch (status) {
      case 0:
        return 'primary'
      case 1:
        return 'success'
      case 2:
        return 'success'
      case 3:
        return 'danger'
      default:
        return 'default'
    }
  }

  const getSexName = (sex?: number) => {
    return sex === 0 ? '男' : sex === 1 ? '女' : ''
  }

  useDidShow(() => {
    reload()
  });

  if (list.length === 0 && !loading) {
    return (
      <ConfigProvider>
        <View className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <Empty
            style={{
              backgroundColor: 'transparent'
            }}
            description="暂无处方数据"
          />
          <Space style={{ marginTop: '20px' }}>
            <Button
              type="primary"
              onClick={() => Taro.navigateTo({url: '/clinic/clinicPrescription/add'})}
            >
              新增处方
            </Button>
          </Space>
        </View>
      </ConfigProvider>
    )
  }

  return (
    <>
      <View className="p-3">
        {list.map((item) => (
          <CellGroup key={item.id} className="mb-3">
            <Cell
              title={
                <View className="flex items-center justify-between">
                  <Space>
                    <Text className="font-medium">{item.realName}</Text>
                    <Text className="font-medium">{item.age}岁</Text>
                    <Text className="font-medium">{getSexName(item.sex)}</Text>
                  </Space>

                  <Tag type={getStatusType(item.status)}>
                    {getStatusText(item.status)}
                  </Tag>
                </View>
              }
            />
            <Cell
              title="处方类型"
              extra={
                <Tag type="info">
                  {getPrescriptionTypeText(item.prescriptionType)}
                </Tag>
              }
            />
            {item.diagnosis && (
              <Cell
                title="诊断结果"
                extra={
                  <Text className="text-gray-600 text-sm">
                    {item.diagnosis.length > 20
                      ? `${item.diagnosis.substring(0, 20)}...`
                      : item.diagnosis}
                  </Text>
                }
              />
            )}
            {item.treatmentPlan && (
              <Cell
                title="治疗方案"
                extra={
                  <Text className="text-gray-600 text-sm">
                    {item.treatmentPlan.length > 20
                      ? `${item.treatmentPlan.substring(0, 20)}...`
                      : item.treatmentPlan}
                  </Text>
                }
              />
            )}
            <Cell
              title="订单金额"
              extra={
                <Text className="text-red-500 font-medium">
                  ¥{item.orderPrice || '0.00'}
                </Text>
              }
            />
            {item.items && item.items.length > 0 && (
              <Cell
                title="药品数量"
                extra={
                  <Tag type="warning">
                    共 {item.items.length} 味药
                  </Tag>
                }
              />
            )}
            <Cell
              title="创建时间"
              extra={
                <Text className="text-gray-500 text-xs">
                  {item.createTime}
                </Text>
              }
            />
            {item.comments && (
              <Cell
                title="备注"
                extra={
                  <Text className="text-gray-600 text-sm">
                    {item.comments.length > 30
                      ? `${item.comments.substring(0, 30)}...`
                      : item.comments}
                  </Text>
                }
              />
            )}
            <Divider />
            <Cell>
              <Space className="w-full justify-end">
                <Button
                  size="small"
                  type="primary"
                  icon={<Edit />}
                  onClick={() => onEdit(item)}
                >
                  编辑
                </Button>
                <Button
                  size="small"
                  type="danger"
                  icon={<Del />}
                  onClick={() => onDel(item)}
                >
                  删除
                </Button>
              </Space>
            </Cell>
          </CellGroup>
        ))}
      </View>

      <FixedButton
        text="开处方"
        onClick={() => Taro.navigateTo({url: '/clinic/clinicPrescription/add'})}
      />
    </>
  )
}

export default ClinicPrescriptionList;
