<template>
  <div class="goods-list bg_c_white radius_10">
    <toptitle name="功能反馈"></toptitle>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      
      <el-form-item label="类型：" prop="status">
         <el-select class="input" clearable v-model="ruleForm.status" placeholder="请选择类型">
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.type"
              :value="item.id"
            ></el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="内容：" prop="content" width="100">
        <el-input  type="textarea" 
        rows="5" 
        v-model="ruleForm.content" 
        placeholder="请输入内容"
        maxlength="250"
        show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="图片：">
              <ul class="el-upload-list el-upload-list--picture-card">
                  <li class="el-upload-list__item is-ready"
                  v-for="(item,index) in imgsJson.supMainImgs" :key="index"
                  >
                    <div>
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="item.url" alt="">
                    </div>
                    <!-- 操作按钮 -->
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handlePictureCardPreview(item)">
                        <i class="el-icon-view"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(item,'supMainImgs',index)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </li>
                  <li class="el-upload-list__item is-ready" style="border:none;">

            <el-upload
            
                accept="image/jpeg,image/jpg,image/png"
                :action="uploadData.host|| '' "
                :data="uploadData"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-success="(response, file, fileList) => handleSuccess(response, file, fileList)"
                 :on-error="onError"
                :on-remove="(file) => handleRemove(file,'supMainImgs')" 
                :show-file-list="false"
                :on-exceed="(files,fileList) => handleExceed(files,fileList,'supMainImgs')"
                :before-upload="(file) => beforeUpload(file,'supMainImgs',)"
                :file-list="imgsJson.supMainImgs"
                :before-remove="handleError"
                :limit="10"
                multiple
                >
                <!--  :show-file-list="false" 隐藏状态. 
                :file-list="imgsJson.supMainImgs" 必须加上这一行，才能在删除图片后，再次上传图片，有超出提示-->
                
                <i class="el-icon-plus"></i>

              </el-upload>
              </li>
          </ul>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>

