import React, { useEffect, useState } from 'react';
import { EnvironmentOutlined, ReloadOutlined } from '@ant-design/icons';
import { Button, Radio, RadioChangeEvent, Space } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';
import { UserAPI } from '@/api';
import { InterDataType } from '@/api/interface';
import { UserAddressSelectList } from '@/api/interface/user';
import QrcodePopover from '@/components/qrcodePopover';
import { setGlobalData } from '@/store/module/globalData';
import { SystemState } from '@/store/module/system';
import { UserInfoState } from '@/store/module/userInfo';

// 列表类型
type ListType = InterDataType<UserAddressSelectList>;

const SubmitAddressView = () => {
  // store
  const dispatch = useDispatch();
  // system
  const system = useSelector((state: any) => state.system) as SystemState;
  // userInfo
  const userInfo = useSelector((state: any) => state.userInfo) as UserInfoState;
  // 收货地址列表
  const [addressList, setAddressList] = useState<ListType>();
  // 当前选中的地址
  const [currentValue, setCurrentValue] = useState<number>();
  // 获取用户的收货地址
  const getUserAddressList = async () => {
    const res = await UserAPI.userAddressSelectList({
      userAccountId: userInfo?.id,
    });
    if (res && res.code === '200') {
      setAddressList(res.result || []);
      // 设置默认地址
      setCurrentValue(res.result?.find((i) => i.type === 0)?.id);
      // 将地址列表存入store
      dispatch(
        setGlobalData({
          userAddressList: res.result,
          userAddressSelectId: res.result?.find((i) => i.type === 0)?.id,
        }),
      );
    }
  };
  // 转换地址
  const transformAddress = (address: string) => {
    return address?.split('/');
  };
  // 选择地址事件
  const handleSelect = (e: RadioChangeEvent) => {
    setCurrentValue(e?.target?.value);
    // 将地址列表存入store
    dispatch(
      setGlobalData({
        userAddressSelectId: e?.target?.value,
      }),
    );
  };
  // 组件挂载
  useEffect(() => {
    if (!system?.token) {
      // 请先完成登录
      dispatch(
        setGlobalData({
          loginModalVisible: true,
        }),
      );
    } else {
      getUserAddressList().then();
    }
  }, [system?.token]);
  return (
    <SubmitAddressWrap>
      <div className="address-title flex-between">
        <div className="title flex-baseline">
          <span>确认收货地址</span>
          <Button
            type="link"
            icon={<ReloadOutlined />}
            onClick={getUserAddressList}
          >
            刷新地址
          </Button>
        </div>
        <QrcodePopover
          text="管理收货地址"
          path="page-mine/address-management/index"
        />
      </div>
      {!addressList?.length && (
        <div className="address-none flex-start">
          <EnvironmentOutlined style={{ color: '#ff6700', fontSize: '13px' }} />
          <div className="text">
            暂无地址，请打开手机端【云享飞】微信小程序，【我的】-【个人设置】-【地址管理】添加
          </div>
        </div>
      )}
      <Radio.Group value={currentValue} onChange={(e) => handleSelect(e)}>
        <Space direction="vertical">
          {addressList?.map((i, j) => (
            <div
              className={`address-item ${
                i?.id === currentValue && 'item-active'
              } flex-start`}
              key={j}
            >
              <div className="label">
                {i?.id === currentValue && (
                  <EnvironmentOutlined
                    style={{ color: '#ff6700', fontSize: '13px' }}
                  />
                )}
              </div>

              <Radio value={i.id}>
                {transformAddress(i?.takeRegion)?.map((n, m) => (
                  <span className="text" key={m}>
                    {n}
                  </span>
                ))}
                <span className="text">{i?.takeAddress}</span>
                <span className="text">（{i?.takeName} 收）</span>
                <span className="text">{i?.takePhone}</span>
                {i?.type === 0 && <span className="text">默认地址</span>}
              </Radio>
            </div>
          ))}
        </Space>
      </Radio.Group>
    </SubmitAddressWrap>
  );
};

export default SubmitAddressView;
// 样式
const SubmitAddressWrap = styled.div`
  position: relative;
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 2rem;
  .address-title {
    position: relative;
    width: 100%;
    border-bottom: 2px solid #f1f1f1;
    box-sizing: border-box;
    padding: 1rem 0 0.5rem 0;
    margin-bottom: 1rem;
    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333333;
    }
    .action {
      font-weight: 400;
      color: #3366cc;
      cursor: pointer;
    }
  }
  .address-none {
    position: relative;
    width: 100%;
    height: 2.5rem;
    line-height: 2.5rem;
    background: #fff1e8;
    border: 0.04rem solid #ff552d;
    box-sizing: border-box;
    padding: 0 0.58rem;
    .text {
      margin-left: 0.5rem;
    }
  }
  .address-item {
    position: relative;
    width: 100%;
    height: 2.5rem;
    box-sizing: border-box;
    padding: 0 0.5rem;
    .text {
      margin-right: 0.3rem;
    }
    .ant-radio + span {
      color: #666666;
    }
    .ant-wave-target {
      margin-right: 0.3rem;
    }
    .label {
      position: relative;
      width: 4rem;
    }
  }
  .item-active {
    background: #fff1e8;
    border: 0.04rem solid #ff552d;
    .ant-radio + span {
      color: #000;
    }
    .label::after {
      position: absolute;
      top: -0.3rem;
      right: 0.5rem;
      content: '寄送至';
      font-size: 13px;
      color: #ff552d;
    }
  }
  .ant-radio-group,
  .ant-space {
    width: 100%;
  }
`;
