import React, { useRef, useState, useEffect } from 'react';
import { Form, Radio, Input, Select } from 'antd';
import './index.less';

import Modal from '../../themeComponents/Modal';
import LabelValue from '../../components/LabelValue';
import ImageView from '../../components/ImageView';
import Player from '../Player';
import CaptureCard from '../CaptureCard';
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
/**
 * @desc 审批与下载，确认的弹窗组件
 * @param {Object} data 申请记录的详细信息
 * @param {Object} dataArray 组装显示的详细信息
 * （imageDetails=[] 图片/fileData={} 视频，downloadContent=[]
 * 下载内容，applyPersonInfo=[] 申请人信息， candidateReviewers=[] 审批人多个）
 * @param {bool} visible 弹窗开关
 * @param {String} title 弹窗标题
 * @param {Function} agreeAndRefuse 同意or拒绝下载申请的事件
 * @param {Function} toSubmit 提交下载申请
 * @param {Function} toCancel 取消下载申请
 * @param {Function} showPicDetail 查看图片详细
 * @param {bool} isCheck 是否审批模式
 * @param {bool} isApply 是否申请模式
 * @param {bool} isEdit 是否编辑模式
 * @param {bool} isOnceAgain 是否再次提交
 * @param {bool} isShowCheckPerson 是否显示审批人信息
 *
 */
