import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Loading, CellGroup, Input, Form, Cell, Avatar, Tag} from '@nutui/nutui-react-taro'
import {ArrowRight} from '@nutui/icons-react-taro'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import FixedButton from "@/components/FixedButton";
import {addShopChatMessage} from "@/api/shop/shopChatMessage";
import navTo from "@/utils/common";
import {getUser} from "@/api/system/user";
import {User} from "@/api/system/user/model";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {ClinicPrescription} from "@/api/clinic/clinicPrescription/model";

const AddMessage = () => {
  const {params} = useRouter();
  const [toUser, setToUser] = useState<User>()
  const [loading, setLoading] = useState<boolean>(true)
  const [FormData, _] = useState<ClinicPrescription>()
  const formRef = useRef<any>(null)

  // 患者和处方状态
  const [selectedPatient, setSelectedPatient] = useState<ClinicPatientUser | null>(null)
  const [selectedPrescription, setSelectedPrescription] = useState<ClinicPrescription | null>(null)

  // 判断是编辑还是新增模式
  const isEditMode = !!params.id
  const toUserId = params.id ? Number(params.id) : undefined

  const reload = async () => {
    if(toUserId){
      getUser(Number(toUserId)).then(data => {
        setToUser(data)
      })
    }
  }

  // 设置选中的患者（供其他页面调用）
  // @ts-ignore
  const setSelectedPatientFunc = (patient: ClinicPatientUser) => {
    console.log('患者:', patient)
    setSelectedPatient(patient)
    console.log(selectedPatient,'selectedPatient')
  }

  // 设置选中的处方（供其他页面调用）
  // @ts-ignore
  const setSelectedPrescriptionFunc = (prescription: ClinicPrescription) => {
    setSelectedPrescription(prescription)
  }

  // 提交表单
  const submitSucceed = async (values: any) => {
    try {
      // 准备提交的数据
      const submitData = {
        ...values
      };

      console.log('提交数据:', submitData)

      // 参数校验
      if(!toUser && !selectedPatient){
        Taro.showToast({
          title: `请选择发送对象或患者`,
          icon: 'error'
        });
        return false;
      }

      // 判断内容是否为空
      if (!values.content) {
        Taro.showToast({
          title: `请输入内容`,
          icon: 'error'
        });
        return false;
      }

      // 如果选择了患者，在消息内容中添加患者信息
      console.log(values,'vals.s..s.s.s.s.s')
      let content = values.content;
      if (selectedPatient) {
        content = `[患者: ${selectedPatient.realName || '未知'}] ${content}`;
      }

      // 如果选择了处方，在消息内容中添加处方信息
      if (selectedPrescription) {
        content = `[处方: ${selectedPrescription.orderNo || '未知'}] ${content}`;
      }

      // 执行新增或更新操作
      await addShopChatMessage({
        toUserId: toUserId || selectedPatient?.userId,
        formUserId: Taro.getStorageSync('UserId'),
        type: 'text',
        content: content
      });

      Taro.showToast({
        title: `发送成功`,
        icon: 'success'
      });

      setTimeout(() => {
        Taro.navigateBack();
      }, 1000);

    } catch (error) {
      console.error('发送失败:', error);
      Taro.showToast({
        title: `发送失败`,
        icon: 'error'
      });
    }
  }

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })

    // 设置页面实例的方法，供其他页面调用
    // @ts-ignore
    Taro.getCurrentInstance().page.setSelectedPatient = setSelectedPatientFunc;
    // @ts-ignore
    Taro.getCurrentInstance().page.setSelectedPrescription = setSelectedPrescriptionFunc;
  }, [isEditMode]);

  if (loading) {
    return <Loading className={'px-2'}>加载中</Loading>
  }

  return (
    <>
      {/* 显示已选择的用户（如果有的话） */}
      {toUser && (
        <Cell title={(
          <View className={'flex items-center'}>
            <Avatar src={toUser.avatar}/>
            <View className={'ml-2 flex flex-col'}>
              <Text>{toUser.alias || toUser.nickname}</Text>
              <Text className={'text-gray-300'}>{toUser.mobile}</Text>
            </View>
          </View>
        )} extra={(
          <ArrowRight color="#cccccc" className={'mt-2'} size={20}/>
        )}/>
      )}

      {/* 选择患者 */}
      {JSON.stringify(selectedPatient)}
      <Cell
        title="选择患者"
        extra={selectedPatient ? (
          <View className={'flex items-center'}>
            <Text className={'mr-2'}>{selectedPatient.realName || '未知患者'}</Text>
            <ArrowRight color="#cccccc" size={18}/>
          </View>
        ) : (
          <ArrowRight color="#cccccc" size={18}/>
        )}
        onClick={() => navTo(`/doctor/orders/selectPatient`, true)}
      />

      <Cell
        title="诊断结果"
        extra={selectedPatient ? (
          <Form.Item name="content" initialValue={FormData?.diagnosis} required>
            <Input placeholder="填写诊断结果" maxLength={300}/>
          </Form.Item>
        ) : (
          <ArrowRight color="#cccccc" size={18}/>
        )}
        onClick={() => navTo(`/doctor/orders/selectPatient`, true)}
      />

      {/* 选择处方 */}
      <Cell
        title="选择处方"
        extra={selectedPrescription ? (
          <View className={'flex items-center'}>
            <Text className={'mr-2'}>{selectedPrescription.treatmentPlan || '未知处方'}</Text>
            <ArrowRight color="#cccccc" size={18}/>
          </View>
        ) : (
          <ArrowRight color="#cccccc" size={18}/>
        )}
        onClick={() => navTo(`/doctor/orders/selectPrescription`, true)}
      />

      <Cell
        title="药方信息"
        extra={selectedPrescription ? (
          <View className={'flex items-center'}>
            {selectedPrescription.items?.map(item => (
              <Tag key={item.id} className={'mr-2'}>{item.medicineName}</Tag>
            ))}
          </View>
        ) : (
          <ArrowRight color="#cccccc" size={18}/>
        )}
        onClick={() => navTo(`/doctor/orders/selectPrescription`, true)}
      />



      <Form
        ref={formRef}
        divider
        initialValues={FormData}
        labelPosition="left"
        onFinish={(values) => submitSucceed(values)}
        onFinishFailed={(errors) => submitFailed(errors)}
      >
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="content" initialValue={FormData?.decoctionInstructions} required>
            <Input placeholder="填写消息内容" maxLength={300}/>
          </Form.Item>
        </CellGroup>
      </Form>

      {/* 底部浮动按钮 */}
      <FixedButton text={isEditMode ? '立即发送' : '立即发送'} onClick={() => formRef.current?.submit()}/>
    </>
  );
};

export default AddMessage;
