<template>
  <div>
    <div v-if="$api.isLook !== '1'">
      <a-textarea
          class='mb5'
          :placeholder="$t('risk-analysis.review-comments.click-to-add-review-comments')"
          v-model='addComments'
          :autoSize='{ minRows: 3 }'
          :maxLength='300'>
      </a-textarea>
      <div class='commentsUpload'>
        <a-upload
            name='file'
            action=''
            accept='.jpg,.txt,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx'
            :fileList='addFileList'
            :customRequest='addUploadFile'
            :remove='addRemoveFile'>
          <a-button :loading='addUploadFileLoading'>
            <a-icon type="upload"/>
            {{ $t('global-btn.select-file') }}
          </a-button>
        </a-upload>
      </div>
      <a-button
          type='primary'
          v-if="this.$api.isLook !== '1'"
          @click="saveComments('',addComments,addFileList)"
          :loading='saveLoading'
          class="mt5 mb10 fr zin99">
        {{ $t('global-btn.confirm') }}
      </a-button>
    </div>
    <div>
      <a-table
          :columns='tableColumns'
          :data-source='tableData'
          bordered
          size="small"
          :loading="tableLoading"
          :scroll="{ x: '100%', y: 'calc(88vh - 400px)' }"
          :pagination='pagination'
          @change='handleOuterTableChange'>
        <template slot='userName' slot-scope='text, row'>
          {{ row.userName }}
        </template>
        <template slot="state" slot-scope='text, row'>
          {{ row.state == 0 ? $t('global-btn.submit') : $t('global-btn.close')}}
        </template>
        <template slot='comments' slot-scope='text, row'>
          <span :title=row.comments>{{ row.flag === 0 || row.flag === 4 ? row.comments : '' }}</span>
          <a-textarea
              v-if='row.flag === 3'
              v-model='row.comments'
              :autoSize='{ minRows: 2 }'
              :placeholder="$t('risk-analysis.review-comments.click-to-add-review-comments')"
              :maxLength='300'>
          </a-textarea>
          <div v-if='row.flag === 0'>
          <span style='font-size:15px;display:block'
                v-for='(item, index) in row.fmeaCommentsFileBOS'
                :key='index'>
            <a-icon type="paper-clip"/>
            <a style='color:#1890FF'
               :href="$api.requestUrl + '/DFMEA/file/downloadFile.do?id=' +item.id + '&fileType=01'">
              {{ item.fileName }}
            </a>
          </span>
          </div>
          <div v-else-if='row.flag === 3'>
            <div>
            <span
                style='font-size:15px;display:block'
                v-for='(item, index) in row.fmeaCommentsFileBOS'
                :key='index'>
              <a-icon type="paper-clip"/>
              {{ item.fileName + '\xa0\xa0\xa0' }}
              <a-tooltip placement='right'>
                <template slot='title'>{{ $t('global-btn.delete-file') }}</template>
                <span @click='deleteFile(row.fmeaCommentsFileBOS,item)' style='float:right'>
                  <a-icon style='cursor: pointer' type='delete'/>
                </span>
              </a-tooltip>
            </span>
            </div>
            <div>
              <a-upload
                  name='file'
                  action=''
                  accept='.jpg,.txt,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx'
                  :customRequest='editUploadFile'
                  :fileList='editFileList'
                  :remove='editRemoveFile'>
                <a-button
                    :loading='editUploadFileLoading'
                    class="mt5 mb10">
                  <a-icon type="upload"/>
                  {{ $t('global-btn.upload-file') }}
                </a-button>
              </a-upload>
            </div>
          </div>
        </template>
        <template slot='closeReason' slot-scope='text, row'>
          <span :title="row.closeReason">{{ row.state === 1 && row.flag != 4 ? row.closeReason : '' }}</span>
          <a-textarea
              v-if='row.flag === 4'
              v-model='row.closeReason'
              :autoSize='{ minRows: 2 }'
              :placeholder="$t('functional-analysis.review-comments.click-to-add-close-reason')"
              :maxLength='100'>
          </a-textarea>
        </template>
        <template slot='operation' slot-scope='text, row'>
          <div v-if='row.isOperation === 1'>
            <div v-if="row.flag === 0 && row.state == 0">
              <!-- 编辑 -->
              <a class="operate-btn"
                 :disabled="!($api.isLook !== '1') || isEdit"
                 @click="reEdit(row)">
                <a-tooltip :title="$t('global-btn.edit')">
                  <i class="iconfont iconicon-bainji"></i>
                </a-tooltip>
              </a>
              <a class="ml10 operate-btn"
                 :disabled="!($api.isLook !== '1') || isEdit"
                 @click="deleteComments(row)">
                <!-- 删除 -->
                <a-tooltip :title="$t('global-btn.delete')">
                  <i class="iconfont iconshanchu"/>
                </a-tooltip>
              </a>
              <!-- 关闭 -->
              <a v-if="row.closeOperation == 1" class="ml10 operate-btn"
                 :disabled="isEdit"
                 @click="close(row)">
                <a-tooltip :title="$t('global-btn.close')">
                  <a-icon type="close-circle"/>
                </a-tooltip>
              </a>
            </div>
            <div v-if="row.flag === 0 && row.state == 1 && row.closeOperation == 1">
              <!-- 提交 -->
              <a class="ml10 operate-btn"
                 :disabled="isEdit"
                 @click="openComents(row.id)">
                <a-tooltip :title="$t('global-btn.reOpen')">
                  <a class="icon iconfont iconchehui"></a>
                </a-tooltip>
              </a>
            </div>
            <div v-else-if='row.flag === 3'>
              <!-- 保存 -->
              <a class="operate-btn"
                 @click="saveComments(row.id,row.comments,[...editFileList,...row.fmeaCommentsFileBOS])">
                <a-tooltip :title="$t('global-btn.save')">
                  <a-icon type="check"/>
                </a-tooltip>
              </a>
              <a class="ml10 operate-btn" @click="cancel(row)">
                <!-- 取消 -->
                <a-tooltip :title="$t('global-btn.cancel')">
                  <a-icon type="undo"/>
                </a-tooltip>
              </a>
            </div>
            <!--更新评审意见-->
            <div v-else-if='row.flag === 4'>
              <!-- 保存 -->
              <a class="operate-btn"
                 @click="closeComments(row.id,row.closeReason)">
                <a-tooltip :title="$t('global-btn.save')">
                  <a-icon type="check"/>
                </a-tooltip>
              </a>
              <a class="ml10 operate-btn" @click="closeCancel(row)">
                <!-- 取消 -->
                <a-tooltip :title="$t('global-btn.cancel')">
                  <a-icon type="undo"/>
                </a-tooltip>
              </a>
            </div>
          </div>
          <div v-else="row.isOperation != 1" >
            <div v-if="row.flag === 0 && row.state == 0 && row.closeOperation == 1">
              <!-- 禁用 -->
              <a class="ml10 operate-btn"
                 :disabled="isEdit"
                 @click="close(row)">
                <a-tooltip :title="$t('global-btn.close')">
                  <a-icon type="close-circle"/>
                </a-tooltip>
              </a>
            </div>
            <div v-if="row.flag === 0 && row.state == 1 && row.closeOperation == 1">
              <!-- 提交 -->
              <a class="ml10 operate-btn"
                 :disabled="isEdit"
                 @click="openComents(row.id)">
                <a-tooltip :title="$t('global-btn.reOpen')">
                  <a class="icon iconfont iconchehui"></a>
                </a-tooltip>
              </a>
            </div>
            <!--更新评审意见-->
            <div v-else-if='row.flag === 4'>
              <!-- 保存 -->
              <a class="operate-btn"
                 @click="closeComments(row.id,row.closeReason)">
                <a-tooltip :title="$t('global-btn.save')">
                  <a-icon type="check"/>
                </a-tooltip>
              </a>
              <a class="ml10 operate-btn" @click="closeCancel(row)">
                <!-- 取消 -->
                <a-tooltip :title="$t('global-btn.cancel')">
                  <a-icon type="undo"/>
                </a-tooltip>
              </a>
            </div>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>

