import {useEffect, useState, useRef} from "react";
import {Loading, CellGroup, Cell, Input, Form} from '@nutui/nutui-react-taro'
import {Edit} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {View} from '@tarojs/components'
import FixedButton from "@/components/FixedButton";
import {useUser} from "@/hooks/useUser";
import {ShopDealerApply} from "@/api/shop/shopDealerApply/model";
import {
  addShopDealerApply,
  pageShopDealerApply,
  updateShopDealerApply
} from "@/api/shop/shopDealerApply";
import {getShopDealerUser} from "@/api/shop/shopDealerUser";

const AddUserAddress = () => {
  const {user} = useUser()
  const [loading, setLoading] = useState<boolean>(true)
  const [FormData, setFormData] = useState<ShopDealerApply>()
  const formRef = useRef<any>(null)
  const [isEditMode, setIsEditMode] = useState<boolean>(false)
  const [existingApply, setExistingApply] = useState<ShopDealerApply | null>(null)

  // 获取审核状态文字
  const getApplyStatusText = (status?: number) => {
    switch (status) {
      case 10:
        return '待审核'
      case 20:
        return '审核通过'
      case 30:
        return '驳回'
      default:
        return '未知状态'
    }
  }

  const reload = async () => {
    // 判断用户是否登录
    if (!user?.userId) {
      return false;
    }
    // 查询当前用户ID是否已有申请记录
    try {
      const res = await pageShopDealerApply({userId: user?.userId});
      if (res && res.count > 0) {
        setIsEditMode(true);
        setExistingApply(res.list[0]);
        // 如果有记录，填充表单数据
        setFormData(res.list[0]);
        setLoading(false)
      } else {
        setIsEditMode(false);
        setExistingApply(null);
        setLoading(false)
      }
    } catch (error) {
      setLoading(true)
      console.error('查询申请记录失败:', error);
      setIsEditMode(false);
      setExistingApply(null);
    }
  }

  // 提交表单
  const submitSucceed = async (values: any) => {
    try {

      // 准备提交的数据
      const submitData = {
        ...values,
        realName: values.realName || user?.nickname,
        mobile: user?.phone,
        refereeId: values.refereeId || FormData?.refereeId,
        applyStatus: 10,
        auditTime: undefined
      };
      await getShopDealerUser(submitData.refereeId);

      // 如果是编辑模式，添加现有申请的id
      if (isEditMode && existingApply?.applyId) {
        submitData.applyId = existingApply.applyId;
      }

      // 执行新增或更新操作
      if (isEditMode) {
        await updateShopDealerApply(submitData);
      } else {
        await addShopDealerApply(submitData);
      }

      Taro.showToast({
        title: `${isEditMode ? '提交' : '提交'}成功`,
        icon: 'success'
      });

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

    } catch (error) {
      console.error('验证邀请人失败:', error);
      return Taro.showToast({
        title: '邀请人ID不存在',
        icon: 'error'
      });
    }
  }

  // 处理固定按钮点击事件
  const handleFixedButtonClick = () => {
    // 触发表单提交
    formRef.current?.submit();
  };

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

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })
  }, [user?.userId]); // 依赖用户ID，当用户变化时重新加载

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

  return (
    <>
      <Form
        ref={formRef}
        divider
        initialValues={FormData}
        labelPosition="left"
        onFinish={(values) => submitSucceed(values)}
        onFinishFailed={(errors) => submitFailed(errors)}
      >
        <View className={'bg-gray-100 h-3'}></View>
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="realName" label="名称" initialValue={user?.nickname} required>
            <Input placeholder="经销商名称" maxLength={10}/>
          </Form.Item>
          <Form.Item name="mobile" label="手机号" initialValue={user?.mobile} required>
            <Input placeholder="请输入手机号" disabled={true} maxLength={11}/>
          </Form.Item>
          <Form.Item name="refereeId" label="邀请人ID" initialValue={FormData?.refereeId} required>
            <Input placeholder="邀请人ID"/>
          </Form.Item>
        </CellGroup>
      </Form>
      {/* 审核状态显示（仅在编辑模式下显示） */}
      {isEditMode && (
        <CellGroup>
          <Cell
            title={'审核状态'}
            extra={
              <span style={{
                color: FormData?.applyStatus === 20 ? '#52c41a' :
                  FormData?.applyStatus === 30 ? '#ff4d4f' : '#faad14'
              }}>
                {getApplyStatusText(FormData?.applyStatus)}
              </span>
            }
          />
          {FormData?.applyStatus === 20 && (
            <Cell title={'审核时间'} extra={FormData?.auditTime || '无'}/>
          )}
          {FormData?.applyStatus === 30 && (
            <Cell title={'驳回原因'} extra={FormData?.rejectReason || '无'}/>
          )}
        </CellGroup>
      )}


      {/* 底部浮动按钮 */}
      {(!isEditMode || FormData?.applyStatus === 10 || FormData?.applyStatus === 30) && (
        <FixedButton
          icon={<Edit/>}
          text={isEditMode ? '保存修改' : '提交申请'}
          disabled={FormData?.applyStatus === 10}
          onClick={handleFixedButtonClick}
        />
      )}

    </>
  );
};

export default AddUserAddress;
