/*
 * @Author: yuananting
 * @Date: 2021-07-29 14:32:24
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-09 17:46:08
 * @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 { basicInfo, startCheck } = props;
  const { taskName, coverUrl, helpStoreUserIds, timeType, startTime, endTime, learnType, assignList, introduce } = basicInfo;
  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) {
    const helpStoreUserIds = data.map((item) => item.userId);
    props.onChange('helpStoreUserIds', helpStoreUserIds);
  }

  function removeSelectedCollaborator(tag, index) {
    const _helpStoreUserIds = helpStoreUserIds.filter((item) => item !== tag);
    props.onChange('helpStoreUserIds', _helpStoreUserIds);
  }
  function test(data) {
    console.log(data);
    props.onChange('introduce', data);
    // props.onChange('introduce', data);
  }

  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}
              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 && !startTime && !endTime ? 'error' : ''}
                        help={startCheck && !startTime && !endTime && '请选择培训时间'}>
                        <RangePicker
                          style={{ width: 320 }}
                          showTime={{ defaultValue: [moment().add(10, 'minutes'), moment().add(10, 'minutes')] }}
                          ranges={{
                            近7天: [moment().add(10, 'minute'), moment().add(6, 'day').endOf('day')],
                            近1个月: [moment().add(10, 'minute'), moment().add(1, 'month').endOf('day')],
                            近3个月: [moment().add(10, 'minute'), moment().add(3, 'month').endOf('day')],
                          }}
                          disabledDate={disabledDate}
                          disabledTime={disabledRangeTime}
                          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} onChange={(e) => props.onChange('learnType', e.target.value)}>
              <Space direction='vertical' size={16}>
                <Radio value='FREEDOM'>自由学习</Radio>
                <Radio value='BREAKTHROUGH_LEARNING'>
                  闯关学习
                  <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>
          <Button
            style={{ display: 'block' }}
            onClick={() => {
              setAssignorModalVisible(true);
            }}>
            添加指派对象
          </Button>
          {assignList > 0 && (
            <Space size={'12'} direction={'vertical'} className='select-obj'>
              {assignList.length > 0 && (
                <div className='obj-type-container'>
                  <div className='type-title'>已选组织：</div>
                  <div className='tag-box'>
                    {_.map(assignList, (item) => {
                      return <Tag closable>{item.name}</Tag>;
                    })}
                  </div>
                </div>
              )}
              {assignList.length > 0 && (
                <div className='obj-type-container'>
                  <div className='type-title'>已选学员：</div>
                  <div className='tag-box'>
                    {_.map(assignList, (item) => {
                      return <Tag closable>{item.name}</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, index) => {
                return (
                  <Tag key={tag.id} onClose={() => removeSelectedCollaborator(tag, index)} closable>
                    <WWOpenDataCom type='userName' openid={tag.nickName} />
                  </Tag>
                );
              })}
            </div>
          )}
        </FormItem>
        <FormItem label='培训目的'>
          <GraphicsEditor
            maxLimit={1000}
            id='intro'
            isIntro={true}
            placeholder='请输入培训目的'
            detail={{
              content: introduce,
            }}
            onChange={(val, length) => {
              test(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
          visible={assignorModalVisible}
          type='CUSTOMER'
          treeDepType={'DEP_CHAT'}
          close={() => {
            // closeChooseMembersModal();
          }}
          onConfirm={() => {
            // confirmAddCustomer();
          }}
        />
      )}
      {collaboratorModalVisible && (
        <ChooseCollaboratorModal
          currentCollaboratorList={helpStoreUserIds}
          visible={collaboratorModalVisible}
          onClose={() => {
            setCollaboratorModalVisible(false);
          }}
          onConfirm={(data) => {
            confirmAddCollaborator(data);
          }}
        />
      )}
    </div>
  );
}

export default BasicInfo;