export default {
  name: 'AddReviewComments',
  components: {},
  props: {
    checkedNode: {
      type: Object
    }
  },
  data() {
    return {
      /** 新增评审意见 */
      addComments: '',
      /** 新增评审意见时，文件上传Loading */
      addUploadFileLoading: false,
      /** 新增评审意见时，文件上传集合 */
      addFileList: [],
      /** 是否编辑 */
      isEdit: false,
      /** 编辑评审意见 */
      editComments: '',
      /** 编辑评审意见时，文件上传Loading */
      editUploadFileLoading: false,
      /** 编辑评审意见时，文件上传集合 */
      editFileList: [],
      /** 保存Loading */
      saveLoading: false,
      /** 列表查询 */
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        struId: this.checkedNode.id,
        fmeaId: this.$store.getters.fmeaId,
        rfmeaId: this.$store.getters.rfmeaId,
        rfmeaType: 'D'
      },
      /** 表格分页 */
      pagination: {
        disabled: false,
        current: 1, // 当前页数
        pageSize: 10, // 每页条数
        showTotal: total => this.$t('global-constant.table.show-total', [total]), //用于显示数据总量和当前数据顺序
        showSizeChanger: true, // 是否可以改变 pageSize
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 指定每页可以显示多少条
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // pageSize 变化的回调
        total: 0 // 总条数
      },
      /** 表格Loading */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 表格缓存数据 */
      tableCacheData: [],
      /** 表格表头 */
      tableColumns: [
        {
          dataIndex: 'userName',
          key: 'userName',
          align: 'center',
          title: () => this.$t('risk-analysis.review-comments.judges'),
          width: 100,
          ellipsis: true
        },
        {
          dataIndex: 'comments',
          key: 'comments',
          align: 'center',
          title: () => this.$t('risk-analysis.review-comments.review-comments'),
          width: 300,
          scopedSlots: {customRender: 'comments'},
          ellipsis: true
        },
        {
          dataIndex: 'insertTime',
          key: 'insertTime',
          title: () => this.$t('risk-analysis.review-comments.date'),
          align: 'center',
          width: 120,
          ellipsis: true
        },
        {
          dataIndex: 'state',
          key: 'state',
          title: () => this.$t('functional-analysis.top-modal.status'),
          align: 'center',
          scopedSlots: {customRender: 'state'},
          width: 120,
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.review-comments.close-reason'),
          align: 'center',
          scopedSlots: {customRender: 'closeReason'},
          width: 300,
          ellipsis: true
        },
        {
          dataIndex: 'closeUserName',
          key: 'closeUserName',
          title: () => this.$t('functional-analysis.review-comments.closeUserName'),
          align: 'center',
          width: 120,
          ellipsis: true
        },
        {
          dataIndex: 'closeTime',
          key: 'closeTime',
          title: () => this.$t('functional-analysis.review-comments.close-time'),
          align: 'center',
          width: 120,
          ellipsis: true
        },
        {
          key: 'operation',
          title: () => this.$t('risk-analysis.review-comments.operate'),
          align: 'center',
          scopedSlots: {customRender: 'operation'},
          width: 120,
          ellipsis: true
        }
      ],
    };
  },
  watch: {},
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 初始化列表
     */
    list() {
      let _that = this;
      _that.tableLoading = true;
      this.$api.getComments(_that.listQuery).then((res) => {
        if (res.flag) {
          _that.tableData = res.data.data || [];
          _that.tableCacheData = res.data.data.map(item => ({...item}));
          _that.pagination.total = res.data.total || 0;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        this.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.tableLoading = false;
      });
    },
    /**
     * 新增评审意见时，文件上传
     * @param obj 回调对象
     */
    addUploadFile(obj) {
      let _that = this;
      if (obj.file.size > 10485760) {
        _that.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      _that.addUploadFileLoading = true;
      let fd = new FormData();
      fd.append('file', obj.file);
      fd.append('fileType', '01');
      _that.$api.uploadFile(fd).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.addFileList.push({
            name: res.data.fileName,
            fileName: res.data.fileName,
            filePath: res.data.filePath,
            fileSize: res.data.fileSize,
            newFileName: res.data.newFileName,
            uid: obj.file.uid
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.addUploadFileLoading = false;
      });
    },
    /**
     * 编辑评审意见时，文件上传
     * @param obj 回调对象
     */
    editUploadFile(obj) {
      let _that = this;
      if (obj.file.size > 10485760) {
        _that.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      _that.editUploadFileLoading = true;
      let fd = new FormData();
      fd.append('file', obj.file);
      fd.append('fileType', '01');
      _that.$api.uploadFile(fd).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.editFileList.push({
            name: res.data.fileName,
            fileName: res.data.fileName,
            filePath: res.data.filePath,
            fileSize: res.data.fileSize,
            newFileName: res.data.newFileName,
            uid: obj.file.uid
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.editUploadFileLoading = false;
      });
    },
    /**
     * 新增评审意见时，文件删除
     * @param file 文件
     */
    addRemoveFile(file) {
      let files = this.addFileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) files.splice(i, 1);
      }
    },
    /**
     * 编辑评审意见时，文件删除
     * @param file 文件
     */
    editRemoveFile(file) {
      let files = this.editFileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) files.splice(i, 1);
      }
    },
    /**
     * 编辑评审意见时：删除已上传文件
     * @param files 文件集合
     * @param row 表格行数据
     */
    deleteFile(files, row) {
      for (let i = files.length - 1; i >= 0; i--) {
        if (row.id === files[i].id) files.splice(i, 1);
      }
    },
    /**
     * 评审意见：保存
     */
    saveComments(id, comments, fileList) {
      let _that = this;
      if (!comments) {
        _that.$message.warning(this.$t('global-message.warn.please-enter-review-comments'));
        return;
      }
      _that.saveLoading = true;
      _that.$api.saveComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        struId: _that.checkedNode.id,
        id: id ? id : undefined,
        comments: comments,
        fmeaAddCommentsFileVOS: fileList
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
          if (!id) {
            _that.addComments = '';
            _that.addFileList = [];
          } else {
            _that.editComments = '';
            _that.editFileList = [];
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        this.isEdit = false;
        this.pagination.disabled = false;
        _that.saveLoading = false;
      });
    },
    /**
     * 关闭
     */
    closeComments(id,closeReason) {
      let _that = this;
      _that.saveLoading = true;
      _that.$api.updateComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        struId: _that.checkedNode.id,
        id: id ? id : null,
        flag: 1, //1表示关闭
        closeReason: closeReason,
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.isEdit = false;
        _that.pagination.disabled = false;
        _that.saveLoading = false;
      });
    },
    /**
     * 重新打开
     */
    openComents(id) {
      let _that = this;
      _that.saveLoading = true;
      _that.$api.updateComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        struId: _that.checkedNode.id,
        id: id ? id : null,
        flag: 0, //0表示提交
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.isEdit = false;
        _that.pagination.disabled = false;
        _that.saveLoading = false;
      });
    },
    /**
     * 表格 - 点击分页中数字触发的方法
     */
    handleOuterTableChange(pagination) {
      this.listQuery.pageSize = pagination.pageSize;
      this.listQuery.pageNo = pagination.current;
      this.pagination.current = pagination.current;
      this.list();
    },
    /**
     * 重新编辑
     * @param row 表格行数据
     */
    reEdit(row) {
      this.isEdit = !this.isEdit;
      this.pagination.disabled = true;
      row.flag = 3;
    },
    /**
     * 取消
     * @param row 表格行数据
     */
    cancel(row) {
      const newTableData = [...this.tableData];
      const target = newTableData.find(item => row.id === item.id);
      if (target) {
        Object.assign(target, this.tableCacheData.find(item => row.id === item.id));
        this.tableData = newTableData;
      }
      this.editFileList = [];
      this.isEdit = !this.isEdit;
      this.pagination.disabled = false;
      row.flag = 0;
    },
    /**
     * 评审意见：删除
     * @param row 表格行数据
     */
    deleteComments(row) {
      let _that = this;
      // 如果 删除的是最后一条，并且不是第一页的最后一条，则自动向上一页跳转
      if (_that.tableData.length === 1 && _that.listQuery.pageNo !== 1) {
        _that.listQuery.pageNo -= 1;
      }
      _that.$confirm({
        title: _that.$t('global-message.warn'),
        content: _that.$t('global-message.warn.sure-delete'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: _that.$t('global-btn.ok'),
        cancelText: _that.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          _that.$api.deleteComments({
            rfmeaId: _that.$store.getters.rfmeaId,
            fmeaId: _that.$store.getters.fmeaId,
            id: row.id,
            struId: _that.checkedNode.id,
            lastEntry: _that.pagination.total === 1
          }).then((res) => {
            if (res.flag) {
              _that.$message.success(res.message, 1);
              _that.list();
            }
          }).catch(error => {
            _that.$message.error(error.response.data.message, 1);
          });
        }
      });
    },
    /**
     * 关闭评审意见
     */
    close(row) {
      this.isEdit = !this.isEdit;
      this.pagination.disabled = true;
      row.flag = 4;
    },
    /**
     * 取消
     */
    closeCancel(row) {
      this.cancel(row);
    },
  }
};
</script>
<style lang='less'>
.commentsUpload {
  margin-bottom: 5px;

  .ant-upload.ant-upload-select {
    width: 100% !important;
  }
}
</style>
<style lang='less' scoped>

/deep/ .ant-table-tbody {
  .ant-table-row-cell-break-word:nth-of-type(2) {
    text-align: left !important;
  }
}

/*/deep/ .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  overflow-y: auto !important;
}*/
</style>
