<template>
  <el-form ref="form" label-width="80px" label-suffix='' v-loading.fullscreen.lock="loading"
  element-loading-background="rgba(0, 0, 0, 0.8)">

    <!-- v-if="propBase.readonly!=='1'"  这个设置是为了区分权限，控制是否可见 -->
    <el-form-item v-for="propBase in compPropsBase" :key="propBase.id" :label="propBase.title" v-if="propBase.readonly!=='1'">
      <el-input v-if="propBase.inputType==='text'" :placeholder="'请输入'+propBase.title" v-model="comp.props[propBase.key].val" v-bind:disabled="propBase.readonly==='1'">
      </el-input>

      <!-- <el-upload v-else-if="propBase.inputType==='uploadimg'" class="upload-demo" :action="''" :on-preview="handlePreview" :on-remove="handleRemove"
        :file-list="imgs" list-type="picture" multiple> -->
      <el-upload class="upload-demo" v-else-if="propBase.inputType==='uploadimg'"
      :action="url"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="uploadBefore"
      :on-remove="uploadRemove"
      list-type="picture"
      :with-credentials="true"
      :show-file-list="true"
      :file-list="uploadImgList"
      accept="image/jpeg,image/jpg,image/png">

        <el-button size="small" type="primary" @click="saveKey(propBase.key)">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb </div>
      </el-upload>

      <div v-if="propBase.inputType==='uploadimg'">
        <el-input :placeholder="'请输入'+propBase.title" v-model="comp.props[propBase.key].val"></el-input>
      </div>

      <div v-if="propBase.inputType==='link'">
        <el-select v-model="comp.props[propBase.key].val" :placeholder="'请选择'+propBase.title">
          <el-option v-for="page in cfg.pages" :key="page.id" v-if="page.id!==selectedPage.id" :label="page.name" :value="page.id"></el-option>
        </el-select>
        <!-- <el-input :placeholder="'请输入自定义'+propBase.title" v-model="comp.props[propBase.key].val"></el-input> -->
      </div>

      <div v-if="propBase.inputType==='color'">
        <el-color-picker v-model="comp.props[propBase.key].val" v-bind:disabled="propBase.readonly==='1'"></el-color-picker>
      </div>
		<div v-if="propBase.inputType === 'richtext'">
			{{registerEditor(propBase.key)}}
			<textarea :id="propBase.key + currentTime" class="tinymce-textarea"></textarea>
		</div>
    </el-form-item>
    <div id="editor-content" style="text-align:left"></div>
  </el-form>
</template>

