<template>
  <!-- 表单渲染 -->
  <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelView" :visible="visible" :title="title" width="1080px">
    <el-form ref="formViewRef" :model="formData" :rules="rules" :status-icon="true" label-width="240px">
      <el-form-item label="资讯分类：" class="form-cell" style="margin: 0">
        <div class="cell-box" style="display: flex">
          <el-form-item prop="type">
            <el-select v-model="formData.type" placeholder="请选择">
              <el-option v-for="item in dict.information_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item label="标题：" class="form-cell" prop="productName">
        <div class="cell-box">
          <el-input v-model="formData.productName" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>

      <el-form-item v-show="formData.type<4" label="来源：" class="form-cell" prop="productName">
        <div class="cell-box">
          <el-input v-model="formData.productName" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type<4" label="内容：" class="form-cell" prop="productDescribe">
        <div class="cell-box">
          <div ref="editor" class="editor" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type>=4" label="链接：" class="form-cell" prop="productName">
        <div class="cell-box">
          <el-input v-model="formData.productName" placeholder="单行输入" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item v-show="formData.type>=4" label="照片：" class="form-cell" prop="productPic">
        <div class="cell-box">
          <el-upload
            ref="uploadCom"
            action="/api/bsw/product/uploadProductPic"
            name="productPic"
            list-type="picture-card"
            :headers="uploadHeaders"
            :limit="5"
            :on-exceed="handleExceed"
            :on-success="handleImported"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogImageVisible">
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancelView">取消</el-button>
      <el-button type="primary" @click="submitForm()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import { HttpReq } from '@/api/common'
import { mapGetters } from 'vuex'
import { upload } from '@/utils/upload'
import E from 'wangeditor'

export default {
  dicts: ['information_type'],
  data() {
    return {
      uploadHeaders: { 'Authorization': getToken() },
      imgSrcStart: process.env.VUE_APP_BASE_API,
      editor: false, // 富文本对象
      dialogImageUrl: '',
      dialogImageVisible: false,
      visible: false,
      title: '添加资讯信息',
      formData: {
        productId: null,
        customerId: null, // 供应商id
        enterpriseName: '', // 供应商名称
        productName: '', // 产品名称
        productType: '1', // 产品大类
        productSubType: null, // 产品小类
        minPrice: null, // 价格区间-小
        maxPrice: null, // 价格区间-大
        productFeature: null, // 产品特点
        productPic: '', // 产品图片
        productDescribe: '', // 产品描述（富文本）
        notes: null, // 其他说明
        letterOfCommitment: false, // 交易保障承诺
        attributeBrand: '', // 属性-品牌
        attributeConsumptionCurrent: '', // 属性-消耗电流
        attributeProductName: '', // 属性-产品名称
        attributeRatedPower: '', // 属性-额定功率
        attributeModel: '', // 属性-型号
        attributeReactionTime: '', // 属性-反应时间
        attributeWorkingVoltage: '', // 属性-工作电压
        attributeEncapsulation: '', // 属性-封装
        attributeQualityAssurance: '', // 属性-质量保证
        attributeProducingArea: '', // 属性-产地
        attributeNumber: '', // 属性-数量
        attributeColor: '', // 属性-颜色
        attributeApplicableScenarios: '', // 属性-品牌
        attributeBatchNumber: '', // 属性-批号
        rank: '1' // 产品品级
      },
      rules: {}
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  mounted() {
  },
  methods: {
    handleExceed() {
      this.$message({
        message: '超出最大上传数量限制',
        type: 'info'
      })
    },
    handleRemove(file, fileList) {
      HttpReq.backstageApi.deleteProductPic({
        productPic: file.response.productPic
      }).then((res) => {
        this.$notify({
          title: res.msg,
          type: 'success',
          duration: 2500
        })
        const arr = []
        fileList.forEach(item => {
          arr.push(item.response.productPic)
        })
        this.formData.productPic = arr.join(';')
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleImported(response, file, fileList) {
      this.$nextTick(() => {
        const arr = this.formData.productPic ? this.formData.productPic.split(';') : []
        arr.push(response.productPic)
        this.formData.productPic = arr.join(';')
        this.$notify({
          title: '上传成功！',
          type: 'success',
          duration: 2500
        })
      })
    },
    showView() {
      this.visible = true
    },
    hideView() {
      this.$refs.uploadCom.clearFiles()
      this.$refs.formViewRef.resetFields()
      this.editor.txt.clear()
      this.visible = false
    },
    cancelView() {
      this.hideView()
    },
    submitForm() {
      this.$refs.formViewRef.validate(valid => {
        if (valid) {
          HttpReq.backstageApi.addProduct(this.formData).then((res) => {
            this.$notify({
              title: res.msg,
              type: 'success',
              duration: 2500
            })
            if (res.code === 200) {
              this.cancelView()
              this.$parent.loadData()
            }
          })
        } else {
          this.$message({
            message: '表单信息有误，请核对无误后提交！',
            type: 'error'
          })
        }
      })
    },
    changeProductType() {
      this.formData.productSubType = null
      this.productSubTypeOpts = this.dict['product_type_' + this.formData.productType]
    },
    loadData() {
      this.showView()
      if (this.editor) {
        return
      }
      this.$nextTick(() => {
        const _this = this
        const editor = new E(this.$refs.editor)
        editor.config.zIndex = 5
        editor.config.customUploadImg = function(files, insert) {
          files.forEach(image => {
            upload(_this.imagesUploadApi, image).then(res => {
              const data = res.data
              const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
              insert(url)
            })
          })
        }
        editor.config.onchange = (html) => {
          this.formData.productDescribe = html
        }
        editor.create()
        // 初始化数据
        editor.txt.html(this.formData.productDescribe)
        this.editor = editor
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.grid-content {
  border: 1px solid rgba(100, 100, 100, 0.3);
  padding: 0;
}
.grid-label {
  background: #dedede;
  padding: 0 10px;
}
.editor{
  text-align:left;
  width: 680px;
}
::v-deep .w-e-text-container {
  height: 560px !important;
}
.cell-box {
  min-width: 120px;
  .cell-input {
    width: 420px;
  }
  .cell-select {
    width: 220px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 28px;
    line-height: 24px;
    padding: 0 8px;
  }
  .input-new-tag {
    width: 140px;
    height: 28px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  >>>.el-input__inner {
    border: 1px solid rgba(100, 100, 100, 0.1);
    border-bottom: 1px solid rgba(100, 100, 100, 0.2);
    border-radius: 5px;
  }
  >>>.el-input.is-disabled .el-input__inner {
    border-radius: 0;
    border: 0;
    border-bottom: 1px solid rgba(100, 100, 100, 0.4);
    background: white;
    cursor: text;
  }
  >>>.el-input.is-disabled .el-input__icon {
    cursor: text;
  }
  >>>.el-icon-circle-check {
    color: #13ce66;
  }
  //>>>.el-icon-arrow-up:before {
  //  content: '';
  //}
}
</style>
