<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-05-15 16:08:31
 -->
<!--
  <text-edit :categoryId="categoryId" @closeText="closeText" @submitText="submitText"></text-edit>
  import textEdit from '@/components/set/text-edit.vue';
 -->
<template>
  <el-dialog :title="!!editRow.materialId ? '编辑文件' : '新建文件'" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
    <div class="">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文件标题" prop="materialTitle">
          <limitInput :inputWidth="440" :inputValue.sync="ruleForm.materialTitle" :holder="'请输入文件标题'" :getByType="'word'" :maxLength="20"> </limitInput>
        </el-form-item>
        <el-form-item label="文件" prop="link">
          <el-upload class="upload-demo" :action="uploadUrl()" :before-upload="beforeFileUpload" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleRemove" :limit="1" :on-exceed="handleExceed" :file-list="fileDatas">
            <el-button type="primary"><i class="el-icon-upload el-icon--right" style="font-size: 16px;padding-right:5px;"></i>上传</el-button>
            <div slot="tip" class="font-12 color-909399">普通文件，不大于20MB。支持word及excel，pdf，ppt，zip，rar格式</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="toCancel">取消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { emojiArr } from '@/utils/emoji';
export default {
  props: {
    editRow: {
      type: Object,
      default() {
        return {};
      }
    },
    categoryId: {
      type: Object,
      default() {
        return '';
      }
    }
  },
  components: {
    limitInput
  },
  data() {
    return {
      editPersion: localStorage.getItem('userName'),
      dialogVisible: true,
      ruleForm: {
        materialId: '',
        materialTitle: '',
        link: ''
      },
      rules: {
        materialTitle: [{ required: true, message: '请输入文件标题', trigger: 'blur' }],
        link: [{ required: true, message: '请上传文件', trigger: 'blur' }]
      },
      emojiList: emojiArr,
      fileType: '.doc',
      fileDatas: []
    };
  },
  methods: {
    /**
     * 上传url
     */
    uploadUrl() {
      const that = this;
      let host = window.location.origin;
      let baseUrl;
      if (host.indexOf('localhost') != '-1') {
        baseUrl = 'http://www.gicdev.com';
      } else {
        baseUrl = host;
      }
      that.upUrl = baseUrl + `/haoban-manage3-web/upload-file?fileType=${that.fileType}`;
      return that.upUrl;
    },
    /**
     * 附件上传
     *
     */
    beforeFileUpload(file) {
      let that = this;
      const arrName = file.name.split('.');
      const fileExt = arrName[arrName.length - 1];
      const isFiles = fileExt.includes('pdf') || fileExt.includes('doc') || fileExt.includes('xls') || fileExt.includes('ppt') || fileExt.includes('zip') || fileExt.includes('rar');
      const isLt20M = file.size / 1024 / 1024 <= 20;
      if (!isLt20M) {
        that.$message.error('文件大小超出20M，无法上传');
      }
      if (!isFiles) {
        that.$message.error('仅支持word及excle，pdf，ppt，zip，rar格式');
        return false;
      }
      return isLt20M && isFiles;
    },
    handleRemove(file, fileList) {
      // const that = this;
      /* eslint-disable */
      // console.log('del:', file, fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleFileSuccess(res, file) {
      const that = this;
      /* eslint-disable */
      // that.ruleFormData.attachment.push(res.result); // 不能动态修改绑定的fileList 否则只拿到最后一个回调
      that.ruleForm.link = res.result.url;
    },
    handleFileChange(files, fileList) {
      let that = this;
      /* eslint-disable */
      // console.log('handleFileChange:',that.fileDatas)
      that.fileDatas = fileList;
    },
    /**
     * 输入内容
     **/
    handleInput($event) {
      const that = this;
      that.ruleForm.materialContent = $event.target.innerText;
    },
    /**
     * 选中表情
     **/
    selectEmoji(item) {
      const that = this;
      that.ruleForm.materialContent = that.ruleForm.materialContent + item.key;
    },
    toCancel() {
      const that = this;
      that.$emit('closeText');
      that.$refs['ruleForm'].resetFields();
    },
    handleClose(done) {
      const that = this;
      that.$emit('closeText');
      that.$refs['ruleForm'].resetFields();
    },
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        }
      });
    }, 300),
    postSave() {
      const that = this;
      const data = {
        categoryId: that.categoryId,
        materialType: 5,
        materialId: that.ruleForm.materialId,
        materialTitle: that.ruleForm.materialTitle,
        link: that.ruleForm.link
      };
      postRequest(that.ruleForm.materialId ? '/haoban-manage3-web/material-edit' : '/haoban-manage3-web/material-add', data)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['ruleForm'].resetFields();
            that.$emit('submitText');
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(error => {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    editRow(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.ruleForm = JSON.parse(JSON.stringify(newData));
        that.fileDatas = [{
          name: newData.link.split('/')[5],
          url: newData.link
          }
        ];
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.editRow).length) {
      that.ruleForm = JSON.parse(JSON.stringify(that.editRow));
      that.fileDatas = [{
          name: that.editRow.link.split('/')[5],
          url: that.editRow.link
          }
        ];
    }
  }
};
</script>
<style lang="less" scoped>
.m-b-20 {
  margin-bottom: 20px;
}
.p-l-18 {
  padding-left: 18px;
}
.material-content {
  position: relative;
  .material-body {
    /*  resize: none;
    width: 440px;
    height: 273px;
    border-radius: 2px;
    border: 1px solid rgba(196, 198, 207, 1); */
    .el-textarea {
      ::v-deep .el-textarea__inner {
        height: 273px;
      }
    }
  }
  .emoji-img {
    position: absolute;
    left: 10px;
    bottom: 10px;
  }
}
.el-textarea {
  ::v-deep .el-textarea__inner {
    height: 273px;
  }
}
.el-form-item {
  ::v-deep .upload-demo {
    .el-upload-list__item-name:hover {
      color: #2f54eb;
    }
  }
}
</style>
