<template>
	<div ref="resizableDiv">
  <a-collapse :defaultActiveKey="'1'" @change="collapseChange">
    <a-collapse-panel :header="$t('plan.review-comments')" key="1">
      <a-card>
        <template slot="title">
          <a-button class="ml10" type="primary" @click="exportExcel">
            {{ $t("global-btn.export") }}
          </a-button>
        </template>
        <template slot="extra">
          <a-dropdown>
            <a-menu slot="overlay">
              <draggable v-model="sortedColumns" handle=".drag-handle" filter=".cant-handle" :move="onMove"
                        class="m-2 mr-1" tag="div" animation="500">
                <a-menu-item v-for="column in sortedColumns" :key="column.dataIndex" :disabled='true'
                            class="custom-menu-item mb-1" :class="column.cantHandle ? 'cant-handle' : ''">
                  <div class="drag-handle" @mousedown="startDrag = true" @mouseup="startDrag = false"
                      @mouseleave="startDrag = false">
                    <i class="icon iconfont iconshangxiayidong-"></i>
                  </div>
                  <a-checkbox v-model="editColumnVisibilities[column.dataIndex]" :disabled="column.cantHide"
                              @change="handleCheckboxChange(column.dataIndex, $event.target.checked)">
                    {{ column.title }}
                  </a-checkbox>
                </a-menu-item>
              </draggable>
              <a-menu-item class="dropdown-footer" :disabled='true'>
                <a-button size="small" class="mr-2" @click='handleCheckBoxReset'>{{
                    $t('global-btn.reset')
                  }}
                </a-button>
                <a-button type="primary" size="small" @click="handleSaveTableConfig">{{
                    $t('plan.change-record.save')
                  }}
                </a-button>
              </a-menu-item>
            </a-menu>
            <a-button icon="setting" type="link" :title="($t('global-constant.setting.col'))"></a-button>
          </a-dropdown>
        </template>
        <a-table
            class="with-page"
            id="review-comments-table"
            ref='tableRef'
            size="small"
            bordered
            :components='components'
            :columns='sortedColumns.filter(column => column.visible)'
            :scroll='{ x: scrollWidth, y: tableHeightValue }'
            :pagination="pagination"
            :rowKey="(record, index) => { return index; }"
            :dataSource="reviewCommentsData"
            :loading="loading"
            @change="handleTableChange">
          <!-- 序号 -->
          <template slot="sortNumber" slot-scope="text, row, index">
            {{ (pagination.pageNo - 1) * pagination.pageSize + 1 + index }}
          </template>
          <!-- 附件 -->
          <template slot="fmeaCommentsFileBOS" slot-scope="text, record">
            <ul class="fileList" v-if="record.flag === 0 || record.flag === 4">
              <li v-for="item in record.fmeaCommentsFileBOS" :key="item.id">
                <a :href="$api.requestUrl +'/DFMEA/file/downloadFile.do?id=' + item.id + '&fileType=01'">
                  {{ item.fileName }}
                </a>
              </li>
            </ul>
            <div v-else-if="record.flag === 3">
              <div>
              <span
                style='font-size:15px; display:block'
                v-for='(item, index) in record.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(record.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="comments" slot-scope="text, record">
            <div
                v-if="record.flag === 0 || record.flag === 4"
                :key="record.index"
                @click="jumpComments(record)"
                :title="text"
                class="spanTitle">
              {{ text }}
            </div>
            <a-textarea
								class="textarea"
                v-if='record.flag === 3'
                v-model='record.comments'
                :autoSize='{ minRows: 2 }'
                :placeholder="$t('functional-analysis.review-comments.click-to-add-review-comments')"
                :maxLength='300'>
            </a-textarea>
          </template>
          <!-- 状态 -->
          <template slot="state" slot-scope='text, row'>
            {{ row.state === 0 ? $t('global-btn.submit') : $t('global-btn.close')}}
          </template>
          <!-- 关闭原因 -->
          <template slot='closeReason' slot-scope='text, row'>
            <span>{{ row.state === 1 && row.flag != 4 ? row.closeReason : '' }}</span>
            <a-textarea
								class="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="closeUserName" slot-scope='text, row'>
            {{ row.state === 0 ? "" : row.closeUserName }}
          </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,row.struId)">
                  <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.struId, 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.struId,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-if="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,row.struId)">
                  <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.struId,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>
      </a-card>
      <!-- 导出 -->
      <a-modal
        :title="$t('global-btn.export')"
        :visible='exportVisible'
        :width="400"
        :maskClosable="false"
        @cancel="closeExportModal"
        @ok="exportFile"
        :okText="$t('global-btn.export')">
        <div>
          <h3>{{$t('global-btn.please-select-export-type')}}</h3>
          <a-radio-group v-model="exportType">
            <a-radio value="1" class="mr-4">{{$t('global-btn.export-by-the-selected-columns')}}</a-radio>
            <a-radio value="0">{{$t('global-btn.export-default-table-columns')}}</a-radio>
          </a-radio-group>
        </div>
      </a-modal>
    </a-collapse-panel>
  </a-collapse>
	</div>
