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

const { TextArea } = Input;

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

/* eslint-disable no-template-curly-in-string */
const validateMessages = {
  required: '${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}',
  },
};
/* eslint-enable no-template-curly-in-string */

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

function CreateCourse(param) {
  const { code, form, onRequestClose } = param;
  const [isEditMode, setIsEditMode] = useState(); // 是否为编辑模式
  const [courseListData, setCourseListData] = useState(); // 课程标签
  const [isShowClassManagement, setShowClassManagement] = useState(false); // 是否展示班级管理
  const [isShowAssistantParticipants, setShowAssistantParticipants] =
    useState(false); // 是否展示助教和参会者
  const [isShowDuration, setIsShowDuration] = useState(false); // 是否展示时长字段
  const [isShowSmallClass, setShowSmallClass] = useState(false); // 是否展示小班化 2、还有直播课程不需要课程源
  const [initialValues, setInitialValues] = useState(null); // 设置表单的编辑初始化
  const [classManagementListData, setClassManagementListData] = useState(); // 班级管理
  const [assistantsListData, setAssistantsListData] = useState(); // 助教列表
  const [expertsListData, setExpertsListData] = useState(); // 参会者列表
  const [courseAlbumListData, setCourseAlbumListData] = useState(); // 关联专辑
  const [videosPagesListData, setVideosPagesListData] = useState(); // 素材库管理
  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();
  let assistantsSearchTimer;
  let currentAssistantsValue;
  let expertsSearchTimer;
  let currentExpertsValue;
  /// 切换课程模式
  const changeAudienceType = (type) => {
    if (type === 2) {
      setShowClassManagement(true);
    } else {
      setShowClassManagement(false);
    }
  };
  /// 切换课程分类
  const changeCourseType = (type) => {
    if (type === 1) {
      setIsShowDuration(true);
      setShowSmallClass(true);
    } else {
      setIsShowDuration(false);
      setShowSmallClass(false);
    }
  };
  /// 切换是否小班化
  const changeIsSmallClass = (isSmallClass) => {
    if (isSmallClass.target.value) {
      setShowAssistantParticipants(true);
    } else {
      setShowAssistantParticipants(false);
    }
  };

  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 handleRemove = () => {};
  const handleChange = async (info) => {
    setLoading(false);
    if (isImage(info.file)) {
      setFileList(info.fileList);
    }
  };
  const beforeUpload = async (file) => {
    setLoading(true);
    if (isImage(file)) {
      const url = await coursesAPI.upload(file);
      setImageUrl(url);
    } else {
      message.error('请选择jpg、jpeg、png的图片上传');
    }
    return false;
  };
  function isImage(file) {
    return (
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg'
    );
  }
  const onChange = (value) => {
    console.log(`selected ${value}`);
  };
  const onSearch = (value) => {
    console.log('search:', value);
  };
  const onFinish = async (values) => {
    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('编辑失败');
      }
    } else {
      result = await coursesAPI.createCourseAsync(values.course);
      if (result.result) {
        onRequestClose();
      } else {
        message.error('创建失败');
      }
    }
  };

  const validatePrice = (_, value) => {
    if (value >= 0 && Number(value.toFixed(2)) === value) {
      return Promise.resolve();
    }

    return Promise.reject(new Error('价格不得小于0元，且最多小数点后两位'));
  };

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

  useEffect(() => {
    setIsEditMode(typeof code === 'string');
    if (typeof code === 'string') {
      initCourseDetailData(code);
    }
    getCourseLabelsAsyncData();
    getUserGroupListsByCreatorCode();
    findCourseAlbumList();
    findVideosPagesList();
    handleSearchAssistants('');
    handleSearchAttendees('');
  }, []);

  // 获取助教列表
  const debouncedFetchAssistants = (value, callback) => {
    if (assistantsSearchTimer) {
      clearTimeout(assistantsSearchTimer);
      assistantsSearchTimer = null;
    }
    currentAssistantsValue = value;
    const fetchData = async () => {
      const result = await findMyOrganizationExpertsList(
        currentAssistantsValue,
      );
      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 () => {
      const result = await findMyOrganizationExpertsList(currentExpertsValue);
      callback(result);
    };
    if (value || value === '') {
      expertsSearchTimer = setTimeout(fetchData, 300);
    } else {
      callback([]);
    }
  };

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

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

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

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

  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 getCourseLabelsAsyncData = async () => {
    let courseListResult = [];
    /// 课程标签
    const courseList = await coursesAPI.getCourseLabelsAsyncData(2);
    for (let i of courseList.result) {
      courseListResult.push({
        value: i.Code,
        label: i.Name,
      });
    }

    setCourseListData(courseListResult);
  };
  /// 获取班级列表
  const getUserGroupListsByCreatorCode = async () => {
    let classManagementList = [];

    const result = await coursesAPI.getUserGroupListsByCreatorCode();
    for (let i of result.result.PageData) {
      classManagementList.push({
        value: i.Code,
        label: i.Name,
      });
    }
    setClassManagementListData(classManagementList);
    return result;
  };
  /// 获取课程专辑列表
  const findCourseAlbumList = async () => {
    let courseAlbumList = [];

    const result = await coursesAPI.findCourseAlbumList();
    for (let i of result.result) {
      courseAlbumList.push({
        value: i.Code,
        label: i.Name,
      });
    }
    setCourseAlbumListData(courseAlbumList);
  };

  /// 初始化编辑模式下的助教下拉列表
  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);
    }
  };

  /// 初始化课程详情
  async function initCourseDetailData(code) {
    let data = await coursesAPI.fetchCourseDetail(code, 'course');
    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.CourseType === 1) {
        setShowSmallClass(true);
        setIsShowDuration(true);
      }
      if (data.IsSmallClass) {
        setShowAssistantParticipants(true);
      }

      if (data.Assistants.length !== 0) {
        initAssistantsListData(data.Assistants);
        handleSearchAssistants(data.Assistants[0].Name);
        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;
      }
      if (data.Cover) {
        setFileList([{ url: data.Cover }]);
        setImageUrl(data.Cover);
      }
    } catch (err) {
      console.log('%c Line:259 👾 err', 'color:#ed9ec7', err);
    }
    setInitialValues({
      course: data,
    });
  }

  /// 获取助教者
  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 findVideosPagesList = async () => {
    let videosPagesList = [];
    const result = await coursesAPI.findVideosPages();
    for (let i of result) {
      videosPagesList.push({
        value: i.Code,
        label: i.Name,
      });
    }
    setVideosPagesListData(videosPagesList);
  };
  return initialValues || !isEditMode ? (
    <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={12}>
          <Form.Item
            name={['course', 'Name']}
            label='名称'
            rules={[
              {
                required: true,
              },
              {
                pattern: /^\S+$/,
                message: '名称不能包含空格',
              },
            ]}>
            <Input placeholder='请输入名称' maxLength={40} />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={12}>
          <Form.Item
            name={['course', 'CourseType']}
            label='课程分类'
            rules={[
              {
                required: true,
              },
            ]}>
            <Select
              allowClear
              placeholder='请选择'
              options={[
                { value: 1, label: '直播课程' },
                { value: 2, label: '多媒体课程' },
              ]}
              onChange={changeCourseType}
            />
          </Form.Item>
        </Col>
        {isShowSmallClass && (
          <Col className='gutter-row' span={12}>
            <Form.Item name={['course', 'IsSmallClass']} label='是否小班化'>
              <Radio.Group onChange={changeIsSmallClass} defaultValue={false}>
                <Radio value={true}> 是 </Radio>
                <Radio value={false}> 否 </Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
        )}
        {isShowSmallClass && (
          <Col className='gutter-row' span={12}>
            <Form.Item
              name={['course', 'StartTime']}
              label='开始时间'
              rules={[
                {
                  required: true,
                },
              ]}>
              <DatePicker
                placeholder='请选择'
                locale={locale}
                disabledDate={disabledDate}
                disabledTime={disabledTime}
                format='YYYY-MM-DD HH:mm'
                style={{ width: '100%' }}
                showTime={
                  {
                    // defaultValue: dayjs("00:00:00", "HH:mm:ss"),
                  }
                }
              />
            </Form.Item>
          </Col>
        )}
        {isShowDuration && (
          <Col className='gutter-row' span={12}>
            <Form.Item
              name={['course', 'Duration']}
              label='时长（分钟）'
              initialValue={120}>
              <InputNumber
                min={1}
                max={100000}
                defaultValue={120}
                onChange={onChange}
                style={{
                  width: '100%',
                }}
              />
            </Form.Item>
          </Col>
        )}
        <Col className='gutter-row' span={12}>
          <Form.Item name={['course', 'CourseLabelCodes']} label='课程标签'>
            <Select
              allowClear
              mode='multiple'
              placeholder='请选择'
              options={courseListData}
              filterOption={(input, option) =>
                (option?.label ?? '')
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={12}>
          <Form.Item
            name={['course', 'AudienceType']}
            label='课程规模'
            rules={[
              {
                required: true,
              },
            ]}>
            <Select
              allowClear
              placeholder='请选择'
              options={[
                { value: 1, label: '公开课' },
                { value: 2, label: '私有课' },
              ]}
              onChange={changeAudienceType}
            />
          </Form.Item>
        </Col>
        {isShowClassManagement && (
          <Col className='gutter-row' span={12}>
            <Form.Item name={['course', 'UserGroupCodes']} label='班级管理'>
              <Select
                allowClear
                mode='multiple'
                options={classManagementListData}
                placeholder='请选择'
              />
            </Form.Item>
          </Col>
        )}
        {isShowAssistantParticipants && (
          <Col className='gutter-row' span={12}>
            <Form.Item name={['course', 'Assistants']} label='助教'>
              <Select
                allowClear
                showSearch={true}
                filterOption={false}
                options={assistantsListData}
                onSearch={handleSearchAssistants}
                placeholder='请选择'
              />
            </Form.Item>
          </Col>
        )}{' '}
        {isShowAssistantParticipants && (
          <Col className='gutter-row' span={12}>
            <Form.Item name={['course', 'Experts']} label='参会者'>
              <Select
                allowClear
                mode='multiple'
                filterOption={false}
                options={expertsListData}
                onSearch={handleSearchAttendees}
                placeholder='请选择'
              />
            </Form.Item>
          </Col>
        )}
        <Col className='gutter-row' span={12}>
          <Form.Item
            name={['course', 'Price']}
            label='课程价格（元）'
            rules={[
              {
                validator: validatePrice,
              },
            ]}
            initialValue={0.0}>
            <InputNumber
              min={0.0}
              max={100000}
              defaultValue={0.0}
              onChange={onChange} // 使用 this.onChange，如果你的组件是类的形式。否则只需使用 “onChange”
              step='0.01'
              style={{
                width: '100%',
              }}
              // formatter={(value) => parseFloat(value).toFixed(2)}
              parser={(value) => parseFloat(value)}
            />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={12}>
          <Form.Item name={['course', 'CourseAlbumCodes']} label='关联专辑'>
            <Select
              showSearch
              mode='multiple'
              placeholder='请选择'
              optionFilterProp='children'
              filterOption={(input, option) =>
                (option?.label ?? '').includes(input)
              }
              filterSort={(optionA, optionB) =>
                (optionA?.label ?? '')
                  .toLowerCase()
                  .localeCompare((optionB?.label ?? '').toLowerCase())
              }
              options={courseAlbumListData}
            />
          </Form.Item>
        </Col>
        {!isShowSmallClass && (
          <Col className='gutter-row' span={12}>
            <Form.Item
              name={['course', 'CourseVideoCodes']}
              label='课程源'
              rules={[
                {
                  required: true,
                },
              ]}>
              <Select
                showSearch
                placeholder='请选择'
                optionFilterProp='children'
                onChange={onChange}
                onSearch={onSearch}
                filterOption={(input, option) =>
                  (option?.label ?? '')
                    .toLowerCase()
                    .includes(input.toLowerCase())
                }
                options={videosPagesListData}
              />
            </Form.Item>
          </Col>
        )}
        <Col className='gutter-row' span={12}>
          <Form.Item name={['course', 'CourseMaterialCodes']} label='资料'>
            <Select
              showSearch
              placeholder='请选择'
              mode='multiple'
              optionFilterProp='children'
              onChange={onChange}
              onSearch={onSearch}
              filterOption={(input, option) =>
                (option?.label ?? '')
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              options={videosPagesListData}
            />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={24}>
          <Form.Item
            name={['course', 'CourseIntro']}
            label='课程描述'
            labelCol={{ span: 4 }}
            rules={[{}]}>
            <TextArea rows={4} placeholder='请输入' maxLength={100} />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={24}>
          <Form.Item
            name={['course', 'Cover']}
            label='封面'
            style={{ height: '102px' }}
            labelCol={{ span: 4 }}>
            <ImgCrop aspect={16 / 9} quality={1}>
              <Upload
                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>{'loadding...'}</div>
  );
}

export default CreateCourse;
