import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Loading, CellGroup, Input, Form, Cell, Avatar} 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 {ShopChatMessage} from "@/api/shop/shopChatMessage/model";
import navTo from "@/utils/common";
import {getUser} from "@/api/system/user";
import {User} from "@/api/system/user/model";

const AddMessage = () => {
  const {params} = useRouter();
  const [toUser, setToUser] = useState<User>()
  const [loading, setLoading] = useState<boolean>(true)
  const [FormData, _] = useState<ShopChatMessage>()
  const formRef = useRef<any>(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)
      })
    }
  }

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

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

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

      // 判断内容是否为空
      if (!values.content) {
        Taro.showToast({
          title: `请输入内容`,
          icon: 'error'
        });
        return false;
      }
      // 执行新增或更新操作
      await addShopChatMessage({
        toUserId: toUserId,
        formUserId: Taro.getStorageSync('UserId'),
        type: 'text',
        content: values.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)
    })
  }, [isEditMode]);

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

  return (
    <>
      <Cell title={toUser ? (
        <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={toUser ? 'mt-2' : ''} size={toUser ? 20 : 18}/>
      )}
            onClick={() => navTo(`/dealer/team/index`, 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?.content} required>
            <Input placeholder="填写消息内容" maxLength={300}/>
          </Form.Item>
        </CellGroup>
      </Form>

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

export default AddMessage;
