<template>
  <div>
    <div>
      <!-- <Navbar title="创建评论" /> -->
      <div>
        <div class="form-group">
          <label for="exampleInputEmail2">主题</label>
          <a-input
            v-model:value="theme"
            autocomplete="off"
            type="text"
            class="form-control"
          />
        </div>

        <div class="form-group">
          <label for="exampleInputEmail2">评论内容</label>
          <EditorWidget v-model="content" :class-name="className" />
        </div>

        <div class="form-group">
          <label for="exampleInputEmail2">通知人</label>
          <a-select
            v-model:value="userIds"
            mode="multiple"
            style="width: 100%"
            placeholder="选择通知人"
            :options="options"
            :filter-option="false"
            auto-clear-search-value
            @change="handleChange"
            @search="listInGroupCompanyByCondition"
          />
        </div>

        <div>
          <input
            ref="fileInput"
            autocomplete="off"
            type="file"
            class="file-input"
            @change="onFileChanges"
          />
          <a-button type="primary" @click="clickButton">
            <UploadOutlined />
            上传附件
          </a-button>
        </div>

        <div style="margin-top: 10px">
          <ul class="list-box">
            <li v-for="item in files" :key="item" class="list-item">
              {{ item }}
              <a-space>
                <a-button type="link" class="badge" @click="download(item)">下载</a-button>
                <a-button type="link" danger class="badge" @click="removeFile(item)">删除</a-button>
              </a-space>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>
<script>
import UpladFile from '../../common/UpladFile.js';

import Common from '../../common/Common.js';
import { Notify } from 'pc-component-v3';
import { DownloadService } from 'pc-component-v3';
import UserResource from '../../api/base/UserResource.js';
import EditorWidget from '../../widget/EditorWidget.vue';
import { UploadOutlined } from '@ant-design/icons-vue';

