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 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({
          id: id,
        })
        .then((res) => {
          setDetail(res.result || null)
        })
      api
        .listWareSkuById({
          id: id,
        })
        .then((res) => {
          res.result?.map((item) => {
            return item
          })
          setWareSkuList(res.result || undefined)
        })
    }
  }, [id])

  //租赁弹框
  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: '3-7天', disable: false },
    { label: '8-15天', disable: false },
    { label: '16-30天', disable: true },
    { label: '30天以上', disable: false },
  ]
  const [selectedTags, setSelectedTags] = useState<number>()
  const [selectedTagsData, setSelectedTagsData] = useState<string>()

  const showModal = () => {
    if (userInfo) {
      setIsModalOpen(true)
      if (wareSkuList?.length) {
        setSelectedTags(wareSkuList[0].id)
        form.setFieldValue('id', wareSkuList[0].id)
        setSelectedTagsData('3-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)
    const result = await Promise.all([
      form.validateFields(),
      formDate.validateFields(),
    ])
    console.log(result)
    if (result) {
    }
    form
      .validateFields()
      .then(async (values) => {
        setLoading(false)
        setIsModalOpen(false)
        setIsModalDateOpen(false)
        setIsorderForGoods(true)
        //   try{
        //    const res = await api.listWareSkuUpdate(values)
        //    if (res.code === "200") {
        //    setLoading(false);
        //    setIsModalOpen(false);
        //    form.resetFields()
        //    message.success('租赁成功')
        //    }else{
        //      setLoading(false);
        //      message.error(res.message)
        //    }

        //  }catch(e:any){
        //    message.error(e.message)
        //  }
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then()
        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
      console.log('You are interested in: ', nextWareSkuList)
      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
      console.log('You are interested in: ', nextSelectedTags)
      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?.wareImgs!} />
            <div className="item-right">
              <div className="title">{detail?.wareTitle}</div>
              {detail?.tags?.length ? (
                <div className="function">
                  {detail?.tags?.map((item) => (
                    <div key={item} className="function-item">
                      {item}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="function not"></div>
              )}
              <div className="menoy">
                <span className="menoy-left">{`¥${detail?.minRent}`}</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: 'skuTitle', 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?.wareDetailContent ? (
            <div
              style={{ textAlign: 'center' }}
              dangerouslySetInnerHTML={{ __html: detail?.wareDetailContent }}
            ></div>
          ) : (
            <div style={{ textAlign: 'center' }}></div>
          )}
          {/* 立即租赁 */}
          <Modal
            wrapClassName="application"
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
            getContainer={false}
            footer={[
              <Button
                style={{ width: '100%', height: 44 }}
                key="submit"
                type="primary"
                loading={loading}
                onClick={handleOk}
              >
                立即租赁
              </Button>,
            ]}
          >
            <div className="title">
              <div className="left"></div>
              <div className="right">
                <div className="top">
                  <span className="tag">¥</span>
                  <span className="money">{detail?.minRent}</span>
                  <span className="unit">/天</span>
                </div>
                <div className="bottom">渠道免押金</div>
              </div>
            </div>
            <Form
              form={form}
              layout="vertical"
              name="application"
              initialValues={{ modifier: 'public' }}
              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.skuTitle}
                    </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>
              <Form.Item style={{ flex: 1, marginRight: 16 }} name="num">
                <div className="num-box">
                  <div className="num-left">
                    <div className="label">租赁数量</div>
                    <div className="inventory">库存9件</div>
                  </div>
                  <div className="num-right">
                    <InputNumber
                      min={1}
                      max={10}
                      defaultValue={3}
                      onChange={onChangeNum}
                    />
                  </div>
                </div>
              </Form.Item>
            </Form>
          </Modal>

          <Modal
            wrapClassName="applicationDate"
            open={isModalDateOpen}
            onOk={handleOkDate}
            onCancel={handleCancel}
            getContainer={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">
                <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">¥700</div>
                <div className="right">(日均175)</div>
              </div>
            </div>
          </Modal>
        </Box>
      ) : (
        <OrderForGoods setIsorderForGoods={setIsorderForGoods} />
      )}
    </Layout>
  )
}
