import React, { useContext, useEffect, useState } from 'react';

import type { RadioChangeEvent } from 'antd';
import { Button, Radio, Space, Input, message, Modal, Image } from 'antd';
import moment from 'moment';

import { UserContext } from '~/lib/userProvider';

import api, { UserAddress, GetOrderForGoods } from './api';
import { OrderForGoodsBox } from './styled';
// eslint-disable-next-line import/no-cycle
import { ShopDetail } from '../../[id].page';
import { GetWebDeviceDetailResult, GetWebDeviceWareSkuById, GetLeaseGoodsResult } from '../../api';

const { TextArea } = Input;
interface PropsBox {
  setIsOrderForGoods: (boolean: boolean) => void;
  detailData?: GetWebDeviceDetailResult | null;
  days?: number;
  shopDetail?: ShopDetail;
  wareSkuList?: GetWebDeviceWareSkuById[];
  discount?: GetLeaseGoodsResult | null;
}

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

  const onChange = (e: RadioChangeEvent) => {
    // console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  const onChangeValue = (index: number) => {
    setValue(index);
  };
  // eslint-disable-next-line consistent-return
  const detailSumbit = () => {
    if (!list?.length) return message.warning('暂无地址信息,请前往云享飞添加地址');
    if (value === -1) return message.warning('请选择地址');
    if (detailData && shopDetail && list?.length && wareSkuList) {
      const pushList = {
        actualPay: getSpecPrice() * shopDetail?.num! * days! || 0,
        deposit: 0,
        endDate: moment(new Date(shopDetail.dateDetail[1])).format('YYYY-MM-DD'),
        orderReceipt: {
          detailAddress: list[value]?.takeAddress,
          receiptMethod: 0,
          region: list[value]?.takeRegion,
          takeName: list[value]?.takeName,
          takePhone: Number(list[value]?.takePhone),
        },
        rentPrice: getSpecPrice() * shopDetail?.num! * days! || 0,
        returnDate: moment(new Date(shopDetail.dateDetail[1]).getTime() + 864e5).format(
          'YYYY-MM-DD',
        ),
        shouldPay: getSpecPrice() * shopDetail?.num! * days! || 0,
        specsId: wareSkuList[0].productSpec,
        startDate: moment(new Date(shopDetail.dateDetail[0]!)).format('YYYY-MM-DD'),
        wareDescription: detailData.goodsName,
        wareImg: detailData.images[0].imgUrl,
        wareInfoId: shopDetail.id,
        wareNo: detailData.goodsNo,
        wareNum: shopDetail.num,
        wareTitle: detailData.goodsName,
        remark: areaValue,
      };

      api.FeignAddLease(pushList).then((res) => {
        if (res.code === '200') {
          message.success('提交成功').then();
          setPaymentDetail(res.result);
          // setIsPaymentOpen(true)
          setIsOrderForGoods(false);
        } else {
          message.error(res.message).then();
        }
      });
    }
  };

  useEffect(() => {
    api
      .listUserAddress({})
      .then((res) => {
        // console.log(res);
        setList(res.result);
        const index: number = res.result?.findIndex((item) => item.type === 0) as number;
        setValue(index);
      })
      .catch((err) => {
        // console.log(err);
      });
    if (shopDetail) {
      setDetail(shopDetail);
    }
  }, []);

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

  // 付款
  const { userInfo } = useContext(UserContext);
  const [loading, setLoading] = useState(false);
  const [isPaymentOpen, setIsPaymentOpen] = useState(false);
  const [paymentDetail, setPaymentDetail] = useState<GetOrderForGoods | null>();
  const handleCancel = () => {
    setIsPaymentOpen(false);
  };
  const handleOkPayment = () => {
    setLoading(true);
    if (paymentDetail?.orderNo) {
      api.OrderPayment({ orderNo: paymentDetail?.orderNo }).then((res) => {
        if (res.code === '200') {
          message.success('付款成功');
          setLoading(false);
          setIsOrderForGoods(false);
          handleCancel();
        } else {
          message.error(res.message);
          setLoading(false);
        }
      });
    } else {
      message.error('出错了');
      setLoading(false);
    }
  };

  // 扫码管理地址
  const [isAddAddressOpen, setIsAddAddressOpen] = useState(false);
  const [addressVisible, setAddressVisible] = useState(false);

  // 生成价格
  const getSpecPrice = () => {
    const tagList = userInfo?.cooperationTagVOS?.map((i: { id: number }) => i.id) || [0];
    // console.log('tagList --->', discount?.specPrice);
    return (
      tagList
        .map((i: number) => discount?.specPrice.find((k) => k.cooperationTag === i))
        // @ts-ignore
        ?.sort((a, b) => a.price - b.price)
        ?.at(0)?.price || 0
    );
  };

  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 === index ? 'active' : ''}`}
                onClick={() => onChangeValue(index)}
              >
                <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={index}>{item.takeAddress}</Radio>
                    </Space>
                  </Radio.Group>
                </div>
                {value === index ? (
                  <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: 300 }}>
              租期
            </div>
            <div className='table-item' style={{ width: 135 }}>
              合计
            </div>
          </div>
          <div className='table-body'>
            <div className='body-item article' style={{ width: 290 }}>
              <div className='image'>
                <Image
                  className='image-box'
                  preview={{ visible: false }}
                  src={(wareSkuList && wareSkuList![0].specImage) || ''}
                  onClick={() => setVisible(true)}
                />
                <div style={{ display: 'none' }}>
                  <Image.PreviewGroup
                    preview={{
                      visible,
                      onVisibleChange: (vis) => setVisible(vis),
                    }}
                  >
                    <Image src={(wareSkuList && wareSkuList![0].specImage) || ''} />
                  </Image.PreviewGroup>
                </div>
              </div>
              <div className='right'>
                <div className='top'>{(wareSkuList && wareSkuList![0].specName) || ''}</div>
                <div className='bottom'>{(wareSkuList && wareSkuList![0].versionDesc) || ''}</div>
              </div>
            </div>
            <div className='body-item' style={{ width: 130 }}>
              {getSpecPrice() || 0}
            </div>
            <div className='body-item' style={{ width: 130 }}>
              {shopDetail?.num || 1}
            </div>
            <div className='body-item lease-term' style={{ width: 300 }}>
              {moment(new Date(shopDetail?.dateDetail[0]!)).format('YYYY/MM/DD')}
              <div className='num'>{days}天</div>
              {moment(new Date(shopDetail?.dateDetail[1]!)).format('YYYY/MM/DD')}
            </div>
            <div className='body-item total-price' style={{ width: 135 }}>
              {getSpecPrice() * shopDetail?.num! * days! || 0}
            </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'>¥{getSpecPrice() * shopDetail?.num! * days! || 0}</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="Payment"
        open={isPaymentOpen}
        onOk={handleOkPayment}
        onCancel={handleCancel}
        getContainer={false}
        maskClosable={false}
        width={420}
        footer={[
          <Button
            style={{ width: '100%', height: 44 }}
            key="submit"
            type="primary"
            loading={loading}
            onClick={handleOkPayment}
          >
            立即付款
          </Button>,
        ]}
      >
        <div className="title">
          ￥{discount?.specPrice[0]?.price! * shopDetail?.num! * days! || 0}
        </div>
        <div>云享飞账号： {userInfo?.uid}</div>
        <div>付款方式： 可用(￥{paymentDetail?.balance})</div>
      </Modal> */}

      <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.com/')
                ? '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.com/')
                    ? '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>
  );
}
