<template>
  <div class="base-detail-container">
    <ts-form-item>
      <ts-radio
        title="属性类型"
        v-model="selectData.attrType"
        :data="attrType"
        type="text"
        @change="refresh(arguments, 'attrType')"
      ></ts-radio>
    </ts-form-item>
    <!-- 属性类型为图片时 -->
    <div v-if="selectData.attrType == 'picture'">
      <ts-form-item>
        <ts-radio
          title="展示方式"
          v-model="selectData.showType"
          :data="showType"
          type="group"
          :isDefaultFirst="true"
          @change="refresh(arguments, 'attrType')"
        ></ts-radio>
      </ts-form-item>
      <div v-if="selectData.showType == 'tile'">
        <ts-form-item>
          <ts-upload
            title="配置"
            action="/ts-system/file/upload"
            v-model="selectData.showPicture"
            type="image"
            @success="upploadHandler"
          ></ts-upload>
        </ts-form-item>
        <ts-form-item>
          <ts-input
            v-model="selectData.titleName"
            title="标题"
            @change="refresh(arguments, 'titleName')"
          ></ts-input>
        </ts-form-item>
        <ts-form-item>
          <ts-input
            v-model="selectData.linkUrl"
            title="链接地址"
            @change="refresh(arguments, 'linkUrl')"
          ></ts-input>
        </ts-form-item>
      </div>
      <!-- 属性类型为图片展示方式为轮播时 -->
      <div v-if="selectData.showType == 'carousel'">
        <ts-form-item>
          <ts-radio
            title="轮播方向"
            v-model="selectData.direction"
            :data="showDirection"
            type="group"
            @change="refresh(arguments, 'direction')"
          ></ts-radio>
        </ts-form-item>
        <ts-form-item>
          <ts-input
            v-model="selectData.interval"
            type="integer"
            :min="0"
            title="循环间隔"
            :clearable="false"
            @change="refresh(arguments, 'interval')"
          ></ts-input>
        </ts-form-item>
        <div>
          <ts-row
            style="background: '#ddd';position:relative;"
            v-for="(item, j) in selectData.carouselList"
            :key="j"
            type="flex"
          >
            <ts-col class="form-autoEdit-item-i txt">{{ j + 1 }}</ts-col>
            <ts-col :flex="19">
              <ts-form-item>
                <ts-upload
                  title="配置"
                  action="/ts-system/file/upload"
                  v-model="item.showPicture"
                  type="image"
                  @success="upploadHandler(arguments, item)"
                ></ts-upload>
              </ts-form-item>
              <ts-form-item>
                <ts-input
                  v-model="item.titleName"
                  title="标题"
                  @change="refresh(arguments, 'titleName')"
                ></ts-input>
              </ts-form-item>
              <ts-form-item>
                <ts-input
                  v-model="item.linkUrl"
                  title="链接地址"
                  @change="refresh(arguments, 'linkUrl')"
                ></ts-input>
              </ts-form-item>
            </ts-col>
            <ts-col :flex="2"></ts-col>
            <ts-col class="form_add" style="padding-top:5px;">
              <ts-button
                id="deleteAutoEdit"
                type="text"
                icon="iconfont icon-Group-17"
                @click="onRelation('delete', item.i)"
                v-if="j != 0"
              ></ts-button>
              <ts-button
                v-if="j === 0"
                id="addAutoEdit"
                type="text"
                icon="iconfont icon-Group-13"
                @click="onRelation('add', item.i)"
                class="form-autoEdit-item-add-btn"
              ></ts-button>
            </ts-col>
          </ts-row>
        </div>
      </div>
    </div>
    <!-- 当类型为视频时 -->
    <div v-else-if="selectData.attrType == 'video'">
      <ts-form-item>
        <ts-input
          v-model="selectData.titleName"
          title="标题"
          @change="refresh(arguments, 'titleName')"
        ></ts-input>
      </ts-form-item>
      <div style="width: 350px; margin: 3px 10px 0 100px;display:flex;">
        <el-upload
          class="avatar-uploader"
          action="/ts-portal/api/portal/elementtype/meidiaUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="font12">
          <div>（上传文件大小，不超过500M)</div>
        </div>
      </div>
      <div v-if="percentageshow" style="width: 200px; margin: 3px 10px 0 100px;">
        <el-progress :percentage="percentage" :format="format"></el-progress>
      </div>
      <div v-if="selectData.videoUrl" style="width: 200px; margin: 3px 10px 0 100px">
        <video width="360" height="180" controls>
          <source :src="selectData.videoUrl" type="video/mp4" />
        </video>
      </div>
    </div>
    <!-- 当类型为富文本编辑时 -->
    <div v-else-if="selectData.attrType == 'text'">
      <ts-form-item>
        <ts-radio
          title="数据源"
          v-model="selectData.isSource"
          :data="isSource"
          type="text"
          :isDefaultFirst="true"
          @change="refresh(arguments, 'isSource')"
        ></ts-radio>
      </ts-form-item>
      <div v-if="selectData.isSource == 'has'">
        <ts-select
          v-model="selectData.dataSourceId"
          :source="dataSourceData"
          title="数据源"
          @selected="refresh($event, 'dataSourceId')"
        ></ts-select>
        <ts-form-item
          v-if="
            selectData.selectDataSourceResultData &&
            selectData.selectDataSourceResultData.length > 0
          "
        >
          <ts-select
            title="结果集"
            :key="'selectDataResult' + selectData.id"
            :source="selectDataSourceResult"
            v-model="selectData.selectDataSourceResult"
            @selected="refresh($event, 'selectDataSourceResult')"
          ></ts-select>
        </ts-form-item>
        <ts-select
          title="绑定字段"
          :key="'selectDataCode' + selectData.id"
          ref="selectDataSourceCode"
          :source="selectDataSourceCode"
          v-model="selectData.selectDataSourceCode"
          @selected="refresh($event)"
        ></ts-select>
      </div>
      <ts-form-item>
        <ts-input v-model="selectData.titleName" title="标题" @change="refresh(arguments)"></ts-input>
      </ts-form-item>
      <vue-editor
        class="custom_text"
        id="editor1"
        :editor-toolbar="customToolbar"
        :useCustomImageHandler="true"
        @image-added="handleImageAdded"
        @text-change="onEditorBlur"
        v-model="selectData.content"
        @blur="onEditorBlur"
        :disabled="editorDisabled"
      ></vue-editor>
    </div>
  </div>
