import React, { useEffect, useState, useContext } from 'react'
import { useRouter } from 'next/router'
import Layout from '~/components/layout'
import { Box } from './styled'
import ImagePreview from './components/picture-preview'
import OrderForGoods from './components/orderForGoods'
import moment from 'moment'
import {
  Button,
  Image as AImage,
  Divider,
  Select,
  Modal,
  Tag,
  Space,
  Form,
  message,
  InputNumber,
  DatePicker,
} from 'antd'
import Image from 'next/image'
import errImg from '~/assets/errImg'
import api, {
  GetWebDeviceDetailResult,
  GetWebDeviceWareSkuById,
  GetLeaseGoodsResult,
} from './api'
import { UserContext } from '~/lib/userProvider'
import flowPat from './assets/flow-path.png'
import { RangePickerProps } from 'antd/es/date-picker'
const { RangePicker } = DatePicker
const { CheckableTag } = Tag

export interface ShopDetail {
  dateDetail: Array<Date>
  num: number
  id: number
}

export default function EquipmentLeasingDetail() {
  const router = useRouter()
  const { userInfo, setNeedLogin } = useContext(UserContext)
  const [id, setId] = useState<number | null>(null)

  const [detail, setDetail] = useState<GetWebDeviceDetailResult | null>()
  const [wareSkuList, setWareSkuList] = useState<
    GetWebDeviceWareSkuById[] | undefined
  >()

  useEffect(() => {
    setId(Number(router.query.id))
  }, [router])

  useEffect(() => {
    if (id) {
      api
        .listDetailDeviceInfo({
          goodsId: id,
          type: 1,
        })
        .then((res) => {
          setDetail(res.result || null)
          const wareList = res.result?.goodsSpec.map(
            (item) => item.productSpecList
          )
          if (wareList) {
            const List: GetWebDeviceWareSkuById[] = wareList.flat()
            setWareSkuList(List)
          }
        })
    }
  }, [id])

  //租赁弹框
  const [visible, setVisible] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalDateOpen, setIsModalDateOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [isorderForGoods, setIsorderForGoods] = useState(false)
  const [form] = Form.useForm()
  const [formDate] = Form.useForm()
  const tagsData = [
    { id: 0, label: '1-7天', disable: false },
    { id: 1, label: '8-15天', disable: false },
    { id: 2, label: '16-30天', disable: false },
    { id: 3, label: '30天以上', disable: false },
  ]

  const [discount, setDiscount] = useState<GetLeaseGoodsResult | null>()
  const [selectedTags, setSelectedTags] = useState<number>()
  const [selectedTagsData, setSelectedTagsData] = useState<number>()
  const [shopDetail, setShopDetail] = useState<ShopDetail>()

  const showModal = () => {
    if (userInfo) {
      setIsModalOpen(true)
      if (wareSkuList?.length) {
        setSelectedTags(wareSkuList[0].id)
        form.setFieldValue('id', wareSkuList[0].id)
        setSelectedTagsData(0)
        form.setFieldValue('date', 0)
        getPrice(0)
      }
    } else {
      setNeedLogin(true)
    }
  }

  const handleOk = () => {
    setLoading(true)
    form
      .validateFields()
      .then(async (values) => {
        setLoading(false)
        setIsModalOpen(false)
        setIsModalDateOpen(true)
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then()
        setLoading(false)
      })
  }

  const [days, setDays] = useState<number>()

  const handleOkDate = async () => {
    setLoading(true)
    try {
      const result = await Promise.all([
        form.validateFields(),
        formDate.validateFields(),
      ])
      if (result) {
        setLoading(false)
        setIsModalOpen(false)
        setIsModalDateOpen(false)
        setIsorderForGoods(true)
        setShopDetail({ ...result[0], ...result[1] })
      }
    } catch (error) {
      setLoading(false)
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false)
    setIsModalDateOpen(false)
    form.resetFields()
    formDate.resetFields()
  }

  const handleChange = (tag: number, checked: boolean) => {
    if (checked) {
      const nextWareSkuList = checked
        ? tag
        : wareSkuList?.filter((t) => t.id !== tag)[0].id
      setSelectedTags(nextWareSkuList)
      form.setFieldValue('id', tag)
    }
  }

  const handleChangeDate = (
    tag: number,
    checked: boolean,
    disable: boolean
  ) => {
    if (checked && !disable) {
      const nextSelectedTags = checked
        ? tag
        : tagsData.filter((t) => t.id !== tag)[0].id
      setSelectedTagsData(nextSelectedTags)
      form.setFieldValue('date', tag)
      getPrice(tag)
    }
  }

  const getPrice = (tag: number) => {
    const Id = wareSkuList?.filter(
      (item) => item.id === form.getFieldValue('id')
    )[0].productSpec
    if (Id) {
      api
        .GoodsPriceDetail({ leaseTerm: tag, productSpecId: Id })
        .then((res) => {
          setDiscount(res.result)
        })
    }
  }

  const onChangeNum = (value: number | string | null) => {
    console.log('changed', value)
  }
  const goBack = () => {
    setIsModalDateOpen(false)
    setIsModalOpen(true)
  }
  const onchanges = (values: any) => {
    if (values) {
      const day = new Date(values[1]).getTime() - new Date(values[0]).getTime()
      const totalDays = Math.floor(day / (1000 * 3600 * 24))
      setDays(totalDays)
    } else {
      setDays(undefined)
    }
  }

  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    return current && current < moment().endOf('day')
  }

  return (
    <Layout>
      {!isorderForGoods ? (
        <Box>
          <div className="item">
            <ImagePreview imgList={detail?.images!} />
            <div className="item-right">
              <div className="title">{detail?.goodsName}</div>
              {detail?.otherService?.length ? (
                <div className="function">
                  {detail?.otherService?.map((item) => (
                    <div key={item.id} className="function-item">
                      {item.serviceName}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="function not"></div>
              )}
              {userInfo?.cooperationTagId ? (
                <div className="menoy">
                  <span className="menoy-left">{`¥${detail?.price! | 0}`}</span>
                  <span className="menoy-right">/天起</span>
                </div>
              ) : (
                <div className="menoy">暂无报价</div>
              )}

              <div className="classification">
                <div className="top">
                  <div className="left">
                    <span className="label">选择</span>
                    <span className="value">商品分类</span>
                  </div>
                  <div className="right">
                    <Select
                      className="selectItem"
                      defaultActiveFirstOption
                      defaultValue={wareSkuList}
                      style={{ width: 120 }}
                      bordered={false}
                      options={wareSkuList}
                      fieldNames={{ label: 'specName', value: 'id' }}
                      placeholder="选择商品"
                    />
                  </div>
                </div>
                <div className="bottom">
                  <span className="label">发货</span>
                  <span className="value">顺丰到付</span>
                </div>
              </div>
              <div className="botton-btn">
                {/* <Button className='btn-left' size='small' type="primary">成为渠道商</Button> */}
                <Button
                  className="btn-right"
                  size="small"
                  type="primary"
                  onClick={showModal}
                >
                  立即租赁
                </Button>
              </div>
            </div>
          </div>
          <div className="flow-path">
            <Image className="image" fill src={flowPat.src} alt="" />
          </div>
          <div className="prompt">更多租金规则请前往【云享飞】微信小程序查</div>
          <Divider className="divider">商品详情</Divider>
          {detail?.goodsDetail.content ? (
            <div
              style={{ textAlign: 'center' }}
              dangerouslySetInnerHTML={{ __html: detail?.goodsDetail.content }}
            ></div>
          ) : null}
          {/* 立即租赁 */}
          <Modal
            wrapClassName="application"
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
            getContainer={false}
            maskClosable={false}
            footer={[
              <Button
                style={{ width: '100%', height: 44 }}
                key="submit"
                type="primary"
                loading={loading}
                onClick={handleOk}
              >
                立即租赁
              </Button>,
            ]}
          >
            <div className="title">
              <div className="left">
                <AImage
                  preview={{ visible: false }}
                  src={detail?.images[0].imgUrl}
                  onClick={() => setVisible(true)}
                />
                <div style={{ display: 'none' }}>
                  <AImage.PreviewGroup
                    preview={{
                      visible,
                      onVisibleChange: (vis) => setVisible(vis),
                    }}
                  >
                    {detail?.images.map((item) => (
                      <AImage key={item.id} src={item.imgUrl} />
                    ))}
                  </AImage.PreviewGroup>
                </div>
              </div>
              <div className="right">
                <div className="top">
                  <span className="tag">¥</span>
                  <span className="money">
                    {discount?.specPrice[0]?.price || 0}
                  </span>
                  <span className="unit">/天</span>
                </div>
                <div className="bottom">渠道免押金</div>
              </div>
            </div>
            <Form
              form={form}
              layout="vertical"
              name="application"
              initialValues={{ num: 1 }}
              className="form-data"
            >
              <Form.Item
                style={{ flex: 1, marginRight: 16 }}
                name="id"
                label="选择商品"
              >
                <Space size={[0, 8]} wrap>
                  {wareSkuList?.map((tag) => (
                    <CheckableTag
                      style={{ height: 28, lineHeight: '28px' }}
                      key={tag.id}
                      checked={wareSkuList?.some(
                        (item) => tag.id === selectedTags
                      )}
                      onChange={(checked) => handleChange(tag.id, checked)}
                    >
                      {tag.specName}
                    </CheckableTag>
                  ))}
                </Space>
              </Form.Item>
              <Form.Item
                style={{ flex: 1, marginRight: 16 }}
                name="date"
                label="租期天数（拿到和归还当天不算入租期）"
              >
                <Space size={[0, 8]} wrap>
                  {tagsData.map((tag) => (
                    <CheckableTag
                      key={tag.id}
                      checked={tag.id === selectedTagsData}
                      onChange={(checked) =>
                        handleChangeDate(tag.id, checked, tag.disable)
                      }
                      className={`tagsData ${
                        tag.disable ? 'disable tagsDisable' : ''
                      }`}
                    >
                      {tag.label}
                    </CheckableTag>
                  ))}
                </Space>
              </Form.Item>
              <div className="num-box">
                <div className="num-left">
                  <div className="label">租赁数量</div>
                </div>
                <div className="num-right">
                  <Form.Item style={{ flex: 1, marginRight: 16 }} name="num">
                    <InputNumber min={1} max={100} onChange={onChangeNum} />
                  </Form.Item>
                </div>
              </div>
            </Form>
          </Modal>

          <Modal
            wrapClassName="applicationDate"
            open={isModalDateOpen}
            onOk={handleOkDate}
            onCancel={handleCancel}
            getContainer={false}
            maskClosable={false}
            width={420}
            footer={[
              <Button
                style={{ width: '100%', height: 44 }}
                key="submit"
                type="primary"
                loading={loading}
                onClick={handleOkDate}
              >
                确认租期{days ? `${days}天` : null}
              </Button>,
            ]}
          >
            <div className="title">
              <div className="left" onClick={goBack}>
                {'<'}
              </div>
              <div className="right">选择租期</div>
            </div>
            <Form
              form={formDate}
              layout="vertical"
              name="applicationDate"
              initialValues={{ modifier: 'public' }}
              className="form-data"
            >
              <Form.Item
                style={{ flex: 1, marginRight: 16 }}
                name="dateDetail"
                rules={[{ required: true, message: '请选择日期' }]}
              >
                <RangePicker
                  style={{ width: 376, marginTop: 10 }}
                  disabledDate={disabledDate}
                  onChange={onchanges}
                />
              </Form.Item>
            </Form>
            <div className="bottom-item">
              <div className="label">租金合计</div>
              <div className="price">
                <div className="left">
                  ¥
                  {discount?.specPrice[0]?.price! *
                    days! *
                    form.getFieldValue('num') || 0}
                </div>
                {/* <div className="right">(日均175)</div> */}
              </div>
            </div>
          </Modal>
        </Box>
      ) : (
        <OrderForGoods
          setIsorderForGoods={setIsorderForGoods}
          shopDetail={shopDetail}
          days={days}
          detailData={detail}
          discount={discount}
          wareSkuList={wareSkuList?.filter(
            (item) => item.id === form.getFieldValue('id')
          )}
        />
      )}
    </Layout>
  )
}