import toptitle from '@/components/common/topTitle'
import { _uuid, _getOssToken, _supplierId, _deepClone, _deal,_getStorage } from '@/utils/utils'
import Validate from '@/utils/verification'
import FileVerification from "@/utils/FileVerification"
export default {
  data() {
    return {
      uploadData: {keys:[],successNum:0,beforeNum:0}, // 临时存放上传文件
      imgsJson:{
        supMainImgs: [],
      },
      ruleForm:{
        status:'',
        content: '',
      },
      rules: {
          status:[
              { required: true, message: '请选择类型', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '请输入内容', trigger: 'blur' },
          ],
      },
      dialogImageUrl: '',
      dialogVisible: false,

       statusList: [
        {
          value: 1,
          label: "功能反馈"
        },
        {
          value: 2,
          label: "优化反馈"
        },
        {
          value: 3,
          label: "销售规格"
        },
        {
          value: 4,
          label: "类目标签"
        },
        {
          value: 5,
          label: "其他反馈"
        }
      ],
    };
  },
  computed: {

  },
  mounted() {
    this.getType()
  },
  methods: {
    onError(err,file,fileList){
      this.loadingEnd(1)
    },
      getType() {
      this.$axios.get("/feedBack/typeList").then(r => {
        let { code, data,msg } = r.data;
        if(code == 200){
          this.statusList = data;
        }else{
          this.$message.error(msg)
        }
      })
    },
      loadingStart(tx){
      this.loading = this.$loading({
        lock: true,
        text: tx?tx:'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    loadingEnd(type){
      if(type){
        this.$message.error('网络异常,请重新上传试试！')
      }
      this.loading.close()
    },
    // 处理已上传的图片
    pictureFun() {
       let imgsJson = {}
       for(let k in this.imgsJson){
          let o = this.imgsJson[k]
          let arr = []
          if(typeof(o) == 'object' && o  instanceof Array){
            o.map(r => {
              arr.push(r.url?r.url:r)
            })
            imgsJson[k] = arr.join(',')
          }else{
            imgsJson[k] = o
          }
        }
        return imgsJson
    },
    submitForm(formName) {

        this.$refs[formName].validate((valid) => {
          if (valid) {
            const images = this.pictureFun();
               let { brandId } = _getStorage('info');
              this.$axios.post("/feedBack/insert",{
                  funType:this.ruleForm.status,
                  funTontent:this.ruleForm.content,
                  img:images.supMainImgs,
                  brandId:brandId,
                  status:1
              }).then(r => {
                let { code, data,msg } = r.data;
                if(code == 200){
                   this.$message.success(msg)
                   this.$router.push({
                     path:'/help/feedback'
                   })
                }else{
                  this.$message.error(msg)
                }
              })
           

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },


      resetForm(formName) {
        this.imgsJson.supMainImgs =[]
        this.$refs[formName].resetFields();
      },
      handleRemove(file, label,idx) {
      
      let fileList = _deepClone(this.imgsJson[label])
      let index = fileList.indexOf(file);

      this.imgsJson[label].splice(idx,1)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
       handleExceed(files, fileList,label) {
 
      this.$message.warning(`超出限制文件个数`);

    },
    beforeUploadCheck(file,label){
      let self = this
      const fv = new FileVerification(file);
      const rules = {
        'supMainImgs':{
          // vSize:512,
          // vImgWH:[800,800]
        },
       
      }
      async function getResult(rule){
        let res = true
        for(let i in rule){
          let val = rule[i]
          if(['vImgPercentage','vImgWH','vImgW','vImgH'].indexOf(i) != -1){
            let r = await fv[i](val[0],val[1])
            res = r
          }else{
            res = fv[i](val)
          }
        }
        return res
      }

      return getResult(rules[label])

    },
    beforeUploadErr(){
        this.uploadData.keys = []
        this.uploadData.successNum = 0
        this.uploadData.beforeNum = 0
    },
    beforeUpload(file,label) {
      this.uploadData.beforeNum += 1
      this.uploadData['label'] = label // 上传位置标识

      // 文件上传
      return new Promise((resolve, reject) => {

        // 校验上传文件属性
        this.beforeUploadCheck(file,label).then(res => {
          if(!res){
            this.$notify.error(
              "请按要求上传文件"
            );
            this.beforeUploadErr()
            reject();
          }else if (typeof(res) == 'object' && !res.result) {
            let err = res.h?res.w + "*" + res.h:res.w
            this.beforeUploadErr()
            this.$notify.error(
              "请上传" + err + "像素的图片格式文件"
            );
            reject();
          }else{
            this.loadingStart()

            _getOssToken.call(this, null).then((res) => {
              let fileExt = /\.[^\.]+$/.exec(file.name);
              let uuid = _uuid()
              let uploadData = this.uploadData
              this.uploadData = {...uploadData, ...res};

              this.uploadData.key = 'ROOT/ETao/gl/' + uuid + fileExt;
              this.uploadData.keys.push('ROOT/ETao/gl/' + uuid + fileExt)
              resolve();

            }).catch((err) => {
              reject(err)
            })

          }
        });

      })
    },
    handleError(file, fileList){

      console.log('cuowu--',file,fileList);
      // 处理加上校验后删除前一个已上传文件的问题
      return false
    },
     handleSuccess(response, file, fileList, supMainImgsIndex){
      // 文件上传
      let filterSku = v => {
        // 过滤需要修改
        return v.key == this.skuImageKey;
      };
      let { label, host, keys } = this.uploadData
      let successNum = this.uploadData.successNum += 1

      if( successNum == this.uploadData.beforeNum ){
        keys.map(key => {
          if(label === 'mainImg'){
            // sku图
            this.skuList.filter(filterSku)[0].mainImg = host + "/" + key
          }
          else{
            if(label === 'video' || label === 'model3D'){
              this.imgsJson[label] = [{"url":host + "/" + key,"name":host + "/" + key}]
            }else{
              // 多图
              this.imgsJson[label].push({"url":host + "/" + key,"name":host + "/" + key})
            }
          }
        })

        this.uploadData.keys = []
        this.uploadData.successNum = 0
        this.uploadData.beforeNum = 0
        this.loadingEnd()
      }


    },
  },
  components: {
    toptitle
  }
};
</script>

<style lang="scss" scoped>
.goods-list {
  color: #333333;
  padding: 20px;
}
</style>
