/*
 * @Author: yuananting
 * @Date: 2021-07-29 14:32:24
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-17 14:50:30
 * @Description: 任务中心-培训任务-新建-基本信息
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useEffect, useState } from 'react';
import { Form, Button, Input, Space, DatePicker, Radio, Tag, message, Tooltip } from 'antd';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Upload from '@/core/upload';
import GraphicsEditor from '@/modules/course-manage/components/GraphicsEditor';
import ImgClipModal from '@/components/ImgClipModal';
import moment from 'moment';
import './BasicInfo.less';
import ChooseAssignorModal from '../modal/ChooseAssignorModal';
import ChooseCollaboratorModal from '../modal/ChooseCollaboratorModal';
import WWOpenDataCom from '@/components/WWOpenDataCom';

const { RangePicker } = DatePicker;

const FormItem = Form.Item;

function BasicInfo(props) {
  const taskState = getParameterByName('taskState');
  const type = getParameterByName('type');
  const originTimeType = getParameterByName('timeType');

  const { basicInfo, startCheck } = props;
  const { createId, taskName, coverUrl, helpStoreUserIds, timeType, startTime, endTime, learnType, assignList, introduce, loadintroduce } = basicInfo;
  const depAssignList = assignList.filter((item) => item.checkedType !== 'CUSTOMER');
  const userAssignList = assignList.filter((item) => item.checkedType === 'CUSTOMER');
  const [imageFile, setImageFile] = useState(null); // 需要被截取的图片
  const [showSelectFileModal, setShowSelectFileModal] = useState(false);
  const [imgClipVisible, setImgClipVisible] = useState(false);
  // 当前是否使用的是默认图片
  const defaultCover = 'https://image.xiaomaiketang.com/xm/rEAetaTEh3.png';
  const isDefaultCover = coverUrl === defaultCover;

  const [assignorModalVisible, setAssignorModalVisible] = useState(false); // 指派学员弹窗显隐
  const [collaboratorModalVisible, setCollaboratorModalVisible] = useState(false); // 协同者弹窗显隐

  // 使用默认封面图
  function handleResetCoverUrl() {
    message.success('已替换为默认图');
    props.onChange('coverUrl', { fileUrl: defaultCover });
  }

  // 从云盘选择封面
  function handleSelectCover(file) {
    setImgClipVisible(true);
    setImageFile(file);
  }

  function getSignature(blob, fileName) {
    Upload.uploadBlobToOSS(blob, 'cover' + new Date().valueOf(), null, 'signInfo').then((signInfo) => {
      const { fileUrl, resourceId } = signInfo;
      setImgClipVisible(false);
      setShowSelectFileModal(false);
      props.onChange('coverUrl', { fileUrl, resourceId });
    });
  }

  // 禁选日期
  function disabledDate(current) {
    return current && current < moment().startOf('day');
  }

  // 禁选时间
  function disabledRangeTime(date, type) {
    if (moment(date).isSame(moment(), 'day')) {
      return {
        disabledHours: () => {
          const hours = [];
          for (let i = 0; i < moment().hour(); i++) {
            hours.push(i);
          }
          return hours;
        },
        disabledMinutes: () => {
          const currentMinute = moment().minute();
          const currentHour = moment(date).hour();
          const minutes = [];
          if (currentHour === moment().hour()) {
            for (let i = 0; i < currentMinute; i++) {
              minutes.push(i);
            }
          }
          return minutes;
        },
      };
    }
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    };
  }

  function confirmAddCollaborator(data) {
    props.onChange('helpStoreUserIds', data);
  }

  function confirmAddAssignor(data) {
    props.onChange('assignList', data);
    setAssignorModalVisible(false);
  }

  function removeSelectedCollaborator(tag) {
    const _helpStoreUserIds = helpStoreUserIds.filter((item) => item.checkedId !== tag.checkedId);
    props.onChange('helpStoreUserIds', _helpStoreUserIds);
  }

  function removeCheckedAssignor(tag) {
    const _assignList = assignList.filter((item) => item.checkedId !== tag.checkedId);
    props.onChange('assignList', _assignList);
  }

  function checkTime() {
    if (!startTime && !endTime) {
      return '请选择培训时间';
    }
    if (!startTime) {
      return '请选择开始时间';
    }
    if (!endTime) {
      return '请选择结束时间';
    }
    if ((type === 'add' || taskState === 'UN_START') && startTime < new Date().getTime()) {
      return '开始时间不能早于现在';
    }
    if (!endTime > new Date().getTime()) {
      return '结束时间不能早于现在';
    }
    return false;
  }

  return (
    <div className='basic-info__form'>
      <Form>
        <FormItem
          label='培训任务名称'
          required
          validateStatus={startCheck && (!taskName || taskName.length > 20) ? 'error' : ''}
          help={startCheck && ((!taskName && '请输入培训任务名称') || (taskName.length > 20 && '任务名称最多20字'))}>
          <Input
            value={taskName}
            placeholder='请输入培训任务名称（20字以内）'
            maxLength={20}
            style={{ width: 300 }}
            onChange={(e) => props.onChange('taskName', e.target.value)}
          />
        </FormItem>
        <FormItem label='封面图'>
          <div className='cover__wrap'>
            <div className='opt-box'>
              <Button
                onClick={() => {
                  setShowSelectFileModal(true);
                }}>
                上传封面
              </Button>
              <span className={`default-btn ${isDefaultCover ? 'disabled' : ''}`} onClick={handleResetCoverUrl}>
                使用默认图
              </span>
              <div className='tips'>建议尺寸1280*720px或16:9。封面图最大5M，支持jpg、jpeg和png。</div>
            </div>
            <div className='img-box'>
              {isDefaultCover && <span className='default-tag'>默认图</span>}
              <img src={coverUrl} alt='' />
            </div>
          </div>
        </FormItem>
        <FormItem label='培训时间'>
          <div className='duration__wrap'>
            <Radio.Group
              value={timeType}
              disabled={originTimeType === 'VALIDITY' && taskState === 'STARTING'}
              onChange={(e) => {
                props.onChange('timeType', e.target.value);
              }}>
              <Space direction='vertical' size={16}>
                <Radio value='FOREVER'>
                  永久有效<span className='tips'>设置为“永久有效”，发布后任务开始生效，取消发布后失效</span>
                </Radio>
                <Radio value='VALIDITY'>
                  固定时间段
                  {timeType === 'VALIDITY' && (
                    <div className='picker-box'>
                      <FormItem validateStatus={startCheck && checkTime() ? 'error' : ''} help={startCheck && checkTime()}>
                        <RangePicker
                          style={{ width: 320 }}
                          showTime={{ defaultValue: [moment().add(10, 'minutes'), moment().add(10, 'minutes')] }}
                          ranges={{
                            近7天: [
                              type === 'edit' && taskState === 'STARTING' ? moment(startTime) : moment().add(10, 'minute'),
                              moment().add(6, 'day').endOf('day'),
                            ],
                            近1个月: [
                              type === 'edit' && taskState === 'STARTING' ? moment(startTime) : moment().add(10, 'minute'),
                              moment().add(1, 'month').endOf('day'),
                            ],
                            近3个月: [
                              type === 'edit' && taskState === 'STARTING' ? moment(startTime) : moment().add(10, 'minute'),
                              moment().add(3, 'month').endOf('day'),
                            ],
                          }}
                          disabledDate={disabledDate}
                          disabledTime={disabledRangeTime}
                          disabled={[type === 'edit' && taskState === 'STARTING', false]}
                          value={[startTime ? moment(Number(startTime)) : null, endTime ? moment(Number(endTime)) : null]}
                          format='YYYY-MM-DD HH:mm'
                          onChange={(date) => {
                            props.onChange('trainDate', date);
                          }}
                        />{' '}
                      </FormItem>
                    </div>
                  )}
                </Radio>
              </Space>
            </Radio.Group>
          </div>
        </FormItem>
        <FormItem label='学习模式' required extra={<div className='learning-model-tips'>提示：任务开始后学习模式将不允许更换</div>}>
          <div className='learning-model__wrap'>
            <Radio.Group value={learnType} disabled={taskState === 'STARTING'} onChange={(e) => props.onChange('learnType', e.target.value)}>
              <Space direction='vertical' size={16}>
                <Radio value='FREEDOM'>自由学习</Radio>
                <Radio value='ORDER'>
                  闯关学习
                  <Tooltip title='学员必须按顺序学习'>
                    <i
                      className='icon iconfont'
                      style={{
                        marginLeft: '5px',
                        cursor: 'pointer',
                        color: '#bfbfbf',
                        fontSize: '14px',
                        fontWeight: 'normal',
                      }}>
                      &#xe61d;
                    </i>
                  </Tooltip>
                </Radio>
              </Space>
            </Radio.Group>
          </div>
        </FormItem>
        <FormItem
          label={
            <span>
              指派学员
              <Tooltip title='选择需要培训的人员'>
                <i
                  className='icon iconfont'
                  style={{
                    marginLeft: '5px',
                    cursor: 'pointer',
                    color: '#bfbfbf',
                    fontSize: '14px',
                    fontWeight: 'normal',
                  }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          }
          required
          validateStatus={startCheck && assignList.length === 0 ? 'error' : ''}
          help={startCheck && assignList.length === 0 && '请选择指派学员'}>
          <Button
            style={{ display: 'block' }}
            onClick={() => {
              setAssignorModalVisible(true);
            }}>
            添加指派学员
          </Button>
          {assignList.length > 0 && (
            <Space size={'12'} direction={'vertical'} className='select-obj'>
              {depAssignList.length > 0 && (
                <div className='obj-type-container'>
                  <div className='type-title'>已选组织：</div>
                  <div className='tag-box'>
                    {_.map(depAssignList, (tag) => {
                      return (
                        <Tag
                          key={tag.checkedId}
                          closeIcon={<span className='icon iconfont close-icon'>&#xe626;</span>}
                          onClose={() => removeCheckedAssignor(tag)}
                          closable>
                          <WWOpenDataCom type='departmentName' openid={tag.checkedName} />
                        </Tag>
                      );
                    })}
                  </div>
                </div>
              )}
              {userAssignList.length > 0 && (
                <div className='obj-type-container'>
                  <div className='type-title'>已选学员：</div>
                  <div className='tag-box'>
                    {_.map(userAssignList, (tag) => {
                      return (
                        <Tag
                          key={tag.checkedId}
                          closeIcon={<span className='icon iconfont close-icon'>&#xe626;</span>}
                          onClose={() => removeCheckedAssignor(tag)}
                          closable>
                          <WWOpenDataCom type='userName' openid={tag.checkedName} />
                        </Tag>
                      );
                    })}
                  </div>
                </div>
              )}
            </Space>
          )}
        </FormItem>
        <FormItem
          label={
            <span>
              协同人员
              <Tooltip title='选择员工协同完成任务指派和督学工作'>
                <i
                  className='icon iconfont'
                  style={{
                    marginLeft: '5px',
                    cursor: 'pointer',
                    color: '#bfbfbf',
                    fontSize: '14px',
                    fontWeight: 'normal',
                  }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          }>
          <Button
            style={{ display: 'block' }}
            onClick={() => {
              setCollaboratorModalVisible(true);
            }}>
            添加协同者
          </Button>
          {helpStoreUserIds.length > 0 && (
            <div className='select-obj'>
              {_.map(helpStoreUserIds, (tag) => {
                return (
                  <Tag
                    key={tag.checkedId}
                    closeIcon={<span className='icon iconfont close-icon'>&#xe626;</span>}
                    className={tag.checkedId === createId && 'disabled'}
                    onClose={() => removeSelectedCollaborator(tag)}
                    closable>
                    <WWOpenDataCom type='userName' openid={tag.checkedName} />
                  </Tag>
                );
              })}
            </div>
          )}
        </FormItem>
        <FormItem label='培训目的'>
          {(type === 'add' || loadintroduce) && (
            <GraphicsEditor
              maxLimit={1000}
              id='intro'
              isIntro={true}
              placeholder='请输入培训目的'
              detail={{
                content: introduce,
              }}
              onChange={(val) => {
                props.onChange('introduce', val);
              }}
            />
          )}
        </FormItem>
      </Form>
      {showSelectFileModal && (
        <SelectPrepareFileModal
          key='basic'
          operateType='select'
          multiple={false}
          accept='image/jpeg,image/png,image/jpg'
          selectTypeList={['JPG', 'JPEG', 'PNG']}
          tooltip='支持文件类型：jpg、jpeg、png'
          isOpen={showSelectFileModal}
          onClose={() => {
            setShowSelectFileModal(false);
          }}
          onSelect={handleSelectCover}
        />
      )}
      {imgClipVisible && (
        <ImgClipModal
          visible={imgClipVisible}
          imgUrl={imageFile.ossUrl}
          onConfirm={getSignature}
          onClose={() => {
            setImgClipVisible(false);
          }}
        />
      )}
      {assignorModalVisible && (
        <ChooseAssignorModal
          currentAssignorList={assignList}
          visible={assignorModalVisible}
          onClose={() => {
            setAssignorModalVisible(false);
          }}
          onConfirm={(data) => {
            confirmAddAssignor(data);
          }}
        />
      )}
      {collaboratorModalVisible && (
        <ChooseCollaboratorModal
          createId={createId}
          currentCollaboratorList={helpStoreUserIds}
          visible={collaboratorModalVisible}
          onClose={() => {
            setCollaboratorModalVisible(false);
          }}
          onConfirm={(data) => {
            confirmAddCollaborator(data);
          }}
        />
      )}
    </div>
  );
}

export default BasicInfo;