</template>

<script>
export default {
  name: 'attr-base',
  props: {},
  data() {
    return {
      percentageshow: false,
      percentage: 0,
      videoUrl: '',
      editorDisabled: false,
      customToolbar: [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        [
          { align: '' },
          { align: 'center' },
          { align: 'right' },
          { align: 'justify' }
        ],
        ['blockquote', 'code-block'],
        [{ list: 'ordered' }, { list: 'bullet' }, { list: 'check' }],
        [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
        [{ color: [] }, { background: [] }], // dropdown with defaults from theme
        ['link', 'image'],
        // [{ 'size': ['10', '12', '14', '16', '18', '20', '22', '24', '26', '32', '48'] }],
        [{ header: [false, 1, 2, 3, 4, 5, 6] }],
        //  [{ size: ['small', false, 'large', 'huge'] }],
        ['clean'] // remove formatting button
      ],
      dataSourceData: {
        dataType: 'local',
        data: this.$store.state.bi.dataSource,
        code: 'id',
        text: 'queryName',
        condition: 'condition',
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      },
      editor1Content: '',
      imageUrl: '',
      isStripe: true,
      attrType: [
        { value: 'picture', text: '图片' },
        { value: 'video', text: '视频' },
        { value: 'text', text: '文本域' }
      ],
      isSource: [
        { value: 'nohas', text: '无' },
        { value: 'has', text: '指定数据源' }
      ],
      showType: [
        { value: 'tile', text: '平铺' },
        { value: 'carousel', text: '轮播' }
      ],
      showDirection: [
        { value: 'horizontal', text: '水平' },
        { value: 'vertical', text: '垂直' }
      ],
      selectData: JSON.parse(JSON.stringify(this.$store.state.bi.selectData)),
      headerList: [{ id: '', name: '', i: 0 }],
      pageInfoloading: false
    }
  },
  created() {},
  computed: {
    selectDataSourceCode() {
      return this.dataSourceColSource(this.selectData.selectDataSourceData)
    },
    // 下拉数据源-值
    selectDataSourceResult() {
      return this.dataSourceColSource(
        this.selectData.selectDataSourceResultData
      )
    }
  },
  methods: {
    percentageDo() {
      this.percentageshow = true
      this.percentage = 0
      let timer = setInterval(() => {
        if (this.percentage >= 99) {
          clearInterval(timer)
        } else {
          this.percentage = this.percentage + 1
        }
      }, 100)
    },
    format(percentage) {
      return `${percentage}%`
    },
    dataSourceColSource(data) {
      return {
        dataType: 'local',
        code: 'name',
        text: 'name',
        data: data || [],
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      }
    },

    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const _this = this
      let data = new FormData()
      data.append('file', file)
      this.$api({
        url: '/ts-system/file/upload',
        method: 'post',
        data: data,
        processData: false,
        contentType: false,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(function(response) {
          let url = response.object.url // Get url from response
          Editor.insertEmbed(cursorLocation, 'image', url)
          resetUploader()
        })
        .catch(function(error) {})
    },
    onEditorBlur(quill) {
      this.$store.commit('setSelectData', { ...this.selectData })
      this.$store.commit('saveArr', { data: { ...this.selectData } })
      this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
    },

    handleAvatarSuccess(val) {
      if (val.object.error == 1) {
        this.$utils.msg(this, '上传失败' + val.object.message, 'error')
        this.percentageshow = false
        return
      }
      this.selectData.videoUrl = val.object.url
      this.percentage = 100
      setTimeout(() => {
        this.percentageshow = false
      }, 100)
      this.$utils.msg(this, '上传成功', 'success')
      this.$store.commit('setSelectData', { ...this.selectData })
      this.$store.commit('saveArr', { data: { ...this.selectData } })
      this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
    },
    beforeAvatarUpload(val) {
      this.selectData.videoUrl = ''
      this.percentageDo()
    },
    onRelation(type, index) {
      //关联指标的操作
      switch (type) {
        case 'add':
          var relation = {
            id: this.$utils.uuid(16),
            i: this.$utils.uuid(16),
            linkUrl: '',
            titleName: '',
            showPicture: ''
          }
          this.selectData.carouselList.push(relation)
          break
        case 'delete':
          for (var i = 0; i < this.selectData.carouselList.length; i++) {
            if (this.selectData.carouselList[i].i == index && index != 0) {
              this.selectData.carouselList.splice(i, 1)
              break
            }
          }
          break
      }
      this.$store.commit('saveArr', { data: { ...this.selectData } })
      this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
    },
    upploadHandler(o, item) {
      if (item) {
        item.showPicture = o[0][o[0].length - 1].url
      } else {
        this.selectData.showPicture = o[o.length - 1].url
      }
      // 上传回写
      this.$store.commit('setSelectData', { ...this.selectData })
      this.$store.commit('saveArr', { data: { ...this.selectData } })
      this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
    },
    refresh(ev, arrKey) {
      if (arrKey == 'stripe') {
        this.isStripe = ev[0] != 'true'
      } else if (arrKey == 'dataSourceId') {
        this.selectData.selectDataSourceCode = ''
        this.selectData.selectDataSourceName = ''
        this.selectData.selectDataSourceResult = ''
        this.selectData.selectDataSourceData = []
        this.selectData.dataSourceId = ev.id
        this.selectData.dataSourceName = ev.queryName
        this.selectData.selectDataSourceResultData = []
        if (ev.serviceType == '2') {
          // 结果集
          for (let item of JSON.parse(ev.columnDefine)) {
            this.selectData.selectDataSourceResultData.push({
              name: item.name,
              tableColumns: item.tableColumns
            })
          }
        } else {
          for (let item of JSON.parse(ev.columnDefine)) {
            this.selectData.selectDataSourceData.push({
              name: item.name
            })
          }
        }
        this.$store.commit('setSelectData', { ...this.selectData })
      } else if (arrKey == 'selectDataSourceResult') {
        this.selectData.selectDataSourceCode = ''
        this.selectData.selectDataSourceName = ''
        this.selectData.selectDataSourceData = []
        this.selectData.selectDataSourceResult = ev.name
        for (let items of ev.tableColumns) {
          this.selectData.selectDataSourceData.push({
            name: items.name
          })
        }
        this.$store.commit('setSelectData', { ...this.selectData })
      }
      if (arrKey == 'isSource') {
        this.editorDisabled = ev[0].label == 'has'
        this.selectData.content = this.editorDisabled
          ? ''
          : this.selectData.content
      }
      this.$nextTick(() => {
        if (arrKey == 'title' && this.selectData.type == 'tab') {
          let activeIndex = this.selectData.activeIndex || '0'
          for (let tab of this.selectData.tabs) {
            if (tab.index == activeIndex) {
              tab.title = ev.value
              break
            }
          }
        }
        this.$store.commit('saveArr', { data: { ...this.selectData } })
        // if (this.selectData.type == 'screen') {
        //   this.$store.commit('setScreenData', [...this.$store.state.bi.screenData])
        // } else {
        this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
        // }
      })
    }
  },
  mounted() {
    this.isStripe = this.selectData.stripe != 'true'
    this.editorDisabled = this.selectData.isSource == 'has'
  },
  watch: {
    '$store.state.bi.selectData': {
      handler(val) {
        this.selectData = JSON.parse(JSON.stringify(val))
        this.isStripe = this.selectData.stripe != 'true'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.form_add {
  position: absolute;
  right: 25px;
  width: 23px;
  top: 5px;
  height: 23px;
}
.form-autoEdit-item-i {
  position: absolute;
  left: 25px;
  width: 23px;
  top: 5px;
  height: 23px;
  border: 1px var(--bd_color) solid;
  text-align: center;
  line-height: 23px;
  margin-right: 6px;
  font-size: 12px;
  color: #555;
}

/deep/ .el-checkbox__label {
  font-size: 12px;
}

.stripeColor {
  height: 25px;
  line-height: 25px;
  width: 70px;
  font-size: 12px;
  text-indent: 6px;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #a9a9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--base-acv);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  height: 150px;
  width: 150px;
  line-height: 150px;
  text-align: center;
}
.el-upload .el-upload--text {
  height: 150px;
  width: 150px;
}
.avatar {
  height: 150px;
  width: 150px;
  display: block;
}
// .el-upload--text {

// }
/deep/ .el-upload--text {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  height: 150px;
  width: 150px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  color: #97a8be;
  font-size: 14px;
  text-align: center;
  .el-icon-upload {
    font-size: 67px;
    color: #97a8be;
    margin: 40px 0 16px;
    line-height: 50px;
  }
  em {
    font-style: normal;
  }
}
.custom_text {
  padding: 0 25px 0 25px;
}
/deep/.quillWrapper .ql-snow.ql-toolbar button svg {
  width: 16px !important;
  height: 16px !important;
}
/deep/ .ql-picker.ql-color-picker svg {
  width: 16px !important;
  height: 16px !important;
}
/deep/ .ql-snow.ql-toolbar button {
  height: 20px;
  width: 20px;
  padding: 2px;
}
/deep/ .quillWrapper .ql-snow.ql-toolbar .ql-formats {
  margin-bottom: 5px;
}
/deep/.ql-toolbar.ql-snow .ql-formats {
  margin-right: 8px;
}
/deep/ .ql-editor {
  font-size: 12px;
}
</style>