</template>
<script>

import {replaceNullName} from "@/utils/tree";
import utils from '@/utils/urlParamUtil';
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';

export default {
  name: "ReviewComments",
  components: {
    VueDraggableResizable,
    draggable
  },
  props: {
    from: {
      type: String,
      default: "mfmea"
    },
    fmeaId: {
      type: String | Number,
      default: ""
    },
    masterFmeaId: {
      type: String | Number,
      default: ""
    },
    fmeaType: {
      type: String | Number,
      default: "1"
    }
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props;
          // 此处的this.sortedColumns 是定义的table的表头属性变量
          const col = this.sortedColumns.find((col) => {
            const k = col.dataIndex || col.key;
            return k === key;
          });
          if (!col || !col.width) {
            return h('th', { ...restProps }, [...children]);
          }
          const dragProps = {
            key: col.dataIndex || col.key,
            class: 'table-draggable-handle',
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: 'x',
              draggable: true,
              resizable: false
            },
            on: {
              dragging: (x, y) => {
                col.width = Math.max(x, 100);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return {
			// 页面自适应
			resizeObserver: null,
      // 分页
      pagination: {
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: (total) => this.$t('global-constant.table.show-total', [total]), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0 //总条数
      },
      // 导出弹框
      exportVisible: false,
      // 导出类型
      exportType: '1',
      // 表格id
      tableId: '',
      scrollWidth: 0,
      tableHeight: 0,
      tableHeightValue: 0,
      // 复选框控制的状态
      columnVisibilities: {
        serialNumber: true,
        comments: true,
        struName: true,
        structureTypeName: true,
        insertTime: true,
        userName: true,
        state: true,
        closeReason: true,
        closeUserName: true,
        closeTime: true,
        fmeaCommentsFileBOS: true,
        operation: true
      },
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      // 评审意见表头
      tableColumns: [
        // 序号
        {
          title: 'fmea.review.comments.export.title.serialNumber',
          align: "center",
          dataIndex: "serialNumber",
          width: 70,
          ellipsis: true,
          visible: true,
          cantHide: true,
          cantHandle: true,
          fixed: 'left',
          scopedSlots: {
            customRender: "sortNumber"
          }
        },
        // 评审意见
        {
          title: 'fmea.review.comments.export.title.reviewComments',
          align: "center",
          dataIndex: "comments",
          width: 300,
          scopedSlots: {
            customRender: "comments"
          },
          visible: true,
          ellipsis: true
        },
        // 所在节点名称
        {
          title: 'fmea.review.comments.export.title.nodeName',
          align: "center",
          width: 300,
          dataIndex: "struName",
          visible: true,
          ellipsis: true
        },
        // 所在节点类别
        {
          title: 'fmea.review.comments.export.title.nodeType',
          align: "center",
          width: 120,
          dataIndex: "structureTypeName",
          visible: true,
          ellipsis: true
        },
        // 添加时间
        {
          title: 'fmea.review.comments.export.title.addTime',
          align: "center",
          width: 150,
          dataIndex: "insertTime",
          visible: true,
          ellipsis: true
        },
        // 提出人
        {
          title: 'fmea.review.comments.export.title.introducer',
          align: "center",
          width: 100,
          dataIndex: "userName",
          visible: true,
          ellipsis: true
        },
        // 状态
        {
          title: 'fmea.review.comments.export.title.status',
          dataIndex: 'state',
          align: 'center',
          scopedSlots: {customRender: 'state'},
          width: 100,
          visible: true,
          ellipsis: true
        },
        // 关闭原因
        {
          title: 'fmea.review.comments.export.title.shutdownReason',
          align: 'center',
          dataIndex: 'closeReason',
          scopedSlots: {customRender: 'closeReason'},
          width: 300,
          visible: true,
          ellipsis: true
        },
        // 关闭人
        {
          title: 'fmea.review.comments.export.title.shutter',
          dataIndex: 'closeUserName',
          align: 'center',
          scopedSlots: {customRender: 'closeUserName'},
          width: 100,
          visible: true,
          ellipsis: true
        },
        // 关闭时间
        {
          title: 'fmea.review.comments.export.title.closingTime',
          dataIndex: 'closeTime',
          align: 'center',
          width: 120,
          visible: true,
          ellipsis: true
        },
        // 附件
        {
          title: 'fmea.review.comments.export.title.attachments',
          align: "center",
          width: 400,
          dataIndex: "fmeaCommentsFileBOS",
          scopedSlots: {
            customRender: "fmeaCommentsFileBOS"
          },
          visible: true,
          ellipsis: true
        },
        // 操作
        {
          title: 'functional-analysis.review-comments.operate',
          dataIndex: 'operation',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
          width: 120,
          ellipsis: true,
          fixed: "right",
          visible: true,
          cantHide: true,
          cantHandle: true,
        }
      ],
      // 评审意见表格数据
      reviewCommentsData: [],
      loading: false,
      /** 是否编辑 */
      isEdit: false,
      /** 编辑评审意见 */
      editComments: '',
      /** 编辑评审意见时，文件上传Loading */
      editUploadFileLoading: false,
      /** 编辑评审意见时，文件上传集合 */
      editFileList: [],
      /** 保存Loading */
      saveLoading: false,
      /** 表格Loading */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 表格缓存数据 */
      tableCacheData: [],
    };
  },

  mounted() {
    this.getReviewCommentsPageList();
    this.initTableColumns();
    this.handleResize();
		// 监听页面大小变化
		this.resizeObserver = new ResizeObserver(entries => {
			this.handleResize();
		});
		this.resizeObserver.observe(this.$refs.resizableDiv);
  },
  //剔除页面大小变化得监听事件
  beforeDestroy() {
		if (this.resizeObserver) {
			this.resizeObserver.disconnect();
		}
  },
  watch: {
    sortedColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格滚动区域的总宽度
          let scrollX = $('.ant-table-fixed').width();
          // 获取表格的总宽度
          let tableWidth = $('.ant-table-body').width();
          // a-table的scrollX宽度需要减去固定列宽度
          this.scrollWidth = scrollX - 260;
          if (scrollX <= tableWidth) {
            this.cancelFixedColmuns();
          } else {
            this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
          }
        });
      },
      deep: true,
      immediate: true
    },
    advanceExpand: {
      handler() {
        this.$nextTick(() => {
          this.handleResize();
        });
      }
    }
  },
  methods: {
    /**
     * 初始化加载已保存的表格列顺序及显隐
     */
     async initTableColumns() {
      // 获取用户信息，如果当前组件的userInfo为空，则从localStorage中获取
      let userInfo = JSON.parse(localStorage.getItem("userInfo"));
      // 获取页面中所有的表格容器
      let tableWrappers = document.querySelectorAll('.ant-table-wrapper');
      // 提取表格容器的id，并转换为数组
      let tableIds = Array.from(tableWrappers).map(item => item.id);
      try {
        // 调用接口获取表格列数据
        let res = await this.$api.getTableColumnsData({
          userId: userInfo.userId,
          pagePath: this.$route.path,
          pageName: this.$route.name,
          tableIds: tableIds
        });
        // 如果接口返回成功
        if (res.flag) {
          // 如果返回的数据中包含当前表格的配置映射，并且映射中有数据
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['review-comments-table'];
            // 如果表格配置存在
            if (tableConfig) {
              // 解析表格列数据 将从数据库中获取的表格title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns
              let oldColumns = JSON.parse(tableConfig.tableColumns);
              oldColumns.forEach((column) => {
                // 处理表格列的title
                column.title = this.$t(column.title);
              });
              this.sortedColumns = [...oldColumns];
              // 解析表格列显示状态
              this.editColumnVisibilities = JSON.parse(tableConfig.tableVisibilities);
            } else {
              // 如果没有表格配置，则使用默认的表格列和显示状态
              // 处理表格列的title 将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
              let newTableColumns = [];
              this.tableColumns.forEach((column) => {
                let newColumn = { ...column };
                newColumn.title = this.$t(column.title);
                newTableColumns.push(newColumn);
              });
              this.sortedColumns = [...newTableColumns];
              this.editColumnVisibilities = { ...this.columnVisibilities };
            }
          } else {
            // 如果没有表格配置，则使用默认的表格列和显示状态
            // 处理表格列的title 将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
            let newTableColumns = [];
            this.tableColumns.forEach((column) => {
              let newColumn = { ...column };
              newColumn.title = this.$t(column.title);
              newTableColumns.push(newColumn);
            });
            this.sortedColumns = [...newTableColumns];
            this.editColumnVisibilities = { ...this.columnVisibilities };
          }
          // 如果接口返回失败
        } else {
          console.error('Failed to retrieve table column data.');
        }
      } catch (error) {
        // 捕获异常，并输出错误信息
        console.error('Error occurred while fetching table columns:', error);
      }
    },
    /**
     * 移动事件处理函数
     *
     * @param event 事件对象
     * @returns 如果当前元素不包含禁止移动属性则返回true，否则返回false
     */
    onMove(event) {
      // 禁止移动到包含禁止移动元素的行
      return !event.relatedContext.element.cantHandle;
    },
    /**
     * 保存表格配置信息
     */
    handleSaveTableConfig() {
      // 创建一个对象用于保存需要保存的配置数据
      // 将sortedColumns中的title替换为tableColumns中的title
      let newSortedColumns = [];
      this.sortedColumns.forEach(column => {
        let newColumn = { ...column };
        if (this.tableColumns.find(item => item.dataIndex === column.dataIndex)) {
          let item = this.tableColumns.find(item => item.dataIndex === column.dataIndex);
          newColumn.title = item.title;
        }
        newSortedColumns.push(newColumn);
      });
      let data = {
        pagePath: this.$route.path,
        pageName: this.$route.name,
        // 表格列信息，转为JSON字符串
        tableColumns: JSON.stringify(newSortedColumns),
        // 表格列可见性信息，转为JSON字符串
        tableVisibilities: JSON.stringify(this.editColumnVisibilities),
        // 表格id
        tableId: 'review-comments-table'
      };
      // 调用API保存表格配置
      this.$api.saveTableConfig(data).then(res => {
        // 如果返回结果中的flag为true，表示保存成功
        if (res.flag) {
          // 显示成功提示信息
          this.$message.success(res.message, 1);
          // 重新初始化数据
          this.getReviewCommentsPageList();
        } else {
          // 显示错误提示信息
          this.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 重新初始化数据
        this.getReviewCommentsPageList();
      });
    },
    /**
     * 处理表格列显隐复选框变化事件
     *
     * @param key 列的唯一标识符
     * @param checked 列的显示状态，true表示显示，false表示隐藏
     */
    handleCheckboxChange(key, checked) {
      // 更新全局的columnVisibilities对象
      this.$set(this.editColumnVisibilities, key, checked);
      // 更新列配置中的visible属性（如果需要的话）
      this.sortedColumns.forEach(column => {
        if (column.dataIndex === key) {
          column.visible = checked;
        }
      });
    },
    /**
     * 重置表格列显示隐藏
     */
    handleCheckBoxReset() {
      this.editColumnVisibilities = { ...this.columnVisibilities };
      // 重置时，将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
      let resetColumns = [];
      this.tableColumns.forEach(column => {
        let newColumn = { ...column };
        newColumn.title = this.$t(column.title);
        resetColumns.push(newColumn);
      });
      this.sortedColumns = [...resetColumns];
      this.sortedColumns.forEach(column => {
        this.$set(column, 'visible', true);
      });
    },
    /**
     * 取消固定列
     *
     * @returns 无返回值
     */
    cancelFixedColmuns() {
      // 遍历已排序的列
      this.sortedColumns.forEach((column) => {
        // 如果列的固定属性为true
        if (column.fixed) {
          // 将列的固定属性设置为false
          column.fixed = false;
        }
      });
    },
    /**
     * 重新设置固定列的固定状态
     *
     * @param fixedLeftColumns 左侧固定列名数组
     * @param fixedRightColumns 右侧固定列名数组
     */
    reloadFixedColmuns(fixedLeftColumns, fixedRightColumns) {
      fixedLeftColumns.forEach((column) => {
        if (this.sortedColumns[column]) {
          this.sortedColumns[column].fixed = 'left';
        }
      });
      fixedRightColumns.forEach((column) => {
        if (this.sortedColumns[column]) {
          this.sortedColumns[column].fixed = 'right';
        }
      });
    },
    /**
     * 处理窗口大小调整事件
     *
     * @returns 无返回值
     */
    handleResize() {
      // 获取窗口宽度
      const width = window.innerWidth;
      // 获取窗口高度
      const height = Math.max(window.innerHeight, 0);
      this.tableHeightValue = height - 326;
      this.scrollWidth = this.$refs.tableRef?.$el.offsetWidth;
      // 获取表格滚动区域的总宽度
      let scrollX = $('.ant-table-fixed').width() - 260;
      // 获取表格的总宽度
      let tableWidth = $('.ant-table-body').width();
      // 超过2K屏时取消固定列
      if (width > 2560 || scrollX <= tableWidth) {
        this.cancelFixedColmuns();
      } else {
				// 此页面需先取消固定列，再重新设置，以便固定列高度与评审意见/关闭原因列高度一致
				this.cancelFixedColmuns();
        this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
      }
    },
    /**
     * 折叠展开事件
     * @param keys
     * @returns {boolean}
     */
    collapseChange(keys) {
      if (!(keys && keys.length > 0)) {
        return false;
      }
      let key = keys[keys.length - 1];
      if (key == 1) {
        this.getReviewCommentsPageList();
      }
    },

    /**
     * 分页事件
     * @param pagination
     */
    handleTableChange(pagination) {
      this.pagination.pageNo = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getReviewCommentsPageList();
    },

    /**
     * 获取评审意见表格分页数据
     * @returns {Promise<void>}
     */
    async getReviewCommentsPageList() {
      var data = {
        fmeaId: this.fmeaId,
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        rfmeaType: 'M'
      };
      this.loading = true;
      await this.$api.post("/DFMEA/mfmea/plan/getComments.do", data).then((response) => {
        this.loading = false;
        if (response.flag) {
          this.reviewCommentsData = response.data.data;
          if (this.reviewCommentsData && this.reviewCommentsData.length > 0) {
            this.reviewCommentsData.forEach(item => {
              item.struName = replaceNullName({name: item.struName, struTypeCode: item.structureType});
            });
          }
          this.pagination.total = response.data.total;
        } else {
          this.reviewCommentsData = [];
          this.pagination.total = 0;
        }
      });
    },

    /**
     * 评审意见跳转功能分析
     * @param record
     */
    jumpComments(record) {
      this.$api.getCommentsStruId({
        fmeaId: this.$store.getters.rfmeaId,
        struId: record.struId
      }).then((res) => {
        if (res.data.rdfmStruTree != null) {
          this.$store.dispatch("fmeaTree/set", {
            key: "rightStruIdFromComments",
            value: record.struId
          });
          this.$store.dispatch("fmeaTree/set", {
            key: "rightParentStruIdFromComments",
            value: res.data.rdfmStruTree.struId
          });
          this.$store.dispatch("fmeaTree/set", {
            key: "leftStruIdFromComments",
            value: res.data.rdfmStruTree.struId
          });
          this.$store.dispatch("fmeaTree/set", {
            key: "commentsParentIds",
            value: res.data.parentIds
          });
          var fmeaId = this.getUrlParam("fmeaId");
          var deriveId = this.getUrlParam("deriveId");
          var rfmeaId = this.getUrlParam("rfmeaId");
          var _from = this.getUrlParam("from");
          let backUrl = utils.getUrlKey('back');
          this.$router.push(
            "/function2" + "?fmeaId=" + fmeaId +
            "&rfmeaId=" + rfmeaId  +
            "&deriveId=" + deriveId +
            "&from=" + _from +
            "&back=" + backUrl +
            '&ntimet=' + new Date().getTime()
          )
        } else {
          this.$message.error(this.$t('global-message.warn.comment.jump.stru'), 1);
        }
      })
    },

    /**
     * 编辑评审意见时，文件上传
     * @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 文件
     */
    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, struId, 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: struId,
        id: id ? id : undefined,
        comments: comments,
        fmeaAddCommentsFileVOS: fileList
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message);
          if (!id) {
            _that.addComments = '';
          } else {
            _that.editComments = '';
            _that.editFileList = [];
          }
        } 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;
        _that.getReviewCommentsPageList();
      });
    },

    /**
     * 关闭
     */
    closeComments(id,struId,closeReason) {
      let _that = this;
      _that.saveLoading = true;
      _that.$api.updateComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        id: id ? id : null,
        struId: struId,
        flag: 1, //1表示关闭
        closeReason: closeReason,
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
        } 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;
        _that.getReviewCommentsPageList();
      });
    },

    /**
     * 重新打开
     */
    openComents(id,struId) {
      let _that = this;
      _that.saveLoading = true;
      _that.$api.updateComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        id: id ? id : null,
        struId: struId,
        flag: 0, //0表示提交
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
        } 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;
        _that.getReviewCommentsPageList();
      });
    },

    /**
     * 重新编辑
     * @param row 表格行数据
     */
    reEdit(row) {
      this.isEdit = !this.isEdit;
      this.pagination.disabled = true;
      row.flag = 3;
    },

    /**
     * 关闭评审意见
     */
    close(row) {
      this.isEdit = !this.isEdit;
      this.pagination.disabled = true;
      row.flag = 4;
    },

    /**
     * 取消
     * @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;
    },

    /**
     * 取消
     */
    closeCancel(row) {
      this.isEdit = !this.isEdit;
      this.pagination.disabled = false;
      row.flag = 0;
    },

    /**
     * 评审意见：删除
     * @param row 表格行数据
     */
    deleteComments(row) {
      let _that = this;
      // 如果 删除的是最后一条，并且不是第一页的最后一条，则自动向上一页跳转
      if (_that.tableData.length === 1 && _that.pagination.pageNo !== 1) {
        _that.pagination.pageNo -= 1;
      }
      _that.$api.deleteComments({
        rfmeaId: _that.$store.getters.rfmeaId,
        fmeaId: _that.$store.getters.fmeaId,
        id: row.id,
        struId: row.struId,
        lastEntry: _that.pagination.total === 1
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.getReviewCommentsPageList();
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      });
    },

    /**
     * 获取路径参数
     * @param paraName
     * @returns {string}
     */
    getUrlParam(paraName) {
      var url = document.location.toString();
      var arrObj = url.split("?");
      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;
        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");
          if (arr != null && arr[0] == paraName) {
            return arr[1];
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 导出弹窗关闭
    closeExportModal() {
      this.exportVisible = false;
      this.exportType = '1';
    },
    // 导出弹窗
    async exportExcel() {
      // 查询表格列配置信息
      let tableConfigData = {
        userId: this.$route.query.userId,
        pagePath: this.$route.path,
        pageName: this.$route.name,
      };
      await this.$api.getTableColumnsData(tableConfigData).then(res => {
        if (res.flag) {
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['review-comments-table'];
            if (tableConfig) {
              this.tableId = tableConfig.id;
            }
          }
        }
      });
      this.exportVisible = true;
    },
    // 导出文件
    exportFile() {
      let tableId = this.tableId || ''; // 表格id
      let exportType = this.exportType; // 导出类型
      // 查询条件
      let fmeaId = this.fmeaId;
      let rfmeaType = 'M';

      let url = this.$api.baseUrl + "/DFMEA/mfmea/plan/exportExcel?";
      url += "fmeaId=" + fmeaId + "&rfmeaType=" + rfmeaType + "&tableId=" + tableId + "&exportType=" + exportType;
      window.open(url);
      this.closeExportModal();
    }
  }
};
</script>
<style lang="scss" scoped>
.textarea {
	resize: none;
}
.fileList {
  max-height: 62px;
  width: 100%;
  overflow-y: auto;
  margin: 0 !important;

  li {
    width: 100%;
    height: 20px;
    line-height: 20px;
    text-align: left;
    margin: 0 !important;

    a {
      color: #40a9ff;
    }
  }
}

.comments-container {
  width: 100%;

  .comments {
    display: -webkit-box;
    /*重点，不能用block等其他，将对象作为弹性伸缩盒子模型显示*/
    -webkit-box-orient: vertical;
    /*从上到下垂直排列子元素（设置伸缩盒子的子元素排列方式）*/
    -webkit-line-clamp: 3;
    /*行数，超出三行隐藏且多余的用省略号表示...*/
    line-clamp: 3;
    word-break: break-all;
    overflow: hidden;
    max-width: 100%;
    max-height: 60px;
  }
}

.spanTitle {
  display: block;
  width: 100%;
  overflow : hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #1890FF !important;
  cursor:pointer;
}
</style>
<style scoped>
/deep/ .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden!important;
  margin-bottom: 0!important;
  padding-right: 8px;
  background: rgb(250, 250, 250);
}
</style>
