import { uploadRef, uploadRefBtn, uploadRefInfo, uploadRefViewBtn } from '../../configuration/constants'
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: uploadRef,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${uploadRef}" class="${uploadRef}">
        <button class="${uploadRefBtn}">选择上传文件</button>
        <div class="${uploadRefInfo}"></div>
        <input type="file"/>
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${uploadRef} {
          position: relative;
          padding: 8px 16px;
          text-align: center;
          overflow: hidden;
          width: auto;
          height: auto;
        }
        .${uploadRef} .${uploadRefBtn} {
          text-align: center;
          border-style: dashed;
          border-width: 1px;
          padding: 0;
          box-sizing:border-box;
          -moz-box-sizing:border-box;
          -webkit-box-sizing:border-box;
        }
        .${uploadRef} .${uploadRefViewBtn} {
          text-align: center;
          padding: 0;
          border-style: solid;
          border-width: 1px;
          box-sizing: border-box;
          -moz-box-sizing:border-box;
          -webkit-box-sizing:border-box;
        }
        .${uploadRef} .${uploadRefInfo} {
          text-align: left;
          width: 100%;
          line-height: 30px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .${uploadRef} input {
          display: none;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
          <path class="gjs-block-svg-path" d="M393.2 701.7c-8.2 0-16.4-3.1-22.6-9.4-12.5-12.5-12.5-32.8 0-45.3l115.3-115.3c14-14 36.9-14 50.9 0L652.1 647c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0l-95.5-95.5-95.5 95.5c-6.2 6.2-14.4 9.4-22.6 9.4z" fill="" p-id="2286"></path><path d="M511.3 921.1c-17.7 0-32-14.3-32-32v-276c0-17.7 14.3-32 32-32s32 14.3 32 32v276c0 17.6-14.3 32-32 32z" fill="" p-id="2287"></path><path d="M732.7 784.9c-17.7 0-32-14.3-32-32s14.3-32 32-32c90.6 0 164.3-73.7 164.3-164.3 0-82.9-61.9-153-144-163.1l-22.7-2.8-4.7-22.4c-20.8-99.9-110.1-172.4-212.4-172.4-102.2 0-191.5 72.5-212.4 172.4l-4.7 22.4-22.7 2.8c-82.1 10.1-144 80.2-144 163.1 0 90.6 73.7 164.3 164.3 164.3 17.7 0 32 14.3 32 32s-14.3 32-32 32c-61 0-118.3-23.8-161.5-66.9-43.1-43.1-66.9-100.5-66.9-161.5 0-107.6 75.2-199.7 178.2-222.8 15.8-53.8 47.7-102.2 91.3-138.1 50.1-41.2 113.4-63.9 178.3-63.9s128.3 22.7 178.3 63.9c43.6 35.9 75.5 84.3 91.3 138.1C885.9 356.8 961 448.9 961 556.5c0 61-23.8 118.3-66.9 161.5-43.1 43.1-100.4 66.9-161.4 66.9z" fill=""></path>
        </svg>
        <div class="gjs-block-label">上传文件</div>
      `,
    };
  },

  spOptions() {
    return {
      label: '上传文件',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/7fd3fd26-ab20-48dd-b3e1-d17024d6b859?# 《上传文件》',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'all',
          description: {
            zh_CN: '输入1'
          }
        }],
      outPorts: [{
          uuid: 'out1',
          subType: 'string',
          description: {
            zh_CN: '文件路径'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      resizable: true,
      dmode: 'absolute',
      highlightable: false,
      droppable: false,
      childrenSelectable: false,
      traits: [
        {
          name: 'authorInfo',
          label: '开发者',
          type: 'authorInfo',
          author: '宗介',
          email: 'zongjie.wxt@xuelangyun.com'
        },
        {
          label: '文件类型',
          changeProp: 1,
          name: 'fileType',
          type: 'select',
          options: [
            { id: 'all', name: '任意文件' },
            { id: '视频', name: '视频(mp4)' },
            { id: '声音', name: '声音(mp3,wav,wma)' },
            { id: '图片', name: '图片(jpg,png)' },
            { id: 'csv', name: 'csv' },
            { id: 'excel', name: 'excel' },
            { id: 'txt', name: 'txt' },
            { id: '压缩文件', name: '压缩文件(rar,zip)' },
            { id: '文件夹', name: '文件夹' }
          ]
        },{
          label: '显示文件类型',
          changeProp: 1,
          name: 'showFileType',
          type: 'checkbox',
        }, {
          label: '上传按钮宽度',
          changeProp: 1,
          name: 'uploadWidth',
          type: 'number',
        }, {
          label: '查看按钮宽度',
          changeProp: 1,
          name: 'viewWidth',
          type: 'number',
        }, {
          label: '高度',
          changeProp: 1,
          name: 'height',
          type: 'number'
        }, {
          label: '背景色',
          changeProp: 1,
          name: 'bgColor',
          type: 'color'
        }, {
          label: '边框颜色',
          changeProp: 1,
          name: 'borderColor',
          type: 'color'
        }, {
          label: '字体颜色',
          changeProp: 1,
          name: 'fontColor',
          type: 'color'
        }, {
          label: '按钮文案',
          changeProp: 1,
          name: 'text',
        }, {
          label: '字体大小',
          changeProp: 1,
          name: 'fontSize',
          type: 'number',
          min: 8
        }, {
          label: '提示信息字体颜色',
          changeProp: 1,
          name: 'fontColorInfo',
          type: 'color'
        }, {
          label: '提示信息字体大小',
          changeProp: 1,
          name: 'fontSizeInfo',
          type: 'number',
          min: 8
        }
      ],
      "fileType": 'all',
      "showFileType": true,
      "uploadWidth": 250,
      "viewWidth": 50,
      "height": 40,
      "bgColor": '#fff',
      "borderColor": '#ccc',
      "fontColor": "#000",
      "fontSize": 14,
      "fontColorInfo": "#000",
      "fontSizeInfo": 14,
      "text": "选择上传文件"
    }
  },

  onModelScript() {
    const fileType = ('{[ fileType ]}').toString();
    const text = ('{[ text ]}').toString();
    const uploadWidth = Boolean('{[ uploadWidth ]}')? Number('{[ uploadWidth ]}') : 250;
    const viewWidth = Boolean('{[ viewWidth ]}')? Number('{[ viewWidth ]}') : 50;
    const height = Boolean('{[ height ]}')? Number('{[ height ]}') : 40;
    const bgColor = Boolean('{[ bgColor ]}')? ('{[ bgColor ]}').toString() : '#fff';
    const borderColor = Boolean('{[ borderColor ]}')? ('{[ borderColor ]}').toString() : '#ccc';
    const fontColor = Boolean('{[ fontColor ]}')? ('{[ fontColor ]}').toString() : '#000';
    const fontSize = Boolean('{[ fontSize ]}')? Number('{[ fontSize ]}') : 14;
    const fontColorInfo = Boolean('{[ fontColorInfo ]}')? ('{[ fontColorInfo ]}').toString() : '#000';
    const fontSizeInfo = Boolean('{[ fontSizeInfo ]}')? Number('{[ fontSizeInfo ]}') : 14;
    const showFileType = Boolean('{[ showFileType ]}')

    const self = this;
    const blockWidth = uploadWidth + viewWidth + 3; //button border
    const input = $(self).find('input')[0];
    const button = $(self).find('.sp-upload-btn')[0];
    const viewButton = $(self).find('.sp-upload-view-btn')[0];
    const fileInfo = $(self).find('.sp-upload-info')[0];
    const _id = self.getAttribute('id');
    const eventName = `call-${_id}`;

    const getSupportFileType = function (fileType) {
      let checkFileType = [];
      switch(fileType) {
        case '视频':
          checkFileType = [".mp4"];
          break;
        case '声音':
          checkFileType = [".mp3",".wav",".wma"]
          break;
        case '图片':
          checkFileType = [".jpg", ".png"]
          break;
        case 'csv':
          checkFileType = [".csv"]
          break;
        case 'excel':
          checkFileType = [".xlsx", ".xls"]
          break;
        case 'txt':
          checkFileType = [".txt"]
          break;
        case '压缩文件':
          checkFileType = [".rar",".zip"]
          break;
      }
      return checkFileType;
    }

    const getSupportFileDisplay = function (fileType) {
      let support = '';
      switch(fileType) {
        case 'all':
            support = '任意文件';
            break;
        case '视频':
          support = '视频[mp4]';
          break;
        case '声音':
          support = '声音[mp3,wav,wma]';
          break;
        case '图片':
          support = '图片[jpg,png]';
          break;
        case 'csv':
          support = 'csv'
          break;
        case 'excel':
          support = 'excel'
          break;
        case 'txt':
          support = 'txt'
          break;
        case '压缩文件':
          support = '压缩文件[rar,zip]'
          break;
        case '文件夹':
          support = '文件夹'
          break;
      }
      return support;
    }

    if (fileType !== '') {
      const fileTypeSupport = getSupportFileType(fileType)
      if( fileType === '文件夹') {
        $(input).attr('webkitdirectory', "webkitdirectory");
        $(input).attr('multiple', "multiple");
      } else {
        $(input).attr('accept', fileTypeSupport.join(','));
      }
    }

    if(showFileType) {
      const fileDisplay = getSupportFileDisplay(fileType);
      $(button).text(`${text}(${fileDisplay})`);
    } else {
      $(button).text(`${text}`);
    }

    $(button).width(uploadWidth);
    $(button).height(height);
    $(button).css("line-height", `${height}px`);
    $(button).css('background-color', bgColor);
    $(button).css('border-color', borderColor);
    $(button).css('color', fontColor);
    $(button).css('font-size', `${fontSize}px`);

    $(viewButton).width(viewWidth);
    $(viewButton).height(height);
    $(viewButton).css("line-height", `${height}px`);
    $(viewButton).css('background-color', bgColor);
    $(viewButton).css('border-color', borderColor);
    $(viewButton).css('color', fontColor);
    $(viewButton).css('font-size', `${fontSize}px`);

    $(fileInfo).width(blockWidth);
    $(fileInfo).css('font-size', `${fontSizeInfo}px`);
    $(fileInfo).css('color', fontColorInfo);

    const beforeUpload = function (files) {
      let checkFlag = true;
      if(['all', '文件夹'].indexOf(fileType) === -1) {
        const file = files[0];
        // const currFileType = file.type;
        const currFileType = file.name.substring(file.name.lastIndexOf('.'));
        const checkFileType = getSupportFileType(fileType);
        if(checkFileType.indexOf(currFileType) === -1) {
          checkFlag = false;
        }
      }
      return checkFlag;
    }
    $(button).on("click", function(event) {
        $(input).trigger('click');
    })
    if (window.spSocket) {
        if(window.spNewUpload === undefined) {
          window.sp({
            url: location.protocol + "//" + location.host + "/dashboard",
            path: '/socket/' + window.appConfig.userId + '/' + window.appConfig.id,
            oss: {
              type: window.appConfig.ossType
            }
          }).then(function(spNewUpload) {
            window.spNewUpload = spNewUpload;
          });
        }

        const oss_path = "studio/" + window.appConfig.userId + "/" + window.appConfig.id + "/";
        let fileName = '';
        $(input).on("change", function(event) {
            const files = $(input)[0].files;
            const filesLength = files.length;
            if(filesLength > 0) {
              const uploadFlag = beforeUpload(files);
              if (uploadFlag) {
                const fileNameList= [];
                for(var i = 0; i < filesLength; i++)
                {
                  fileNameList.push(files[i].name);
                }
                fileName = fileNameList.join(',');
                $(fileInfo).html(`上传文件: ${fileName}`);
                $(fileInfo).attr('title', `上传文件: ${fileName}`)
                window.spNewUpload.sendFile(oss_path, files).then((keys)=>{
                    $(fileInfo).html(`${fileName}上传成功`);
                    $(fileInfo).attr('title', `${fileName}上传成功`)
                    keys.forEach(key => {
                        window.spNewUpload.oss.getSignedUrl(keys[0]).then((content) => {
                          window.spSocket.send({
                            eventName,
                            data: {
                              success: true,
                              out1: content,
                              extra: {
                                global: { debug: true }
                              }
                            }
                          });
                        });
                    });
                }).catch((reason)=>{
                    let msg = '';
                    if (reason instanceof Error) {
                        if(`${reason.name}` === "ConnectionTimeoutError") {
                        msg = "连接超时(5分钟)"
                        } else {
                        msg = `${reason.message}`
                        }
                    } else if(reason instanceof Object) {
                        msg = `${reason.msg}`
                    } else {
                        msg = reason
                    }
                    $(fileInfo).html(`上传失败！${msg}`);
                    $(fileInfo).attr('title',`上传失败！${msg}`)
                    $(input).value = '';
                });
              } else {
                $(fileInfo).html('选择的文件类型错误');
                $(fileInfo).attr('title','选择的文件类型错误')
              }
            }
        })
    }
  },

  onViewInit() {
    const evn = `
      change:uploadWidth
      change:viewWidth
      change:height
      change:bgColor
      change:borderColor
      change:fontColor
      change:fontSize
      change:fontSizeInfo
      change:fontColorInfo
      change:fileType
      change:showFileType
      change:text
    `
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    this.listenTo(this.em, 'update:component:style:height update:component:style:width', throttle.bind(this, this.updateScript.bind(this)));
  }
}