<script>
  //import quillEditor from 'vue-quill-editor' //调用编辑器
  import E from "wangeditor";
  import tinymce from 'tinymce'
  import 'tinymce/themes/silver/'
  import 'tinymce/skins/ui/oxide/skin.css'
  import '@/assets/js/libs/zh_CN'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/autoresize'

  export default {
    name: "CompPropsSetting",
    props: ["comp", "cfg", "selectedPage"],
    data() {
      return {
        compPropsBase: undefined, // 当前编辑的这个组件的基本属性列表
        compProps: {},
        imgs: [],
        url:this.sup8._appConf.apiUrl.alioss,
        imgKey:"",
        uploadImgList:[],
        loading:false,
		  currentTime :new Date().getTime()
      };
    },
    methods: {
		registerEditor (key) {
			this.$nextTick(() => {
				const value = this.comp.props[key].val
				const setting =
					{
						mode: 'none',
						selector: `#${key+this.currentTime}`,
						language: 'zh_CN',
						max_height: 450,
						resize: true,
						init_instance_callback: editor => {
							if (value) {
								try {
									editor.setContent(decodeURIComponent(value))
								} catch (e) {
									editor.setContent(value)
								}
							}
							editor.on('input undo redo execCommand CloseWindow', (e) => {
								this.comp.props[key].val = encodeURIComponent(editor.getContent())
							})
						},
						browser_spellcheck: false, // 拼写检查
						branding: false, // 去水印
						// elementpath: false,  //禁用编辑器底部的状态栏
						statusbar: false, // 隐藏编辑器底部的状态栏
						paste_data_images: true, // 允许粘贴图像
						menubar: false, // 隐藏最上方menu
						plugins: 'code,autoresize',
						theme_advanced_toolbar_location : "top",
						theme_advanced_resizing : true,
						toolbar: 'code fontselect fontsizeselect forecolor backcolor bold italic underline alignleft aligncenter alignright alignjustify',
						fontsize_formats:"0.12rem 0.14rem 0.16rem 0.18rem 0.20rem 0.22rem 0.24rem 0.26rem 0.28rem 0.30rem 0.32rem",
					}
				tinymce.init(setting)
			})
		},
      saveKey(key){
        this.imgKey = key;
      },
      uploadSuccess(response, file, fileList) {
        if(response.flag && response.data !=undefined){
          this.uploadImgList=[response.data];
          this.comp.props[this.imgKey].val = response.data.url;
          this.loading = false;
          this.$message.success('上传成功');
        }
      },
      uploadError(err, file, fileList) {
        this.$message.error('上传失败');
        this.loading = false;
      },
      uploadBefore(file) {
        const size = 1024*500;
        const typeArr = ["image/jpeg","image/jpg","image/png"];
        if(!typeArr.includes(file.type)){
          this.$message.warning('请上传png/jpg类型的图片');
          return false;
        }
        if(file.size>size){
          this.$message.warning('上传图片不能超过500kb');
          return false;
        }
        this.loading = true;
      },
      uploadRemove(file, fileList) {
        this.uploadImgList=[];
        this.comp.props[this.imgKey].val = "";
      },
      getContent() {
        alert(this.editorContent);
      },
      afterGetPropData(props) {
        var that = this;
        // 对数据进行处理，防止实际属性列表和默认不匹配时报错
        _.forEach(props, function (ch) {
          if (ch && ch.key && !that.comp.props[ch.key]) {
            props[ch.key] = ch;
            props[ch.key].val = "";
            props[ch.key].available = props === "0";
          }

          // 如果是富文本框形式的参数项，需要些特殊配置
          if (ch.inputType === "rich") {
            var editor = new E("#editor-content");
            if (editor) {
              editor.customConfig.onchange = html => {
                that.comp.props[ch.key].val = html;
              };

              editor.customConfig.uploadImgServer = that.sup8._appConf.apiUrl.alioss;
              editor.customConfig.withCredentials = true;
              // editor.customConfig.debug = true;
              // editor.customConfig.uploadImgHeaders = {
              //     'Accept': 'text/x-json'
              // }
              editor.customConfig.customAlert = function (info) {
                  // info 是需要提示的内容
                  this.$message.error(info);
              }
              editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                    // 图片上传之前触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件

                    // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                    // return {
                    //     prevent: true,
                    //     msg: '放弃上传'
                    // }
                },
                success: function (xhr, editor, result) {
                  console.log(xhr, editor, result);
                    // 图片上传并返回结果，图片插入成功之后触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                  console.log(xhr, editor, result);
                    // 图片上传并返回结果，但图片插入错误时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                error: function (xhr, editor) {
                  console.log(xhr);
                    // 图片上传出错时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },
                timeout: function (xhr, editor) {
                    // 图片上传超时时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                  console.log(insertImg, result, editor);
                    // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                    // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data.url;
                    insertImg(url)

                    // result 必须是一个 JSON 格式字符串！！！否则报错
                }
              }
              editor.customConfig.showLinkImg = true;
              editor.customConfig.hideLinkImg = false;
              editor.customConfig.colors = [
                "#000000",
                "#eeece0",
                "#1c487f",
                "#4d80bf",
                "#c24f4a",
                "#8baa4a",
                "#7b5ba1",
                "#46acc8",
                "#f9963b",
                "#ffffff",
                "#CC0000",
                "#cd940b",
                "#898989"
              ];

              editor.customConfig.uploadImgShowBase64 = true;
              editor.create();
              editor.txt.html(that.comp.props[ch.key].val);
            }
          }
        });
      }
    },
    watch: {
      "selectedPage.isHome": function (n, o) {
        console.log("CompPropsSetting:watch:selectedPage", n);
        var that = this;
        _.forEach(this.cfg.pages, function (page) {
          if (page.id !== that.selectedPage.id) {
            page.isHome = false;
          }
        });
      }
    },
    created() {
      var that = this;
      console.log("公共");
      // debugger;
    },
    mounted: function () {
      console.log("CompPropSetting:mounted:", this.comp);
      var that = this;
      that.mergeCompProps(that.comp);
      //that.compPropsBase;
      // 查找此插件的数据是不是已经有了
      if (that.sup8._baseComponentList !== undefined) {
        let baseComp = _.find(that.sup8._baseComponentList, {
          id: that.comp.baseCompId,
          ver: that.comp.ver
        });

        if (baseComp !== undefined && baseComp.props !== undefined) {
          that.compPropsBase = baseComp.props;
        }
      }

      if (that.compPropsBase === undefined) {
        //  if (true) {
        var reqParam = {
          appkey: sessionStorage.appkey,
          accesstoken: sessionStorage.accesstoken,
          compid: this.comp.baseCompId,
          ver: this.comp.ver,
          level: that.sup8.role.permissionLevel
        };
        that.$http
          .post(that.sup8._appConf.apiUrl.getComponentProps, reqParam)
          .then(
            function (response) {
              var resData = response.body;
              that.compPropsBase = resData.data;
              that.afterGetPropData(that.compPropsBase);
            },
            function (response) {
              console.log("error", response);
            }
          );
      } else {
        that.afterGetPropData(that.compPropsBase);
      }
      console.log(this.compPropsBase);
      //this.comp.props = this.convertCompProps(this.comp.props)
    }
  };

</script>

<style scoped>
  .w-e-text-container {
    height: auto;
  }

  .w-e-text {
    padding: 0 !important;
  }

  #editor-content {
    /* width: 316px; */
  }

  .w-e-text-container {
    height: 800px;
  }

</style>
