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 } 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 wareSkuList: GetWebDeviceWareSkuById[] = wareList.flat()
            setWareSkuList(wareSkuList)
          }
        })
    }
  }, [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 = [
    { label: '1-7天', disable: false },
    { label: '8-15天', disable: false },
    { label: '16-30天', disable: false },
    { label: '30天以上', disable: false },
  ]
  const [selectedTags, setSelectedTags] = useState<number>()
  const [selectedTagsData, setSelectedTagsData] = useState<string>()
  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('1-7天')
        form.setFieldValue('date', '3-7天')
      }
    } 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: string,
    checked: boolean,
    disable: boolean
  ) => {
    if (checked && !disable) {
      const nextSelectedTags = checked
        ? tag
        : tagsData.filter((t) => t.label !== tag)[0].label
      setSelectedTagsData(nextSelectedTags)
      form.setFieldValue('date', tag)
    }
  }

  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>
              )}
              <div className="menoy">
                <span className="menoy-left">{`¥${detail?.price! | 0}`}</span>
                <span className="menoy-right">/天起</span>
              </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>
          ) : (
            <div style={{ textAlign: 'center' }}></div>
          )}
          {/* 立即租赁 */}
          <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">{detail?.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.label}
                      checked={tag.label === selectedTagsData}
                      onChange={(checked) =>
                        handleChangeDate(tag.label, 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={10} 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">¥{detail?.price! * days! || 0}</div>
                {/* <div className="right">(日均175)</div> */}
              </div>
            </div>
          </Modal>
        </Box>
      ) : (
        <OrderForGoods
          setIsorderForGoods={setIsorderForGoods}
          shopDetail={shopDetail}
          days={days}
          detailData={detail}
          wareSkuList={wareSkuList?.filter(
            (item) => item.id === form.getFieldValue('id')
          )}
        />
      )}
    </Layout>
  )
}
