import React, { useState, useEffect, useRef } from 'react';
import './index.less';
import { Button, Form, message, Modal, Input, Upload } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
// import FacilitysTow from './FacilitysTow';
import { Link, useIntl, connect, Dispatch, history } from 'umi';

function getBase64(file: any) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
const module = 'FacilityBookings';

const Facilitys = (props: any) => {
  //传递值
  const { updata, disabled, FacilitysList, dispatch, dumps } = props;

  //上传列表
  // const [FacilitysList, setFileList] = useState(FacilitysList);
  //显示隐藏
  const [previewVisible, setpreviewVisible] = useState(false);
  // 名称
  const [previewTitle, setpreviewTitle] = useState('');
  // 图片地址
  const [previewImage, setpreviewImage] = useState('');

  // 传递给后台加 key
  const updetaTow = (key: any) => {
    let data = updata;
    data.identification = key;
    return data;
  };

  //绑定值
  const updetaList = (key: any) => {
    return FacilitysList[key].fileList;
  };

  // 预览
  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setpreviewImage(file.url || file.preview);
    setpreviewTitle(file.name);
    setpreviewVisible(true);
  };

  // 点击移除图片
  const handRemove = (key: any) => {
    // let list = fileList;
    // 将图片信息提交给state
    deleteImg(key);
  };

  // 点击遮罩回调
  const handleCancel = () => {
    setpreviewVisible(false);
  };

  // 上传属性
  const uploadProps: any = {
    listType: 'picture-card',
    accept: '.jpeg,.png,.jpg',
    action: '/tos/image/upload',
    onChange(info: any) {
      // console.log(info);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
        // 拿到key 值  开始存储
        let key = info.fileList[0].response.data.identification;
        let list = FacilitysList;
        list[key].id = key;
        list[key].fileList = info.fileList;
        // 存储到mode里面去
        dispatch({ type: module + '/genxin', list });
        // 当前页面也要刷新

        // let list = fileList;
        // setFileList(list);      // 注意 不能直接赋值  因为使用完全绑定需要全部更新

        // setFileList(list);
        // let list: any = [...fileList, ...info.fileList];
        // setFileList(list);

        console.log(list);
        // 将图片信息提交给state
        // let data = { val: info.file.name, key: keys };
        // dispatch({ type: module + '/retImgsList', data });
        // 结束
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  // 新增动作
  const add = () => {
    let list = FacilitysList;
    let adds = {
      id: '-1',
      fileList: [],
      name: '',
    };
    // 验证已添加的是否上传完整
    let complete = list.every((item: any) => {
      // return item.fileList.length > 0 && item.name !== '';
      return item.fileList.length > 0;
    });

    if (list.length == 0 || complete) {
      list.push(adds);
      // 存储到mode里面去
      dispatch({ type: module + '/genxin', list });
    } else {
      // 提示每一项都要填写完
      message.error('Please fill out each item ！');
    }
  };

  //删除动作
  const deleteImg = (key: any) => {
    let list = FacilitysList;
    list[key].name = '';

    // 这里还要清除表单的值，否则再次新增输入框的值会重复出现
    dumps(key);

    list.splice(key, 1);
    // 存储到mode里面去
    dispatch({ type: module + '/genxin', list });
  };

  // 新增按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  // 输入框内容
  const monitor = (e: any) => {
    let list = FacilitysList;
    let { id, value } = e.target;
    if (id == 'basic_shebei_0') {
      id = 0;
    }
    list[id].name = value;
    dispatch({ type: module + '/genxin', list });
  };

  return (
    <>
      <Form.Item name="picList" required={false} style={{ marginBottom: 0 }}>
        {FacilitysList.map((item: any, index: any, key: any) => {
          return (
            <div className={'test'} key={'pic_' + index}>
              <div className={'diybox'} key={'pic_' + index}>
                <Upload
                  {...uploadProps}
                  fileList={
                    FacilitysList[index].fileList.length > 0 ? FacilitysList[index].fileList : false
                  }
                  // data={updata}
                  data={updetaTow(index)} // 携带数据
                  disabled={disabled} // 禁止
                  onPreview={handlePreview} // 预览
                  onRemove={() => {
                    handRemove(index);
                  }} //移除
                >
                  {FacilitysList[index].fileList.length > 0 ? null : uploadButton}
                </Upload>

                <div className={'Facility'} key={'pic_' + index}>
                  <Form.Item
                    label={`Facility Name ${index + 1}`}
                    name={'shebei_' + index}
                    rules={[{ required: true, message: 'Please input Facility Name!' }]}
                  >
                    <Input
                      placeholder="Facility Name"
                      disabled={disabled}
                      id={index}
                      onChange={(e: any) => monitor(e)}
                      value={FacilitysList[index].name}
                    />
                  </Form.Item>
                  <div className={'over'}>
                    <Button type="link" disabled={disabled} onClick={() => deleteImg(index)}>
                      Delete
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </Form.Item>
      <Form.Item>
        <Button
          type="dashed"
          onClick={() => add()}
          style={{ width: '100px', height: '100px' }}
          icon={<PlusOutlined />}
          disabled={disabled}
        ></Button>
      </Form.Item>

      {/* 预览表格 */}
      <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
};

function mapStateToProps(state: any) {
  const { FacilitysList } = state.FacilityBookings;
  return {
    FacilitysList,
  };
}
export default connect(mapStateToProps)(Facilitys);
