import React, { useContext, useEffect, useState } from 'react';
import { OrderForGoodsBox } from './styled';
import type { FormInstance, RadioChangeEvent } from 'antd';
import { Button, Radio, Space, Input, message, Modal, Image } from 'antd';
import api, { UserAddress, GetOrderForGoods } from './api';
import moment from 'moment';
// import { ShopDetail } from '../../[id].page'
// import {
//   GetWebDeviceDetailResult,
//   GetWebDeviceWareSkuById,
//   GetLeaseGoodsResult,
// } from '../../api'
import { UserContext } from '~/lib/userProvider';
const { TextArea } = Input;

interface PropsBox {
  setIsorderForGoods: (boolean: boolean) => void;
  mallDetail?: any;
  detailData?: any;
  shopDetail?: any;
  wareSkuList?: any;
  discount?: any;
}

export default function OrderForGoods(props: PropsBox) {
  const { setIsorderForGoods, shopDetail, detailData, wareSkuList, discount, mallDetail } = props;
  const [value, setValue] = useState(1);
  const [areaValue, setAreaValue] = useState<string>();
  const [list, setList] = useState<Array<UserAddress> | null>();

  const onChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  const onChangeValue = (index: number) => {
    setValue(index);
  };
  const detailSumbit = () => {
    if (!list?.length) return message.warning('暂无地址信息,请前往云享飞添加地址');
    if (list?.length && !value && value !== 0) return message.warning('请选择地址');
    if (detailData && list && mallDetail) {
      const pushList = {
        buyNum: mallDetail.buyNum,
        directoryId: mallDetail.directoryId,
        goodsInfoId: mallDetail.goodsInfoId,
        mallSpecIds: mallDetail.mallSpecIds,
        userAddressId: value,
        remark: areaValue,
      };

      api.FeignAddLease(pushList).then((res) => {
        if (res.code === '200') {
          message.success('提交成功');
          setIsorderForGoods(false);
        } else {
          message.error(res.message);
        }
      });
    }
  };

  useEffect(() => {
    api
      .listUserAddress({})
      .then((res) => {
        console.log(res);
        setList(res.result);
        res.result?.map((item, index) => {
          if (item.type === 0) {
            setValue(item.id);
          }
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  //图片预览
  const [visible, setVisible] = useState(false);

  //扫码管理地址
  const [isAddAddressOpen, setIsAddAddressOpen] = useState(false);
  const [addressVisible, setAddressVisible] = useState(false);
  return (
    <OrderForGoodsBox>
      <div className='address'>
        <div className='top'>
          <div className='left'>确认收货地址</div>
          <div className='right'>
            <Button
              onClick={() => setIsAddAddressOpen(true)}
              type='link'
              style={{ color: '#007aff' }}
            >
              管理收货地址
            </Button>
          </div>
        </div>
        <div className='bottom'>
          {list?.length ? (
            list?.map((item, index) => (
              <div
                key={item.id}
                className={`item ${value === item.id ? 'active' : ''}`}
                onClick={() => onChangeValue(item.id)}
              >
                <div className='left'>
                  <div className='active'>
                    <div className='icon'></div>
                    <div className='label'>寄送至</div>
                  </div>
                  <Radio.Group onChange={onChange} value={value}>
                    <Space direction='vertical'>
                      <Radio value={item.id}>{item.takeAddress}</Radio>
                    </Space>
                  </Radio.Group>
                </div>
                {value === item.id ? (
                  <div className='right'>
                    <Button
                      onClick={() => setIsAddAddressOpen(true)}
                      type='link'
                      style={{ color: '#007aff' }}
                    >
                      修改地址
                    </Button>
                  </div>
                ) : null}
              </div>
            ))
          ) : (
            <div className='item active'>
              <div className='left'>
                <div className='active'>
                  <div className='icon'></div>
                  <div className='label'>
                    暂无地址，请打开手机端【云享飞】微信小程序，【我的】-【个人设置】-【地址管理】添加
                  </div>
                </div>
              </div>
              <div className='right'>
                <Button
                  onClick={() => setIsAddAddressOpen(true)}
                  type='link'
                  style={{ color: '#007aff' }}
                >
                  添加地址
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
      <div className='info'>
        <div className='title'>确认订单信息</div>
        <div className='table'>
          <div className='table-title'>
            <div className='table-item' style={{ width: 290 }}>
              宝贝
            </div>
            <div className='table-item' style={{ width: 130 }}>
              单价
            </div>
            <div className='table-item' style={{ width: 130 }}>
              数量
            </div>
            <div className='table-item' style={{ width: 435 }}>
              合计
            </div>
          </div>
          {mallDetail.orderGoodsProdDetailDTOS.map((item: any) => (
            <div className='table-body' key={item.id}>
              <div className='body-item article' style={{ width: 290 }}>
                <div className='image'>
                  <Image
                    className='image-box'
                    preview={{ visible: false }}
                    src={item.prodSkuSpecImage || ''}
                    onClick={() => setVisible(true)}
                  />
                  <div style={{ display: 'none' }}>
                    <Image.PreviewGroup
                      preview={{
                        visible,
                        onVisibleChange: (vis) => setVisible(vis),
                      }}
                    >
                      <Image src={item.prodSkuSpecImage || ''} />
                    </Image.PreviewGroup>
                  </div>
                </div>
                <div className='right'>
                  <div className='top'>{`【${item.productName}】${item.specName}` || ''}</div>
                  <div className='bottom'>版本：{item.versionDesc || ''}</div>
                  <div className='bottom'>料号：{item.partNo || ''}</div>
                </div>
              </div>
              <div className='body-item' style={{ width: 130 }}>
                {item.unitPrice || 0}
              </div>
              <div className='body-item' style={{ width: 130 }}>
                {item.buyNum || 1}
              </div>
              <div className='body-item total-price' style={{ width: 435 }}>
                {item.skuSpecAmount}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className='notes'>
        <div className='left'>
          <div className='label'>备注：</div>
          <TextArea
            value={areaValue}
            onChange={(e) => setAreaValue(e.target.value)}
            placeholder='请输入备注'
            autoSize={{ minRows: 3, maxRows: 5 }}
            style={{ width: 385, height: 72 }}
          />
        </div>
        <div className='right'>
          <div className='top'>
            <div className='font'>
              <div className='label'>运费：</div>
              <div className='value'>邮寄到付,由客户自己承担</div>
            </div>
            <div className='price'>0.00</div>
          </div>
          <div className='bottom'>
            <div className='font'>
              <div className='label'>押金：</div>
              <div className='value'>渠道商可免押金</div>
            </div>
            <div className='price'>0.00</div>
          </div>
        </div>
      </div>
      <div className='detail-box'>
        <div className='right-box'>
          <div className='detail'>
            <div className='top'>
              <div className='label'>实付款</div>
              <div className='price'>¥{mallDetail.orderAmount}</div>
            </div>
            <div className='bottom'>
              <div className='value'>寄送至</div>
              {list ? <div className='value-content'>{list![value]?.takeAddress}</div> : null}
            </div>
          </div>
          <div className='detail-sumbit'>
            <Button className='btn' onClick={detailSumbit}>
              提交订单
            </Button>
          </div>
        </div>
      </div>
      <Modal
        wrapClassName='addAddress'
        open={isAddAddressOpen}
        onCancel={() => setIsAddAddressOpen(false)}
        getContainer={false}
        maskClosable={false}
        width={420}
        footer={false}
      >
        <div className='title'>扫码管理地址</div>
        <div className='image'>
          <Image
            className='addressImg'
            preview={{ visible: false }}
            src={
              window.location.href.includes('https://test.iuav.shop/')
                ? 'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/image/app-iuav-formal1.jpg'
                : 'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/image/app-iuav-trial1.jpg' || ''
            }
            onClick={() => setAddressVisible(true)}
          />
          <div style={{ display: 'none' }}>
            <Image.PreviewGroup
              preview={{
                visible: addressVisible,
                onVisibleChange: (vis) => setAddressVisible(vis),
              }}
            >
              <Image
                src={
                  window.location.href.includes('https://test.iuav.shop/')
                    ? 'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/image/app-iuav-formal1.jpg'
                    : 'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/image/app-iuav-trial1.jpg' ||
                      ''
                }
              />
            </Image.PreviewGroup>
          </div>
        </div>
        <div className='content'>
          【打开微信扫一扫】-进入云享飞【我的】- 【个人设置】-【地址管理】
        </div>
      </Modal>
    </OrderForGoodsBox>
  );
}
