<template>
  <a-collapse :defaultActiveKey="'1'" @change="collapseChange">
    <a-collapse-panel :header="$t('plan.change-log')" key="1">
      <a-card class="mb_8">
        <a-form layout="vertical">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan.change-log.userName')">
                <a-input
                    allowClear
                    :placeholder="$t( 'plan.change-log.please-enter-userName')"
                    v-model="queryParam.userName"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan.change-log.action')">
                <a-input
                    allowClear
                    :placeholder="$t('plan.change-log.please-enter-action')"
                    v-model="queryParam.actDetail"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan.change-log.insertTime')">
                <a-range-picker :value="tg1Date" @change="tg1Change" style="width:100%"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="24" :md="24" :sm="24" :xs="24">
              <a-form-item class="tr" :label="'\xa0'">
                <a-button class="ml10" type="primary" @click="getSearch">
                  {{ $t('global-btn.search') }}
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <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="change-log-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="changeLogData"
            :loading="loading"
            @change="handleTableChange">
          <template slot="sortNumber" slot-scope="text, row, index">
            {{ (pagination.current - 1) * pagination.pageSize + 1 + index }}
          </template>
          <template slot="action" slot-scope="text, record">
            <span>
                <a @click="edit(record)">
                <!-- 编辑 -->
                <a-tooltip :title="$t('global-btn.edit')">
                  <i class="iconfont iconicon-bainji"></i>
                </a-tooltip>
                </a>
            </span>
            <span>
              <a @click="del(record)">
                <!-- 删除 -->
                <a-tooltip :title="$t('global-btn.delete')">
                  <i class="iconfont iconshanchu"></i>
                </a-tooltip>
              </a>
            </span>
          </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>
</template>

<script>
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';

export default {
  name: "ChangeLog",
  components: {
    VueDraggableResizable,
    draggable
  },
  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 {
      // 导出弹框
      exportVisible: false,
      // 导出类型
      exportType: '1',
      // 表格id
      tableId: '',
      scrollWidth: 0,
      tableHeight: 0,
      tableHeightValue: 0,
      // 复选框控制的状态
      columnVisibilities: {
        serialNumber: true,
        insertUserName: true,
        insertTime: true,
        actDetail: true
      },
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      queryParam: {},
      tg1Date: [],
      loading: false,
      changeLogData: [],
      pagination: {
        current: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: (total) => this.$t('global-constant.table.show-total', [total]), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true,  //显示快速跳转的页码
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        // onChange: (page, pageSize) => self.changePage(page, pageSize), //点击页码事件
        total: 0 //总条数,
      },
      tableColumns: [
        {
          title: 'fmea.change.log.export.title.serialNumber',
          align: "center",
          width: 50,
          dataIndex: "serialNumber",
          ellipsis: true,
          visible: true,
          cantHide: true,
          cantHandle: true,
          scopedSlots: {
            customRender: "sortNumber"
          }
        },
        {
          title: 'fmea.change.log.export.title.userName',
          align: "center",
          width: 200,
          dataIndex: "insertUserName",
          visible: true,
          ellipsis: true
        },
        {
          title: 'fmea.change.log.export.title.operatingTime',
          align: "center",
          width: 200,
          dataIndex: "insertTime",
          visible: true,
          ellipsis: true
        },
        {
          title: 'fmea.change.log.export.title.operationDetails',
          align: "center",
          width: 200,
          dataIndex: "actDetail",
          visible: true,
          ellipsis: true
        },
      ],
    }
  },
  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([], []);
          }
        });
      },
      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['change-log-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: 'change-log-table'
      };
      // 调用API保存表格配置
      this.$api.saveTableConfig(data).then(res => {
        // 如果返回结果中的flag为true，表示保存成功
        if (res.flag) {
          // 显示成功提示信息
          this.$message.success(res.message, 1);
          // 重新初始化数据
          this.search();
        } else {
          // 显示错误提示信息
          this.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 重新初始化数据
        this.search();
      });
    },
    /**
     * 处理表格列显隐复选框变化事件
     *
     * @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);
      // 获取用户信息容器的高度
      let searchCardHeight = $("#search-card").height();
      // 系统内菜单栏、标签栏的高度恒定为64 + 40 = 104，其他页边距需根据每个页面布局自行计算
      $("#grid-card").height(height - 104 - searchCardHeight - 40);
      this.tableHeightValue = height - 104 - searchCardHeight - 222;
      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.reloadFixedColmuns([], []);
      }
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.search();
    },
    collapseChange(keys) {
      if (!(keys && keys.length > 0)) {
        return false;
      }
        this.search();
    },
    // 变更时间
    tg1Change(date, dateString) {
      this.tg1Date = date;
      this.queryParam.tg1_start = dateString[0] || undefined;
      this.queryParam.tg1_end = dateString[1] || undefined;
    },
    // 查询按钮绑定功能
    getSearch() {
      this.pagination.current = 1;
      this.search();
    },
    //查询
    search() {
      this.loading = true;
      let data = {
        fmeaId: this.$route.query.rfmeaId,
        userName: this.queryParam.userName,
        createDateStart: this.queryParam.tg1_start,
        createDateEnd: this.queryParam.tg1_end,
        actDetail: this.queryParam.actDetail,
        pagination: {
          pageCurrent: this.pagination.current,
          pageSize: this.pagination.pageSize,
        }
      };
      this.$api.getChangeLogPageList(data).then(res => {
        if (res.flag) {
          this.changeLogData = res.data.dfmeaLogList;
          this.pagination.total = res.data.pagination.rowTotal;
          this.loading=false;
        } else {
          this.$message.error(res.message, 1);
        }
      })
    },
    // 导出弹窗关闭
    closeExportModal() {
      this.exportVisible = false;
      this.exportType = '1';
    },
    // 导出弹窗
    async exportExcel() {
      // 查询表格列配置信息
      let userInfo = JSON.parse(localStorage.getItem('userInfo'));
      let tableConfigData = {
        userId: userInfo.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['change-log-table'];
            if (tableConfig) {
              this.tableId = tableConfig.id;
            }
          }
        }
      });
      this.exportVisible = true;
    },
    // 导出文件
    exportFile() {
      let tableId = this.tableId || ''; // 表格id
      let exportType = this.exportType; // 导出类型
      // 查询条件
      let fmeaId = this.$route.query.rfmeaId;
      let userName = this.queryParam.userName || '';
      let createDateStart = this.queryParam.tg1_start || '';
      let createDateEnd = this.queryParam.tg1_end || '';
      let actDetail = this.queryParam.actDetail || '';

      let url = this.$api.baseUrl + "/DFMEA/rdfmUpgrade/changeLogExportExcel?";
      url += "fmeaId=" + fmeaId +
        "&userName=" + userName + "&createDateStart=" + createDateStart +
        "&createDateEnd=" + createDateEnd + "&actDetail=" + actDetail +
        "&tableId=" + tableId + "&exportType=" + exportType;
      window.open(url);
      this.closeExportModal();
    }
  },
  mounted() {
    this.search();
    this.initTableColumns();
    this.handleResize();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
}
</script>

<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>
