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

import { Tabs, Modal, Button, Form, message, DatePicker, Image as AImage, Input } from 'antd';
import type { TabsProps } from 'antd';
import { RangePickerProps } from 'antd/es/date-picker';
import moment from 'moment';
import Image from 'next/image';
import { useRouter } from 'next/router';

import commonApi from '~/api';
import Layout from '~/components/layout';
import WxCodeModal from '~/components/wxCodeModal';
import { UserContext } from '~/lib/userProvider';

import api, { ListPageJobInfoResp } from './api';
import Evaluate from './components/evaluate';
import AddressMap from './components/map';
import { Box } from './styled';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
export default function JobServicesDetail() {
  const router = useRouter();
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const [id, setId] = useState<number | null>(null);

  const [detail, setDetail] = useState<ListPageJobInfoResp | null>();
  const [sale, setSale] = useState<string | null>();
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `服务介绍`,
      children: (
        <div className='teamIntroduction'>
          {detail?.serviceIntroduction ? (
            <div dangerouslySetInnerHTML={{ __html: detail?.serviceIntroduction }}></div>
          ) : null}
        </div>
      ),
    },
    {
      key: '2',
      label: `服务评价`,
      children: <Evaluate evaluateInfo={detail?.inspComtList || []} />,
    },
  ];

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

  useEffect(() => {
    if (id) {
      api.listDetailJobServicesInfo({ id }).then((res) => {
        setDetail(res.result || null);
      });
    }
  }, [id]);

  useEffect(() => {
    setSale((Math.floor(Math.random() * 901) + 100).toFixed(0));
  }, []);

  // 预约弹框
  const [visible, setVisible] = useState(false);
  const [formDate] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isAddressMapShow, setIsAddressMapShow] = useState(false);
  const [addressContent, setAddressContent] = useState<any>();
  const [wxCodeImg, setWxCodeImg] = useState<string>('');
  const [wxCodeModalShow, setWxCodeModalShow] = useState<boolean>(false);

  useEffect(() => {
    getWXCode();
  }, []);
  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    return current && current < moment().endOf('day');
  };
  useEffect(() => {
    // 选择地点后重新验证
    formDate.setFieldValue('latitudeAndLongitude', addressContent);
    formDate.validateFields();
  }, [addressContent]);
  // 立即预约
  const appointmentNow = () => {
    if (userInfo) {
      setIsModalOpen(true);
    } else {
      setNeedLogin(true);
    }
  };

  const handleOk = () => {
    setLoading(true);
    formDate
      .validateFields()
      .then(async (values) => {
        // console.log(values);
        if (!addressContent) {
          message.warning('请选择地点');
          return;
        }
        const res = await api.insertOrderTask({
          address: addressContent.addressDteail,
          taskDescription: values.taskDescription,
          city: addressContent.city,
          inspectionId: detail?.id || 1,
          lat: addressContent.lat,
          lon: addressContent.lon,
          province: addressContent.province,
          startTime: moment(new Date(values.dateDetail[0])).format('YYYY-MM-DD HH:MM:SS'),
          endTime: moment(new Date(values.dateDetail[1])).format('YYYY-MM-DD HH:MM:SS'),
        });
        console.log(res);
        if (res.code === '200') {
          message.success('提交成功');
          formDate.resetFields();
          setAddressContent(undefined);
          setLoading(false);
          setIsModalOpen(false);
        } else {
          message.error(res.message);
          setLoading(false);
        }
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
        setLoading(false);
      });
  };
  const handleCancel = () => {
    setAddressContent(undefined);
    setIsModalOpen(false);
    formDate.resetFields();
  };
  // 在线沟通-二维码
  const showWxCodeModalClick = () => {
    setWxCodeModalShow(true);
  };
  const getWXCode = () => {
    commonApi.listBannerImg('WX_CODE').then(({ result }) => {
      if (result) {
        setWxCodeImg(result[1]?.bannerImg);
      }
    });
  };
  const wxCodeModalCancel = () => {
    setWxCodeModalShow(false);
  };

  return (
    <Layout>
      <Box>
        <div className='top'>
          <div className='top-image'>
            <Image fill src={detail?.coverPlan ? detail?.coverPlan : ''} alt='error' />
          </div>
          <div className='top-right'>
            <div className='right-top'>
              <div className='title'>{detail?.serviceName}</div>
              <div className='detail'>
                <div className='tab'>专业飞手</div>
                <span className='content'>飞手需通过认证培训才可作业</span>
              </div>
              <div className='more'>
                {/* <div className='tab filst'>测绘场景榜第1名</div> */}
                <div className='tab'>7x24小时服务</div>
                {/* <div className='tab'>{`月售${sale}`}</div> */}
              </div>
            </div>
            <div className='right-bottom'>
              <div className='bottom-btn'>
                <Button
                  className='btn-left'
                  size='small'
                  type='primary'
                  onClick={showWxCodeModalClick}
                >
                  在线沟通
                </Button>
                <Button onClick={appointmentNow} className='btn-right' size='small' type='primary'>
                  立即预约
                </Button>
              </div>
            </div>
          </div>
        </div>
        <Tabs className='tabs' defaultActiveKey='1' items={items} />

        <Modal
          wrapClassName='reservation'
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          getContainer={false}
          maskClosable={false}
          width={420}
          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?.coverPlan ? detail?.coverPlan : ''}
                onClick={() => setVisible(true)}
                style={{ width: 58, height: 58 }}
              />
              <div style={{ display: 'none' }}>
                <AImage.PreviewGroup
                  preview={{
                    visible,
                    onVisibleChange: (vis) => setVisible(vis),
                  }}
                >
                  <AImage src={detail?.coverPlan ? detail?.coverPlan : ''} />
                </AImage.PreviewGroup>
              </div>
            </div>
            <div className='right'>{detail?.serviceName}</div>
          </div>
          <Form
            form={formDate}
            layout='vertical'
            name='reservationForm'
            initialValues={{ modifier: 'public' }}
            className='form-data'
          >
            <Form.Item
              label='选择日期'
              style={{ flex: 1, marginRight: 16 }}
              name='dateDetail'
              rules={[{ required: true, message: '请选择日期' }]}
            >
              <RangePicker style={{ width: 376, marginTop: 10 }} disabledDate={disabledDate} />
            </Form.Item>
            <Form.Item
              label='选择地点'
              style={{ flex: 1, marginRight: 16 }}
              name='latitudeAndLongitude'
              rules={[{ required: true, message: '请选择地点' }]}
            >
              {addressContent ? (
                <div className='address-map'>
                  <div className='value'>已选择：{addressContent.addressDteail}</div>
                  <Button onClick={() => setIsAddressMapShow(true)} type='primary'>
                    修改位置
                  </Button>
                </div>
              ) : (
                <Button onClick={() => setIsAddressMapShow(true)} type='text'>
                  点击从地图选择地点
                </Button>
              )}
            </Form.Item>
            <div>
              任务描述(选填) 项目号、 业务负责人、
              客户名称、演示设备(注明飞机、挂载、地面站)、现场联系人及电话
            </div>
            <Form.Item style={{ flex: 1, marginRight: 16 }} name='taskDescription'>
              <TextArea
                placeholder='补充描述有助于方案沟通更高效哦~'
                autoSize={{ minRows: 3, maxRows: 5 }}
                style={{ width: 385, height: 72 }}
              />
            </Form.Item>
          </Form>
        </Modal>

        {isAddressMapShow ? (
          <Modal
            wrapClassName='reservation'
            open={isAddressMapShow}
            onCancel={() => setIsAddressMapShow(false)}
            getContainer={false}
            maskClosable={false}
            width={850}
            footer={false}
          >
            <div style={{ textAlign: 'center', fontWeight: '700' }}>选择地点</div>
            <AddressMap
              setAddressContent={setAddressContent}
              setIsAddressMapShow={setIsAddressMapShow}
            />
          </Modal>
        ) : null}
        <WxCodeModal
          wxCodeImg={wxCodeImg}
          open={wxCodeModalShow}
          onCancel={wxCodeModalCancel}
        ></WxCodeModal>
      </Box>
    </Layout>
  );
}
