import React, { 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'
const { RangePicker } = DatePicker
const { TextArea } = Input
export default function JobServicesDetail() {
  const router = useRouter()

  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"
          />
        </div>
      ),
    },
    {
      key: '2',
      label: `团队评价`,
      children: <Evaluate evaluateInfo={detail?.evaluateInfo || []} />,
    },
  ]

  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 [areaValue, setAreaValue] = useState<string>()
  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    return current && current < moment().endOf('day')
  }
  const handleOk = () => {
    setLoading(true)
    formDate
      .validateFields()
      .then(async (values) => {
        console.log(values)

        const res = await api.insertOrderTask({
          address: '西丽街道',
          city: '深圳',
          inspectionId: detail?.id || 1,
          lat: 30,
          lon: 120,
          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)
        // formDate.resetFields()
        // setLoading(false)
        // setIsModalOpen(false)
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then()
        setLoading(false)
      })
  }
  const handleCancel = () => {
    setIsModalOpen(false)
    formDate.resetFields()
  }
  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)
    }
  }

  return (
    <Layout>
      <Box>
        <div className="top">
          <div className="top-image">
            <Image
              fill
              src={detail?.pictureUrl ? detail?.pictureUrl : ''}
              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={() => setIsModalOpen(true)}
                  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?.pictureUrl ? detail?.pictureUrl : ''}
                onClick={() => setVisible(true)}
                style={{ width: 58, height: 58 }}
              />
              <div style={{ display: 'none' }}>
                <AImage.PreviewGroup
                  preview={{
                    visible,
                    onVisibleChange: (vis) => setVisible(vis),
                  }}
                >
                  <AImage src={detail?.pictureUrl ? detail?.pictureUrl : ''} />
                </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
              style={{ flex: 1, marginRight: 16 }}
              name="dateDetail"
              rules={[{ required: true, message: '请选择日期' }]}
            >
              <RangePicker
                style={{ width: 376, marginTop: 10 }}
                disabledDate={disabledDate}
                onChange={onchanges}
                showTime
              />
            </Form.Item>
            <div>
              任务描述(选填) 项目号、 业务负责人、
              客户名称、演示设备(注明飞机、挂载、地面站)、现场联系人及电话
            </div>
            <Form.Item
              style={{ flex: 1, marginRight: 16 }}
              name="taskDescription"
            >
              <TextArea
                value={areaValue}
                onChange={(e) => setAreaValue(e.target.value)}
                placeholder="补充描述有助于方案沟通更高效哦~"
                autoSize={{ minRows: 3, maxRows: 5 }}
                style={{ width: 385, height: 72 }}
              />
            </Form.Item>
          </Form>
        </Modal>
      </Box>
    </Layout>
  )
}
