import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Divider} from '@nutui/nutui-react-taro'
import {Dongdong, ArrowRight, CheckNormal, Checked} from '@nutui/icons-react-taro'
import {View} from '@tarojs/components'
import {ShopUserAddress} from "@/api/shop/shopUserAddress/model";
import {listShopUserAddress, removeShopUserAddress, updateShopUserAddress} from "@/api/shop/shopUserAddress";

const Address = () => {
  const [list, setList] = useState<ShopUserAddress[]>([])
  const [address, setAddress] = useState<ShopUserAddress>()

  const reload = () => {
    listShopUserAddress({
      userId: Taro.getStorageSync('UserId')
    })
      .then(data => {
        setList(data || [])
        // 默认地址
        setAddress(data.find(item => item.isDefault))
      })
      .catch(() => {
        Taro.showToast({
          title: '获取地址失败',
          icon: 'error'
        });
      })
  }

  const onDefault = async (item: ShopUserAddress) => {
    if (address) {
      await updateShopUserAddress({
        ...address,
        isDefault: false
      })
    }
    await updateShopUserAddress({
      id: item.id,
      isDefault: true
    })
    Taro.showToast({
      title: '设置成功',
      icon: 'success'
    });
    reload();
  }

  const onDel = async (id?: number) => {
    await removeShopUserAddress(id)
    Taro.showToast({
      title: '删除成功',
      icon: 'success'
    });
    reload();
  }

  const selectAddress = async (item: ShopUserAddress) => {
    if (address) {
      await updateShopUserAddress({
        ...address,
        isDefault: false
      })
    }
    await updateShopUserAddress({
      id: item.id,
      isDefault: true
    })
    setTimeout(() => {
      Taro.navigateBack()
    },500)
  }

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

  if (list.length == 0) {
    return (
      <ConfigProvider>
        <div className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <Empty
            style={{
              backgroundColor: 'transparent'
            }}
            description="您还没有地址哦"
          />
          <Space>
            <Button onClick={() => Taro.navigateTo({url: '/user/address/add'})}>新增地址</Button>
            <Button type="success" fill="dashed"
                    onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}>获取微信地址</Button>
          </Space>
        </div>
      </ConfigProvider>
    )
  }

  return (
    <>
      <CellGroup>
        <Cell
          onClick={() => Taro.navigateTo({url: '/user/address/wxAddress'})}
        >
          <div className={'flex justify-between items-center w-full'}>
            <div className={'flex items-center gap-3'}>
              <Dongdong className={'text-green-600'}/>
              <div>获取微信地址</div>
            </div>
            <ArrowRight className={'text-gray-400'}/>
          </div>
        </Cell>
      </CellGroup>
      {list.map((item, _) => (
        <Cell.Group>
          <Cell className={'flex flex-col gap-1'} onClick={() => selectAddress(item)}>
            <View>
              <View className={'font-medium text-sm'}>{item.name} {item.phone}</View>
            </View>
            <View className={'text-xs'}>
              {item.province} {item.city} {item.region} {item.address}
            </View>
          </Cell>
          <Cell
            align="center"
            title={
              <View className={'flex items-center gap-1'} onClick={() => onDefault(item)}>
                {item.isDefault ? <Checked className={'text-green-600'} size={16}/> : <CheckNormal size={16}/>}
                <View className={'text-gray-400'}>默认地址</View>
              </View>
            }
            extra={
              <>
                <View className={'text-gray-400'} onClick={() => onDel(item.id)}>
                  删除
                </View>
                <Divider direction={'vertical'}/>
                <View className={'text-gray-400'}
                      onClick={() => Taro.navigateTo({url: '/user/address/add?id=' + item.id})}>
                  修改
                </View>
              </>
            }
          />
        </Cell.Group>
      ))}
    </>
  );
};

export default Address;
