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

import {
  Button,
  Image as AImage,
  Divider,
  Select,
  Modal,
  Tag,
  Space,
  Form,
  message,
  InputNumber,
  DatePicker,
} from 'antd';
import { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import Image from 'next/image';
import { useRouter } from 'next/router';

import Layout from '~/components/layout';
import { UserContext } from '~/lib/userProvider';

import api, { GetWebDeviceDetailResult, GetWebDeviceWareSkuById, GetLeaseGoodsResult } from './api';
import flowPat from './assets/flow-path.png';
// eslint-disable-next-line import/no-cycle
import OrderForGoods from './components/orderForGoods';
import ImagePreview from './components/picture-preview';
import { Box } from './styled';

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, minDay: 1, maxDay: 7 },
    { id: 1, label: '8-15天', disable: false, minDay: 8, maxDay: 15 },
    { id: 2, label: '16-30天', disable: false, minDay: 16, maxDay: 30 },
    { id: 3, label: '31天以上', disable: false, minDay: 31, maxDay: -1 },
  ];

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

  // 获取价格
  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) => {
        // console.log('discount --->', res.result);
        setDiscount(res.result);
      });
    }
  };

  // 显示弹窗
  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 [days, setDays] = useState<number>();

  // 规格弹窗选择规格之后点击提交
  const handleOk = () => {
    setLoading(true);
    form
      .validateFields()
      .then(async (_values) => {
        setLoading(false);
        setIsModalOpen(false);
        setIsModalDateOpen(true);
        // 当前选择的租期范围
        const leaseTime = tagsData.find((i) => i.id === selectedTagsData);
        // 设置日期默认值
        formDate.setFieldValue('dateDetail', [
          dayjs(),
          dayjs().add(
            Number(leaseTime?.minDay) > 1
              ? Number(leaseTime?.minDay) - 1
              : Number(leaseTime?.minDay),
            'day',
          ),
        ]);
        // 设置默认天数
        setDays(leaseTime?.minDay);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
        setLoading(false);
      });
  };

  // 确认租期点击事件
  const handleOkDate = async () => {
    // 当前选择的租期范围
    const leaseTime = tagsData.find((i) => i.id === selectedTagsData);
    // 判断租期
    if (leaseTime?.maxDay === -1 && Number(days) < Number(leaseTime?.minDay)) {
      message.warning(`租期最少${leaseTime?.minDay}天`);
      return;
    }
    if (leaseTime?.maxDay !== -1 && Number(leaseTime) < Number(leaseTime?.minDay)) {
      message.warning(`租期至少${leaseTime?.minDay}天`);
      return;
    }
    if (leaseTime?.maxDay !== -1 && Number(days) > Number(leaseTime?.maxDay)) {
      message.warning(`租期最多${leaseTime?.maxDay}天`);
      return;
    }
    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 onChangeNum = (value: number | string | null) => {
    console.log('changed', value);
  };

  // 选择租期返回事件
  const goBack = () => {
    // 日期选择弹窗隐藏
    setIsModalDateOpen(false);
    // 租赁弹窗显示
    setIsModalOpen(true);
    // 重置日期选择表单
    formDate.resetFields();
  };

  // 租期选择监听事件
  const onDateChanges = (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 < dayjs().endOf('day');
  };

  // 生成价格
  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 (
    <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='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'>{getSpecPrice() || 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={onDateChanges}
                />
              </Form.Item>
            </Form>
            <div className='bottom-item'>
              <div className='label'>租金合计</div>
              <div className='price'>
                <div className='left'>
                  ¥{getSpecPrice()! * 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>
  );
}
