<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.ptsid ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" width="75%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
          <el-form-item label="产品名称" prop="title">
          <el-input v-model="dataForm.title" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="产品类型" prop="typeid"  class="type-list">
          <el-popover v-model="typeListVisible" ref="typeListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="typeList"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            ref="typeListTree"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="typeListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.type" v-popover:typeListPopover :readonly="true" placeholder="类型">
        </el-input>
      </el-form-item>
      <el-form-item label="产品主图" prop="thumbnail">
            <upload-img ref="uploadImg"></upload-img>
      </el-form-item>
          <el-form-item label="产品展示" prop="content">
            <upload-imgs ref="uploadImgs"></upload-imgs>
      </el-form-item>
      <el-form-item label="产品描述" prop="content">
          <editor ref="editor"></editor>
      </el-form-item>
          <el-form-item label="产品优势" prop="content1">
          <el-input v-model="dataForm.content1" placeholder="产品优势"></el-input>
      </el-form-item>
          <el-form-item label="产品特点" prop="content2">
          <el-input v-model="dataForm.content2" placeholder="产品特点"></el-input>
      </el-form-item>
          <el-form-item label="产品参数" prop="content3">
          <el-input v-model="dataForm.content3" placeholder="产品参数"></el-input>
      </el-form-item>
          <el-form-item label="价格" prop="price">
          <el-input v-model="dataForm.price" placeholder="价格"></el-input>
      </el-form-item>
          <el-form-item label="市场价" prop="nprice">
          <el-input v-model="dataForm.nprice" placeholder="市场价"></el-input>
      </el-form-item>
          <el-form-item label="数量" prop="quantity">
          <el-input v-model="dataForm.quantity" placeholder="数量"></el-input>
      </el-form-item>
        </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Editor from '../utils/editor'
import UploadImgs from '../utils/upload-imgs'
import UploadImg from '../utils/upload-img'


export default {
  data () {
    return {
      visible: false,
      typeListVisible:false,
      typeList:[],
      dataForm: {
        ptsid: '',
        title: '',
        content: '',
        content1: '',
        content2: '',
        content3: '',
        price: '',
        nprice: '',
        quantity: '',
        typeid: '',
        creator: '',
        taix: '',
        thumbnail: '',
        count: '',
        createDate: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        title: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content1: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content2: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content3: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        price: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        nprice: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        typeid: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        thumbnail: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        count: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()

        this.getTypeList().then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }else{
            this.$refs['editor'].content = "";
            this.$refs['uploadImgs'].uploadList = [];
            this.$refs['uploadImg'].imgSrc = "";
          }
        })

      })
    },
    toHtml(content) {
      if (!content) return ''
      return content.replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&amp;/g, "&")
        .replace(/&quot;/g, '"')
        .replace(/&apos;/g, "'");
    },

    // 获取类型列表
    getTypeList () {
      return this.$http.get('/cniyv/cniyvproducttype/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.typeList = res.data
      }).catch(() => {})
    },
    // 上级菜单树, 选中
    typeListTreeCurrentChangeHandle (data) {
      this.dataForm.typeid = data.ptsid
      this.dataForm.type = data.name
      this.typeListVisible = false
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/cniyv/cniyvproduct/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }

        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }

        this.$refs.typeListTree.setCurrentKey(this.dataForm.typeid)

        this.$refs['editor'].content = this.toHtml(this.dataForm.content);

        if(this.dataForm.imgs){
          this.$refs['uploadImgs'].uploadList = this.dataForm.imgs.split(",");
        }
        this.$refs['uploadImg'].imgSrc = this.dataForm.thumbnail;
        console.log(this.$refs['uploadImg'])
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        console.log(this.$refs['editor'].content)
        this.dataForm.content =  encodeURIComponent(this.$refs['editor'].content)
        this.dataForm.imgs = this.$refs['uploadImgs'].uploadList.join(",")
        this.dataForm.thumbnail =  this.$refs['uploadImg'].imgSrc
        this.$http[!this.dataForm.ptsid ? 'post' : 'put']('/cniyv/cniyvproduct/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  },
  components: {
    Editor,
    UploadImgs,
    UploadImg 
  }
}
</script>

<style lang="scss">
  .type-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
</style>
