import React, { FC, useState, useEffect, useImperativeHandle } from 'react';
import styles from './index.less';
import deleteIcon from './assets/deleteIcon.png';
import { Toast, Modal, Picker, List, DatePicker } from 'antd-mobile-v2';
import classnames from 'classnames';

import { CardDiv } from '../index';
import copyIcon from './assets/copy.png';
import moment from 'moment';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

interface PageProps {
  isEdit?: boolean;
  oppId?: string;
  dispatch: any;
  optionObjs?: any;
  cRef?: any;
  title?: string;
  propsFileList?: any[];
  hidden?: boolean;
  currentBlockInfo?: any;
  modalName?: any;
  saveKey?: any;
}

const Enclosure: FC<PageProps> = ({
  isEdit = false,
  oppId,
  dispatch,
  optionObjs = {},
  cRef,
  title = '商机附件',
  propsFileList = [],
  hidden = false,
  currentBlockInfo = {},
  modalName = '',
  saveKey = '',
}) => {
  //   const { oppType } = formsValues;
  let fileTypeOptions = [] as any[];
  const { tableProps = {} } = currentBlockInfo;
  tableProps?.columns?.map((item: any) => {
    if (item.dataIndex === 'SaleOppFileUpload_fileType') {
      fileTypeOptions = item.dataSource;
    }
  });
  console.log('currentBlockInfo', currentBlockInfo);
  const isTypeUpload = !!fileTypeOptions.length;
  const [fileList, setFileList] = useState(propsFileList as any[]);
  const [showModal, setShowModal] = useState(false);
  const [fileTypeValue, setFileTypeValue] = useState(undefined as any);
  const [signTime, setSignTime] = useState(undefined as any);
  const [isChooseFile, setIsChooseFile] = useState(true);
  const rightView = () =>
    isTypeUpload ? (
      <div
        className={styles.rightView}
        onClick={() => {
          setShowModal(true);
        }}
      >
        上传附件
      </div>
    ) : (
      <div
        className={classnames({
          [styles.footerViewTop]: true,
          [styles.rightView]: true,
        })}
      >
        上传附件
        <input
          className={styles.footerInput}
          id="uploadEnclosure"
          name="file"
          accept="/*"
          type="file"
          onChange={uploadImg}
        />
      </div>
    );

  useEffect(() => {
    if (!!propsFileList && !!propsFileList.length) {
      setFileList(propsFileList);
    }
  }, [propsFileList]);

  const saveFileList = (list: any[]) => {
    if (modalName && saveKey) {
      dispatch!({
        type: `${modalName}/disChangeFile`,
        payload: {
          eleCode: saveKey,
          dataList: list,
        },
      });
    }
  };

  useImperativeHandle(
    cRef,
    () => ({
      getFileList: () => {
        return fileList;
      },
    }),
    [fileList],
  );
  if (hidden) return <></>;
  const uploadImg = (e: any) => {
    console.log('onUploadFile', e);
    const files = e.target.files;
    console.log('files', files);
    if (files && files.length > 0) {
      const reader = new FileReader();
      reader.readAsDataURL(files[0]);
      reader.onload = async (e2) => {
        let imag = e2.target?.result as any;
        let mFile = files[0];
        const fileSize = mFile.size;
        const formData = new FormData();
        formData.append('file', mFile);
        dispatch!({
          type: 'businessManagement/uploadFile',
          payload: formData,
        }).then((res: any) => {
          console.log('res', res);
          setFileTypeValue(undefined);
          setShowModal(false);
          setSignTime(undefined);
          setIsChooseFile(true);
          const { isSuccess, data = [] } = res;

          if (isSuccess && data?.length > 0) {
            const mFileList: any[] = JSON.parse(JSON.stringify(fileList));
            if (isTypeUpload) {
              let filerItem = [] as any[];
              filerItem = fileTypeOptions.filter(
                (row: any) => row?.value === fileTypeValue[0],
              );
              const pushItem: any = {
                SaleOppFileUpload_file: [
                  {
                    ...data[0],
                  },
                ],
                SaleOppFileUpload_fileType: filerItem[0]?.value,
                SaleOppFileUpload_uploadDate: moment(new Date()).format(
                  dateFormat,
                ),
                SaleOppFileUpload_uploadStaff: 'admin', // 改为登录人数据
                SaleOppFileUpload_uploadStaffId: '1', // 改为登录人数据
              };
              if (signTime) {
                pushItem.assignDate = moment(signTime).format(dateFormat);
              }
              mFileList.push(pushItem);
            } else {
              mFileList.push({
                ...data[0],
                SaleOppFileUpload_uploadDate: moment(new Date()).format(
                  dateFormat,
                ),
              });
            }

            setFileList(mFileList);
            saveFileList(mFileList);
            Toast.success('附件上传成功', 1);
          } else {
            Toast.fail(data?.resultMsg, 1);
          }
        });
        // if (!new RegExp("(jpg|jpeg|gif|png)+", "gi").test(files[0].type)) {
        //   Toast.fail("您上传的文件格式有误，请重新上传~");
        // } else {
        //   dispatch!({
        //     type: "businessManagement/uploadFile",
        //     payload: {
        //       fileName: mFile.split(".")[0],
        //       inputStream: imag,
        //     },
        //   });
        // }
      };
      reader.onerror = () => {
        Toast.fail('文件读取失败', 2);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          if (event.loaded === event.total) {
            Toast.hide();
          } else {
            Toast.loading('文件上传中，请稍候...', 0);
          }
        }
      };
    }
  };

  // 附件删除
  const onDeleteProd = (index: number) => {
    const mfileList = JSON.parse(JSON.stringify(fileList));
    mfileList.splice(index, 1);
    saveFileList(mfileList);
    setFileList(mfileList);
  };

  const renderRow = (rowData: any, index: number) => {
    const { SaleOppFileUpload_file = [] } = rowData;
    let uploadFile = {} as any;
    if (SaleOppFileUpload_file.length > 0) {
      uploadFile = SaleOppFileUpload_file[0];
    }
    let fileTypeName = rowData.SaleOppFileUpload_fileType;
    fileTypeOptions.map((item: any) => {
      if (rowData.SaleOppFileUpload_fileType === item.value) {
        fileTypeName = item.label || '';
      }
    });
    return (
      <div className={styles.fileList} key={uploadFile?.attachId}>
        <div className={styles.flieLeft}>
          <img src={copyIcon} className={styles.Img} />
          {isTypeUpload ? (
            <div className={styles.fileText}>
              <div className={styles.fileName}>{uploadFile.fileName}</div>
              <div className={styles.fileTips}>
                <div>{`${fileTypeName || ''}\xa0\xa0|\xa0\xa0${
                  rowData.SaleOppFileUpload_uploadDate
                }`}</div>
              </div>
            </div>
          ) : (
            <div className={styles.fileText}>
              <div className={styles.fileName}>{rowData.fileName}</div>
              <div className={styles.fileTips}>
                <div>{`${fileTypeName || ''}\xa0\xa0|\xa0\xa0${
                  rowData.SaleOppFileUpload_uploadDate
                }`}</div>
              </div>
            </div>
          )}
        </div>
        {isEdit && (
          <img
            className={styles.deleteIcon}
            src={deleteIcon}
            alt=""
            onClick={() => {
              onDeleteProd(index);
            }}
          />
        )}
      </div>
    );
  };

  const renderUploadModal = () => {
    return (
      <Modal
        visible={showModal}
        transparent
        className={styles.modal}
        onClose={() => {
          setFileTypeValue(undefined);
          setSignTime(undefined);
          setShowModal(false);
          setIsChooseFile(true);
        }}
      >
        <div className={styles.modalView}>
          <div className={styles.title}>附件上传</div>
          <List style={{ backgroundColor: 'white' }}>
            <Picker
              data={fileTypeOptions}
              cols={1}
              value={fileTypeValue}
              onChange={(val) => {
                if (!val?.includes('5000')) {
                  setSignTime(undefined);
                  setIsChooseFile(false);
                } else {
                  setIsChooseFile(true);
                }
                setFileTypeValue(val);
              }}
            >
              <List.Item arrow="horizontal">附件类型</List.Item>
            </Picker>
            {fileTypeValue && fileTypeValue.includes('5000') && (
              <DatePicker
                mode="date"
                title="签约时间"
                extra="请选择"
                value={signTime}
                onChange={(date) => {
                  setIsChooseFile(false);
                  setSignTime(date);
                }}
              >
                <List.Item arrow="horizontal">签约时间</List.Item>
              </DatePicker>
            )}
          </List>

          <div
            className={classnames({
              [styles.footerView]: true,
              [styles.disableColor]: isChooseFile,
            })}
          >
            选择附件
            <input
              className={styles.footerInput}
              id="uploadEnclosure"
              name="file"
              accept="/*"
              type="file"
              disabled={isChooseFile}
              onChange={uploadImg}
            />
          </div>
        </div>
      </Modal>
    );
  };

  return (
    <CardDiv
      title={title}
      style={styles.cardDiv}
      rightView={isEdit && rightView()}
    >
      <>
        <div className={styles.dataList}>
          {fileList.map((row: any, index: number) => renderRow(row, index))}
        </div>
        {renderUploadModal()}
      </>
    </CardDiv>
  );
};

export default React.memo(Enclosure);