export default {
  components: {
    UpladFile,
    EditorWidget,
    UploadOutlined,
  },

  props: {
    recordId: {
      type: String,
      default: null,
    },

    windowNo: {
      type: String,
      default: null,
    },
  },

  data: function () {
    return {
      content: '',
      images: [],
      className: 'com.leanwo.prodog.system.model.CurdWindowComment',
      files: [],
      commentDto: {},
      loading: false,
      options: [],
      userIds: [],
      theme: '',
    };
  },

  mounted: function () {
    var _self = this;
    $('.input-tan').focus(function () {
      document.activeElement.blur();
    });
    this.listInGroupCompanyByCondition(null);
  },
  beforeUnmount: function () {
   
  },
  methods: {
    /**
     * 根据姓名获取抄送人用户集合
     */
    listInGroupCompanyByCondition: function (search) {
      let _self = this;
      const searchQueryParam = {
        range: {
          start: 0,
          length: 1000,
        },
        conditional: search,
      };

      var userDtos = [];
      UserResource.listInGroupCompanyByCondition(searchQueryParam).then(
        successData => {
          if (successData != null && successData.resultList != null) {
            successData.resultList.forEach(function (user) {
              var userDto = {};

              user.text = user.name + '(';
              if (user.organizations != null && user.organizations.length > 0) {
                let isFirst = true;
                user.organizations.forEach(item => {
                  if (isFirst === true) {
                    user.text += item.organizationName;
                    isFirst = false;
                  } else {
                    user.text += ',' + item.organizationName;
                  }
                });
              }
              user.text += ')';

              userDto.value = user.id;
              userDto.label = user.text;
              userDtos.push(userDto);
            });
            _self.options = userDtos;
            console.log(_self.options);
          } else {
            _self.options = [];
            console.log(_self.options);
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    handleChange(value) {
      let _self = this;
      console.log(this.userIds);
      _self.listInGroupCompanyByCondition(null);
    },

    /**
     * 点击上传按钮事件
     * @return {[type]} [description]
     */
    clickButton: function () {
      $(this.$refs.fileInput).click();
    },

    //----------文件------------
    /**
     * 删除文件
     * @param  {String} item 文件Name
     */
    removeFile: function (index) {
      var _self = this;
      _self.files.splice(index, 1);
    },
    /**
     * 选择文件发生改变
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    onFileChanges: function (e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.uploadFile(files[0]);
    },

    /**
     * 上传文件
     * @param  {File} selectedFile 选择的文件
     */
    uploadFile: function (selectedFile) {
      var _self = this;
      if (selectedFile == undefined) {
        return;
      }
      var size = undefined;
      if (
        _self.commentDto.commentAttachmentSize != undefined &&
        _self.commentDto.commentAttachmentSize != null
      ) {
        size = _self.commentDto.commentAttachmentSize;
      }
      //当系统没有配置附件大小时默认8m
      if (size == undefined) {
        size = 8;
      }
      if (selectedFile.size != undefined && selectedFile.size != null) {
        if (selectedFile.size / 1024 <= 1024 * size) {
          var formData = new FormData();
          formData.append('files', selectedFile);
          formData.append('className', _self.className);
          _self.loading = true;
          $.ajax({
            url: Common.getApiURL('file/classFileUpload'),
            type: 'post',
            beforeSend: function (request) {
              Common.addTokenToRequest(request);
            },
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
              _self.loading = false;
              if (data.errorCode == 0) {
                if (data.datas) {
                  var fileName = data.datas[0];
                  _self.files.push(fileName);
                }
              } else {
                Notify.error('提示', data.errorMessage);
              }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              _self.loading = false;
              Common.processException(XMLHttpRequest, textStatus, errorThrown);
            },
          });
        } else {
          Notify.error(
            '提示',
            '文件大小不能超过' + size + 'M，可在任务配置功能中配置！',
          );
        }
      } else {
        Notify.error('提示', '上传的文件为空！');
      }
    },
    /**
     * 获取文件地址
     * @param  {String} item 图片名称
     * @return {String}      图片URL地址
     */
    getFileSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getResourceUrl('file', _self.className, item);
      } else {
        return '';
      }
    },

    /**
     * 下载文件
     * @param  {String} fileName 文件名
     * @return {void}
     */
    download: function (fileName) {
      var _self = this;
      DownloadService.fileDownload(_self.className, fileName);
    },


    /**
     * 保存评论表数据
     * @author GuoZhiBo 20171201
     */
    photograph: function () {
      var _self = this;
      
      if (_self.content != '' && _self.content != null) {
        var curdComment = {
          recordId: _self.recordId,
          content: _self.content,
          attachments: _self.files.join(','),
          carbonCopyUserIds: _self.userIds.join(','),
          windowNo: _self.windowNo,
          theme: _self.theme,
        };
        _self.loading = true;
        $.ajax({
          url: Common.getApiURL(
            'CurdWindowCommentResource/saveCurdWindowComment',
          ),
          type: 'post',
          contentType: 'application/json',
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          data: JSON.stringify(curdComment),
          success: function (data) {
            _self.loading = false;
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading = false;
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      } else {
        Notify.error('提示', '请填写评论内容！');
      }
    },

    // 获取通知(供外部调用)
    getNotification: function () {
      var _self = this;
      var contentText = _self.content;
      if (contentText.indexOf('<img src=') != -1 || _self.files.length > 0) {
        contentText = '您有份文件评论，请在“待审阅”中查看。';
      } else {
        var regex = /<[^>]+>/g;
        contentText = contentText.replace(regex, '');
      }
      console.log(contentText);
      var notification = {
        userIds: _self.userIds,
        theme: _self.theme,
        contentText: contentText,
      };
      return notification;
    },
  },
};
</script>
<style scoped>
.mui-divs3 {
  margin-top: 10px;
}

.file-input {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.list-box {
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
  padding-left: 0;
  margin-bottom: 20px;
}

.list-item {
  position: relative;
  display: block;
  padding: 10px 15px;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid #ddd;
  display: flex;;
  align-items: center;
  justify-content: space-between;
}

.list-item > .badge {
  float: right;
  margin-left: 10px;
}

</style>