const DownloadModal = ({ data = {},
  dataArray = {},
  visible,
  title = '下载申请',
  agreeAndRefuse,
  toSubmit,
  toCancel,
  showPicDetail,
  isCheck = false,
  isApply = false,
  isEdit = false,
  isOnceAgain = false,
  isShowCheckPerson = false,
  form,
  isBatchDownload = false,
  containerDom,
  ...props }) => {
  const formRef = useRef()
  const [downType, setDownType] = useState()
  const getFooterProps = () => {
    let footerProps = { hasFooter: false };
    if (isCheck && isEdit) {
      footerProps = {
        hasFooter: true,
        okText: '同意',
        onOk: () => agreeAndRefuse(formRef.current.getFieldsValue(), 1),
        cancelText: '拒绝',
        onFootCancel: () => agreeAndRefuse(formRef.current.getFieldsValue(), 0),
      };
    }
    if (isApply) {
      footerProps = {
        hasFooter: true,
        cancelText: '取消',
        okText: isOnceAgain ? '再次提交' : '提交',
        onOk: () => toSubmit(formRef.current.getFieldsValue()),
        onCancel: toCancel,
      };
    }
    return footerProps;
  };


  const downTypeChange = (value) => {
    setDownType(value)
    if (value === 'offline') {
      formRef.current.setFieldsValue({ downloadFormat: '2' })
    }
  }

  useEffect(() => {
    setDownType()
  }, [visible])

  let { imageDetails = [], fileData = {}, downloadContent = [], applyPersonInfo = [], candidateReviewers = [] } = dataArray;
  const footerProps = getFooterProps();
  return (
    <Modal title={title} destroyOnClose onOk={toCancel} onCancel={toCancel} visible={visible} width="480px" className="check-detail-modal-box" {...footerProps} {...props} zIndex={1001}>
      <Form ref={formRef} className="check-content">
        {!isBatchDownload && (
          <div className="img-video-box">
            {imageDetails.length > 0 ? (
              imageDetails.length === 1 ? (
                imageDetails.map((v) => (
                  <div className="img-item-one">
                    <ImageView src={v.url} />
                  </div>
                ))
              ) : (
                imageDetails.map((v) => <CaptureCard key={v.id} imgUrl={v.url} deviceName={v.deviceName} captureTime={v.startTime} relativeIcon={false} className="img-item-more" checkboxItem={false} onClick={() => showPicDetail && showPicDetail(v)} />)
              )
            ) : (
              <Player isFrontEnd={+fileData.videoType === 1} startTime={fileData.startTime} endTime={fileData.endTime} title={fileData.deviceName} cid={fileData.cid} key={fileData.cid} isLive={false} historyList={fileData.historyList} hasHistory={false} />
            )}
          </div>
        )}

        {!!downloadContent.length && (
          <ItemBox title="下载内容">
            {downloadContent.map((item, index) => (
              <LabelValue key={index} className={item.label !== '设备名称' ? 'item' : 'item deviceItem'} label={item.label} value={item.value || ''} />
            ))}
          </ItemBox>
        )}
        <ItemBox
          title="选择下载方式"
          isFormItem
          getFieldDecorator={{
            name: 'downType',
            rules: [{ required: true, message: '请选择下载方式' }],
            initialValue: (data.downType && String(data.downType)) || 'online',
          }}
        >
          <Select onChange={downTypeChange} className="select-download-format" dropdownClassName="select-filter-drop" style={{ width: 170, marginRight: '12px' }}>
            <Option value="online" key={'online'}>
              在线下载
            </Option>
            <Option value="offline" key={'offline'}>
              离线任务
            </Option>
          </Select>
        </ItemBox>

        {!!downloadContent.length && !imageDetails.length && fileData.videoType !== 1 && (
          <ItemBox
            title="选择下载格式"
            isFormItem
            getFieldDecorator={{
              name: 'downloadFormat',
              rules: [{ required: true, message: '是否选择视频格式' }],
              initialValue: (data.downloadFormat && String(data.downloadFormat)) || '2',
            }}
          >
            <Select disabled={downType === 'offline'} className="select-download-format" dropdownClassName="select-filter-drop" style={{ width: 170, marginRight: '12px' }}>
              <Option value="1" key={'ts'}>
                TS格式
              </Option>
              <Option value="2" key={'mp4'}>
                MP4格式
              </Option>
            </Select>
          </ItemBox>
        )}

        {!!applyPersonInfo.length && <ItemBox title="申请人信息">{applyPersonInfo && applyPersonInfo.map((item) => <LabelValue className="item" label={item.label} value={item.value || ''} />)}</ItemBox>}

        {isCheck && (
          <ItemBox title="下载原因">
            <LabelValue className="item" label={'下载原因'} value={data.applyReason || ''} />
          </ItemBox>
        )}

        {isCheck && data.resourceType === '121301' && (
          <ItemBox title="是否有水印">
            <LabelValue className="item" label={'水印'} value={data.hasMarker ? '有' : '无'} />
          </ItemBox>
        )}

        {isCheck && !isEdit && isShowCheckPerson && (
          <ItemBox title="审批人">
            <LabelValue className="item" label={'说明'} value={'以下人员均可审批此条申请'} />
            <div className="check-person" style={{ paddingLeft: '80px', fontSize: '12px' }}>
              {candidateReviewers.length > 0 ? candidateReviewers.map((v) => v.name).join('，') : ''}
            </div>
          </ItemBox>
        )}

        {isCheck && !isEdit && (
          <ItemBox title="审批备注">
            <LabelValue className="item" label={'审批备注'} value={data.reviewNotes || ''} />
          </ItemBox>
        )}

        {isCheck && isEdit && (
          <ItemBox title="审批备注" isFormItem getFieldDecorator={{ name: 'reviewNotes', initialValue: data.reviewNotes || '' }}>
            <TextArea style={{ minHeight: '64px', fontSize: '12px' }} maxLength={201} placeholder="请填写您的备注信息，最大长度不超过200" />
          </ItemBox>
        )}

        {isApply && (
          <React.Fragment>
            <ItemBox title="下载原因" className="reason" isFormItem getFieldDecorator={{ name: 'applyReason', initialValue: data.applyReason || '' }}>
              <TextArea style={{ minHeight: '64px', fontSize: '12px' }} maxLength={201} placeholder="请填写您的下载原因，最大长度不超过200" />
            </ItemBox>
            {imageDetails.length >= 1 && (
              <ItemBox
                title="水印"
                isFormItem
                getFieldDecorator={{
                  name: 'hasMarker',
                  rules: [{ required: true, message: '是否有水印必须选择' }],
                  initialValue: data.hasOwnProperty('hasMarker') ? (data.hasMarker ? 1 : 0) : 1,
                }}
              >
                <Radio.Group style={{ fontSize: '12px' }}>
                  <Radio value={1}>打水印</Radio>
                  <Radio value={0}>不打水印</Radio>
                </Radio.Group>
              </ItemBox>
            )}
          </React.Fragment>
        )}
        <div
          className={`watermark
            ${data && data.reviewStatus === 1 ? 'agree' : ''}
            ${data && data.reviewStatus === 0 ? 'refuse' : ''}
          `}
        ></div>
      </Form>
    </Modal>
  );
}

const ItemBox = ({ title, className = '', isFormItem = false, getFieldDecorator, children }) => {
  return (
    <React.Fragment>
      <h2>{title}：</h2>
      {isFormItem ? (
        <FormItem label={title} className={`form-detail-desc ${className}`} {...getFieldDecorator}>
          {children}
        </FormItem>
      ) : (
        children
      )}
    </React.Fragment>
  );
};
export default DownloadModal;
