import {
  Form,
  Input,
  Row,
  Col,
  Upload,
  Modal,
  message,
  Select,
  DatePicker,
  Radio,
} from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import * as coursesAPI from '../../apis/coursesAPI';
import { useTranslation } from 'react-i18next';
import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
} from 'react';
import { useForm } from 'antd/lib/form/Form';
import moment from 'moment';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import ImgCrop from 'antd-img-crop';

// 创建直播课，由 CreateCoursePage 精简得到
const CreateLiveCourseDialog = forwardRef(function Component(props, ref) {
  const { code, onRequestClose, readOnly: readOnly } = props.props;
  const [form] = useForm();
  const [isEditMode, setIsEditMode] = useState(); // 是否为编辑模式
  const [initialValues, setInitialValues] = useState(null); // 设置表单的编辑初始化
  const [isShowAssistantParticipants, setShowAssistantParticipants] =
    useState(false); // 是否展示助教和参会者
  const [fileList, setFileList] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const [assistantsListData, setAssistantsListData] = useState(); // 助教列表
  const [expertsListData, setExpertsListData] = useState(); // 参会者列表
  // 正在查询助教列表
  const [isSearchingAssistants, setIsSearchingAssistants] = useState(false);
  // 正在查询参会者列表
  const [isSearchingExperts, setIsSearchingExperts] = useState(false);
  const { t, i18n } = useTranslation();
  const { TextArea } = Input;

  // useImperativeHandle 可以自定义暴露给父组件的方法
  // 与 forwardRef 一起使用
  useImperativeHandle(ref, () => ({
    submit() {
      form.submit();
    },
  }));

  const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const disabledDate = (current) => {
    return current && current < dayjs().startOf('day');
  };

  const range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  const disabledTime = (cur) => {
    const hour = moment().format('HH');
    const min = moment().format('mm');
    const ss = moment().format('ss');
    if (cur) {
      //如果选择时间为当前时间
      if (
        cur.format('YYYY-MM-DD').valueOf() ===
        moment().format('YYYY-MM-DD').valueOf()
      ) {
        //如果选择小时位为当前时间小时位
        if (cur.format('HH').valueOf() === moment().format('HH').valueOf()) {
          //如果选择分钟位为当前时间分钟位
          if (cur.format('mm').valueOf() === moment().format('mm').valueOf()) {
            //则当前时间之前的 小时位、分钟位、秒位都不能选择
            return {
              disabledHours: () => range(0, 24).splice(0, Number(hour)),
              disabledMinutes: () => range(0, 60).splice(0, Number(min)),
              disabledSeconds: () => range(0, 60).splice(0, Number(ss)),
            };
          }
          //否则当前时间的小时位、分钟都不能选择、秒位可以任意选择
          return {
            disabledHours: () => range(0, 24).splice(0, Number(hour)),
            disabledMinutes: () => range(0, 60).splice(0, Number(min)),
          };
        }
        //否则当前时间之前的小时位不能选择、分钟位、秒位都可以任意选择
        return {
          disabledHours: () => range(0, 24).splice(0, Number(hour)),
        };
      }
      //否则小时、分钟、秒位都不禁用
      return {
        disabledHours: () => [],
        disabledMinutes: () => [],
        disabledSeconds: () => [],
      };
    }
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    };
  };

  /// 切换是否小班化
  // const changeIsSmallClass = (isSmallClass) => {
  //   if (isSmallClass.target.value) {
  //     setShowAssistantParticipants(true);
  //   } else {
  //     setShowAssistantParticipants(false);
  //   }
  // };

  const validateMessages = {
    required: t('${label}是必填项'),
    types: {
      email: '${label} is not a valid email!',
      number: '${label} is not a valid number!',
    },
    number: {
      range: '${label} must be between ${min} and ${max}',
    },
  };

  const getBase64 = (file) =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });

  const handleCancel = () => setPreviewOpen(false);
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    );
  };
  const handleChange = async (info) => {
    setLoading(false);
    if (info.fileList.length < 1) {
      setFileList([]);
    }
  };
  const beforeUpload = async (file) => {
    setLoading(true);
    if (isImage(file)) {
      const url = await coursesAPI.upload(file);
      setImageUrl(url);
      const newFileList = [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: url,
        },
      ];
      setFileList(newFileList);
    } else {
      message.error(t('请选择jpg、jpeg、png的图片上传'));
    }
    return false;
  };
  function isImage(file) {
    return (
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg'
    );
  }
  const onFinish = async (values) => {
    values.course.CourseType = 1; // 默认直播课
    values.course.AudienceType = 1; // 默认公开课
    values.course.Cover = imageUrl;
    if (!Array.isArray(values.course.Assistants) && values.course.Assistants) {
      values.course.Assistants = [values.course.Assistants];
    }

    if (
      !Array.isArray(values.course.CourseVideoCodes) &&
      values.course.CourseVideoCodes
    ) {
      values.course.CourseVideoCodes = [values.course.CourseVideoCodes];
    }
    let result;
    if (typeof code === 'string') {
      values.course.Code = code;
      result = await coursesAPI.updateCourseAsyncAsync(values.course);
      if (result.result) {
        onRequestClose();
      } else {
        message.error(toolbar(t('编辑失败')));
      }
    } else {
      result = await coursesAPI.createCourseAsync(values.course);
      if (result.result) {
        onRequestClose();
      } else {
        message.error(t('创建失败'));
      }
    }
  };
  const validateAssistants = ({ getFieldValue }) => ({
    /// 校验助教是否是参会者
    validator(_, value) {
      if (getFieldValue(['course', 'Experts']) === undefined) {
        return Promise.resolve();
      }
      if (getFieldValue(['course', 'Experts']).includes(value)) {
        return Promise.reject(new Error(t('助教不能是参会者')));
      }
      return Promise.resolve();
    },
  });

  // const validateExperts = ({ getFieldValue }) => ({
  //   /// 校验参会者最多四人
  //   validator(_, value) {
  //     if (value.length > 4) {
  //       return Promise.reject(new Error(t('参会者最多四人')));
  //     }
  //     return Promise.resolve();
  //   },
  // });

  // const changeExperts = async (value) => {
  //   try {
  //     await form.validateFields([['course', 'Assistants']]);
  //   } catch (e) {
  //     console.log(e);
  //   }
  // };

  const changeAssistants = async (value) => {
    handleSearchAssistants('');
  };

  const handleSearchAssistants = (newValue) => {
    debouncedFetchAssistants(newValue, setAssistantsListData);
  };

  // const handleSearchAttendees = (newValue) => {
  //   debouncedFetchExperts(newValue, setExpertsListData);
  // };

  let assistantsSearchTimer;
  let expertsSearchTimer;
  let currentAssistantsValue;
  let currentExpertsValue;

  // 获取助教列表
  const debouncedFetchAssistants = (value, callback) => {
    if (assistantsSearchTimer) {
      clearTimeout(assistantsSearchTimer);
      assistantsSearchTimer = null;
    }
    currentAssistantsValue = value;
    const fetchData = async () => {
      setIsSearchingAssistants(true);
      const result = await findMyOrganizationExpertsList(
        currentAssistantsValue,
      );
      setIsSearchingAssistants(false);
      callback(result);
    };
    if (value || value === '') {
      assistantsSearchTimer = setTimeout(() => fetchData(), 300);
    } else {
      callback([]);
    }
  };

  // 获取参会者列表
  // const debouncedFetchExperts = (value, callback) => {
  //   if (expertsSearchTimer) {
  //     clearTimeout(expertsSearchTimer);
  //     expertsSearchTimer = null;
  //   }
  //   currentExpertsValue = value;
  //   const fetchData = async () => {
  //     setIsSearchingExperts(true);
  //     const result = await findMyOrganizationExpertsList(currentExpertsValue);
  //     setIsSearchingExperts(false);
  //     callback(result);
  //   };
  //   if (value || value === '') {
  //     expertsSearchTimer = setTimeout(fetchData, 300);
  //   } else {
  //     callback([]);
  //   }
  // };

  /// 获取助教者
  const findMyOrganizationExpertsList = async (keyWord) => {
    let assistantsList = [];
    const result = await coursesAPI.getAllStudentsAsync(keyWord, []);
    for (let i of result.result.PageData) {
      assistantsList.push({
        value: i.UserCode,
        label: i.DisplayName,
      });
    }
    return assistantsList;
  };

  /// 初始化编辑模式下的助教下拉列表
  const initAssistantsListData = (AssistantsList) => {
    let assistantsList = [];
    for (let i of AssistantsList) {
      assistantsList.push({
        value: i.Code,
        label: i.Name,
      });
      setAssistantsListData(assistantsList);
    }
  };

  /// 初始化编辑模式下的专家下拉列表
  // const initExpertsListData = (ExpertsList) => {
  //   let expertsList = [];
  //   for (let i of ExpertsList) {
  //     expertsList.push({
  //       value: i.Code,
  //       label: i.Name,
  //     });
  //     setExpertsListData(expertsList);
  //   }
  // };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}>
        {t('上传封面图')}
      </div>
    </div>
  );

  useEffect(() => {
    setIsEditMode(typeof code === 'string');
    if (typeof code === 'string') {
      /// 编辑模式
      initCourseDetailData(code);
    } else {
      initCourseDetailDataOnCreate();
    }
    handleSearchAssistants('');

    // handleSearchAttendees('');
    // 用作声明周期[onInit]
    // Tip: dev 环境会执行两次，prod 环境只会执行一次。为正常现象
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function initCourseDetailDataOnCreate() {
    setInitialValues(null);

    /// 新建模式
    const tomorrow = moment().add(24, 'hours').local();

    const formattedTime = tomorrow.format('YYYY-MM-DD HH:mm:ss');

    let data = {
      Name: '',
      StartTime: dayjs(formattedTime, 'YYYY-MM-DD HH:mm:ss'),
      CourseIntro: '',
      Assistants: [],
      IsSmallClass: false,
      Experts: [],
      Cover: '',
    };
    setInitialValues({
      course: data,
    });
  }

  /// 初始化课程详情 [用于修改课程信息时预填数据]
  async function initCourseDetailData(code) {
    let data = await coursesAPI.fetchCourseDetail(code, 'course');
    // console.log('%c Line:163 🍻 data', 'color:#ea7e5c', data);
    setInitialValues(null);
    try {
      const dateObj = moment(data.StartTime).local();
      const formattedTime = dateObj.format('YYYY-MM-DD HH:mm:ss');
      data.StartTime = dayjs(formattedTime, 'YYYY-MM-DD HH:mm:ss');
      if (data.IsSmallClass) {
        setShowAssistantParticipants(true);
      }
      /// 初始化封面
      if (data.Cover) {
        setFileList([{ url: data.Cover }]);
        setImageUrl(data.Cover);
      }
      /// 初始化助教
      if (data.Assistants.length !== 0) {
        initAssistantsListData(data.Assistants);
        data.Assistants = [data.Assistants[0].Code];
      }
      /// 初始化参会者
      // if (data.Experts.length !== 0) {
      //   initExpertsListData(data.Experts);
      //   let codeList = [];
      //   for (let i of data.Experts) {
      //     codeList.push(i.Code);
      //   }
      //   data.Experts = codeList;
      // }
    } catch (err) {
      console.log('%c Line:259 👾 err', 'color:#ed9ec7', err);
    }
    setInitialValues({
      course: data,
    });
  }

  return initialValues ? (
    <div>
      <div className='h-10' />
      <Form
        {...layout}
        form={form}
        labelAlign='left'
        name='nest-messages'
        onFinish={onFinish}
        initialValues={initialValues}
        validateMessages={validateMessages}>
        <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
          <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'Name']}
              label={t('名称')}
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                },
                {
                  pattern: /^(?!\s*$).+/,
                  message: t('名称不能只包含空格'),
                },
              ]}>
              <Input
                placeholder={t('请输入名称')}
                maxLength={40}
                readOnly={readOnly}
              />
            </Form.Item>
          </Col>
          <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'StartTime']}
              label={t('开始时间')}
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                },
              ]}>
              <DatePicker
                locale={locale}
                placeholder={t('请选择')}
                disabledDate={disabledDate}
                disabledTime={disabledTime}
                allowClear={false}
                format='YYYY-MM-DD HH:mm'
                style={{ width: '100%' }}
                suffixIcon={null}
                // initialValues={moment().add(24, 'hours').local()}
                showTime={
                  {
                    // defaultValue: dayjs("00:00:00", "HH:mm:ss"),
                  }
                }
                disabled={readOnly}
              />
            </Form.Item>
          </Col>
          <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'CourseIntro']}
              label={t('课程描述')}
              labelCol={{ span: 4 }}
              rules={[{}]}>
              <TextArea
                rows={4}
                placeholder={readOnly ? t('无') : t('请输入描述')}
                maxLength={100}
                readOnly={readOnly}
              />
            </Form.Item>
          </Col>
          <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'Assistants']}
              label={t('助教')}
              labelCol={{ span: 4 }}
              rules={[validateAssistants]}>
              <Select
                mode='multiple'
                allowClear={false}
                filterOption={false}
                options={assistantsListData}
                onSearch={handleSearchAssistants}
                onChange={changeAssistants}
                maxCount={1}
                placeholder={readOnly ? t('无') : t('请选择')}
                dropdownRender={(menu) => {
                  return isSearchingAssistants ? (
                    <div className='flex items-center justify-center h-20'>
                      <LoadingOutlined />
                    </div>
                  ) : (
                    menu
                  );
                }}
                disabled={readOnly}
              />
            </Form.Item>
          </Col>
          {/* <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'IsSmallClass']}
              label={t('是否小班化')}
              labelCol={{ span: 4 }}>
              <Radio.Group onChange={changeIsSmallClass} defaultValue={false}>
                <Radio value={true}> {t('是')} </Radio>
                <Radio value={false}> {t('否')} </Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          {isShowAssistantParticipants && (
            <Col className='gutter-row' span={24}>
              <Form.Item
                name={['course', 'Experts']}
                label={t('参会者')}
                labelCol={{ span: 4 }}
                rules={[validateExperts]}>
                <Select
                  mode='multiple'
                  allowClear={false}
                  filterOption={false}
                  options={expertsListData}
                  onSearch={handleSearchAttendees}
                  onChange={changeExperts}
                  maxCount={4}
                  placeholder={t('请选择')}
                  dropdownRender={(menu) => {
                    return isSearchingExperts ? (
                      <div className='flex items-center justify-center h-20'>
                        <LoadingOutlined />
                      </div>
                    ) : (
                      menu
                    );
                  }}
                />
              </Form.Item>
            </Col>
          )} */}
          <Col className='gutter-row' span={24}>
            <Form.Item
              name={['course', 'Cover']}
              label={t('封面')}
              style={{ height: '102px' }}
              labelCol={{ span: 4 }}>
              <ImgCrop
                aspect={16 / 9}
                quality={1}
                maxZoom={1}
                zoomSlider={false}>
                <Upload
                  disabled={readOnly}
                  listType='picture-card'
                  fileList={fileList}
                  accept='image/jpeg,image/png,image/jpg'
                  beforeUpload={beforeUpload}
                  onPreview={handlePreview}
                  onChange={handleChange}>
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              </ImgCrop>
            </Form.Item>
          </Col>
        </Row>
        <Modal
          open={previewOpen}
          title={previewTitle}
          footer={null}
          onCancel={handleCancel}>
          <img alt='example' style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Form>
    </div>
  ) : (
    <center>
      <div className='h-[9rem]'></div>
      <LoadingOutlined />
      <div className='h-3'></div>
      {t('加载中')}
      <div className='h-[9rem]'></div>
    </center>
  );
});

export default CreateLiveCourseDialog;
