import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Loading, CellGroup, Input, Form} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {
  getShopDealerBank,
  listShopDealerBank,
  updateShopDealerBank,
  addShopDealerBank
} from "@/api/shop/shopDealerBank";
import FixedButton from "@/components/FixedButton";
import {ShopDealerBank} from "@/api/shop/shopDealerBank/model";

const AddUserAddress = () => {
  const {params} = useRouter();
  const [loading, setLoading] = useState<boolean>(true)
  const [FormData, setFormData] = useState<ShopDealerBank>()
  const formRef = useRef<any>(null)

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

  const reload = async () => {
    // 如果是编辑模式，加载地址数据
    if (isEditMode && bankId) {
      try {
        const bank = await getShopDealerBank(bankId)
        setFormData(bank)
      } catch (error) {
        console.error('加载地址失败:', error)
        Taro.showToast({
          title: '加载地址失败',
          icon: 'error'
        });
      }
    }
  }

  // 提交表单
  const submitSucceed = async (values: any) => {
    console.log('.>>>>>>,....')
    try {
      // 准备提交的数据
      const submitData = {
        ...values,
        isDefault: true // 新增或编辑的地址都设为默认地址
      };

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

      // 如果是编辑模式，添加id
      if (isEditMode && bankId) {
        submitData.id = bankId;
      }

      // 先处理默认地址逻辑
      const defaultAddress = await listShopDealerBank({isDefault: true});
      if (defaultAddress && defaultAddress.length > 0) {
        // 如果当前编辑的不是默认地址，或者是新增地址，需要取消其他默认地址
        if (!isEditMode || (isEditMode && defaultAddress[0].id !== bankId)) {
          await updateShopDealerBank({
            ...defaultAddress[0],
            isDefault: false
          });
        }
      }

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

      Taro.showToast({
        title: `${isEditMode ? '更新' : '保存'}成功`,
        icon: 'success'
      });

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

    } catch (error) {
      console.error('保存失败:', error);
      Taro.showToast({
        title: `${isEditMode ? '更新' : '保存'}失败`,
        icon: 'error'
      });
    }
  }

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

  useEffect(() => {
    // 动态设置页面标题
    Taro.setNavigationBarTitle({
      title: isEditMode ? '编辑银行卡' : '添加银行卡'
    });

    reload().then(() => {
      setLoading(false)
    })
  }, [isEditMode]);

  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)}
      >
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="bankName" label="开户行名称" initialValue={FormData?.bankName} required>
            <Input placeholder="开户行名称" maxLength={10}/>
          </Form.Item>
          <Form.Item name="bankAccount" label="银行开户名" initialValue={FormData?.bankAccount} required>
            <Input placeholder="银行开户名" maxLength={10}/>
          </Form.Item>
          <Form.Item name="bankCard" label="银行卡号" initialValue={FormData?.bankCard} required>
            <Input placeholder="银行卡号" maxLength={11}/>
          </Form.Item>
        </CellGroup>
      </Form>

      {/* 底部浮动按钮 */}
      <FixedButton text={isEditMode ? '更新地址' : '保存并使用'} onClick={() => formRef.current?.submit()}/>
    </>
  );
};

export default AddUserAddress;
