import React, { useContext, useEffect, useState } from 'react';
import Layout from '~/components/layout';
import { Box } from './styled';
import moment from 'moment';
import { Tabs, Modal, Button, Form, message, DatePicker, Image as AImage, Input } from 'antd';
import { RangePickerProps } from 'antd/es/date-picker';
import type { TabsProps } from 'antd';
import Evaluate from './components/evaluate';
import { useRouter } from 'next/router';
import api, { ListPageJobInfoResp } from './api';
import Image from 'next/image';
import { RegionResp } from '~/components/filter/api';
import AddressMap from './components/map';
import { UserContext } from '~/lib/userProvider';
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 onChange = (key: string) => {
    console.log(key);
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `团队介绍`,
      children: (
        <div className='teamIntroduction'>
          {/* <Image width={1100} height={800} src={detail?.teamPoster ? detail?.teamPoster : ''} alt='error'/> */}
          {/* <img
            style={{ width: '100%' }}
            src={detail?.teamPoster ? detail?.teamPoster : ''}
            alt="error"
          /> */}
          {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 [provinceList, setProvinceList] = useState<RegionResp[]>([]);
  const [isAddressMapShow, setIsAddressMapShow] = useState(false);
  const [addressContent, setAddressContent] = useState<any>();

  useEffect(() => {
    api.region().then((res) => {
      console.log(res);
      console.log(res?.result?.map((item) => item.childInfo).flat());

      setProvinceList(res?.result || []);
    });
  }, []);
  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) {
          return message.warning('请选择地点');
        }
        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();
  };

  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'>
                  电话沟通
                </Button>
                <Button onClick={appointmentNow} className='btn-right' size='small' type='primary'>
                  立即预约
                </Button>
              </div>
            </div>
          </div>
        </div>
        <Tabs className='tabs' defaultActiveKey='1' items={items} onChange={onChange} />

        <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}
      </Box>
    </Layout>
  );
}
