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
  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)
  }
  const detailSumbit = () => {
    if (detailData && shopDetail && list && wareSkuList) {
      const pushList = {
        actualPay:
          discount?.specPrice[0].price! * 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:
          discount?.specPrice[0].price! * shopDetail?.num! * days! || 0,
        returnDate: moment(
          new Date(shopDetail.dateDetail[1]).getTime() + 864e5
        ).format('YYYY-MM-DD'),
        shouldPay:
          discount?.specPrice[0].price! * 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('提交成功')
          setPaymentDetail(res.result)
          setIsPaymentOpen(true)
        } 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(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) {
      const date = new FormData()
      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)
    }
  }

  return (
    <OrderForGoodsBox>
      <div className="address">
        <div className="top">
          <div className="left">确认收货地址</div>
          <div className="right">
            <Button type="link" style={{ color: '#007aff' }}>
              管理收货地址
            </Button>
          </div>
        </div>
        <div className="bottom">
          {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 type="link" style={{ color: '#007aff' }}>
                    修改地址
                  </Button>
                </div>
              ) : null}
            </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
                  preview={{ visible: false }}
                  src={wareSkuList![0].specImage}
                  onClick={() => setVisible(true)}
                />
                <div style={{ display: 'none' }}>
                  <Image.PreviewGroup
                    preview={{
                      visible,
                      onVisibleChange: (vis) => setVisible(vis),
                    }}
                  >
                    <Image src={wareSkuList![0].specImage} />
                  </Image.PreviewGroup>
                </div>
              </div>
              <div className="right">
                <div className="top">{wareSkuList![0].specName}</div>
                <div className="bottom">{wareSkuList![0].versionDesc}</div>
              </div>
            </div>
            <div className="body-item" style={{ width: 130 }}>
              {discount?.specPrice[0].price || 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 }}>
              {discount?.specPrice[0].price! * 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">
                ¥{discount?.specPrice[0].price! * 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>
    </OrderForGoodsBox>
  )
}
