<template>
  <a-collapse :defaultActiveKey="'3'" @change="collapseChange">
    <a-collapse-panel :header="$t('plan.change-record')" key="3">
      <a-card class="mb_8" id="search-card">
        <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-record.cause')">
                <a-input
                    allowClear
                    :placeholder="$t( 'plan.change-record.please-enter-cause')"
                    v-model="queryParam.cause"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan-change-record.content')">
                <a-input
                    allowClear
                    :placeholder="$t('plan-change-record.please-enter-content')"
                    v-model="queryParam.content"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan-change-record.changer')">
                <a-input
                    allowClear
                    :placeholder="$t('plan-change-record.please-enter-changer')"
                    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-record.version')">
                <a-input
                    allowClear
                    :placeholder="$t('plan-change-record.please-enter-version')"
                    v-model="queryParam.version"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('plan-change-record.changeTime')">
                <a-range-picker :value="tg1Date" @change="tg1Change" style="width:100%"/>
              </a-form-item>
            </a-col>
            <a-col :xl="18" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item class="tr" :label="'\xa0'">
                <a-button class="ml10" type="primary" @click="search">
                  {{ $t('global-btn.search') }}
                </a-button>
								<a-button v-if="$api.isLook !== '1'" class="ml10 fr" type="primary" @click="add">
									{{ $t('plan.change-record.add') }}
								</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
			<!-- 表格-->
			<a-card id="grid-card">
				<template slot="title">
					<!-- 导出-->
					<a-button class="ml10" type="primary" @click="excelExport">
						{{ $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('fmeamanager.setting.col'))"></a-button>
					</a-dropdown>
				</template>
				<a-table
					id="change-record-table"
					ref='tableRef'
					class="with-page"
					bordered
					size="small"
					:pagination="pagination"
					:rowKey="(record, index) => {
            return index;
          }"
					:scroll='{ x: scrollWidth, y: tableHeightValue }'
					:columns='sortedColumns.filter(column => column.visible)'
					:components='components'
					:dataSource="changeRecordData"
					: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" v-if="$api.isLook !== '1'">
							<span class="operate-btn">
                	<a @click="edit(record)" v-if="record.versionCode == currentVersionCode ">
									<!-- 编辑 -->
									<a-tooltip :title="$t('global-btn.edit')">
										<i class="iconfont iconicon-bainji"></i>
									</a-tooltip>
                  </a>
							</span>
						<span class="ml10 operate-btn">
								<a @click="del(record)" v-if="record.versionCode == currentVersionCode ">
									<!-- 删除 -->
									<a-tooltip :title="$t('global-btn.delete')">
										<i class="iconfont iconshanchu"></i>
									</a-tooltip>
								</a>
              </span>
					</template>
				</a-table>
			</a-card>
    </a-collapse-panel>
    <ChangeRecordAdd ref="ChangeRecordAdd"  @getchangeRecordPageList="getchangeRecordPageList"></ChangeRecordAdd>
    <EditChangeRecord ref="EditChangeRecord"  @getchangeRecordPageList="getchangeRecordPageList" ></EditChangeRecord>
  </a-collapse>
</template>

<script>
import ChangeRecordAdd from "@/views/project/components/project/components/ChangeRecordAdd";
import EditChangeRecord from "@/views/project/components/project/components/EditChangeRecord";
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';
export default {
  name: "ChangeRecord",
	components: {
		EditChangeRecord,
		VueDraggableResizable,
		draggable,
		ChangeRecordAdd
	},
  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 {
      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 //总条数
      },
			// 表格操作列配置
			sortedColumns: [],
			startDrag: false,
			editColumnVisibilities: [],
			scrollWidth: 0,
			tableHeightValue: 0,
			// 复选框控制的状态
			columnVisibilities: {
				sortNumber: true,
				description: true,
				cause: true,
				ownerName: true,
				upgradeChangeTime: true,
				versionCode: true,
				action: true
			},
			tableColumns: [
        {
          title: 'plan.approval-record.serial-number',
          align: "center",
					dataIndex:"sortNumber",
          width: 50,
          ellipsis: true,
          scopedSlots: {
            customRender: "sortNumber"
          },
					fixed: "left",
					visible: true,
					cantHide: true,
					cantHandle: true
        },
        {
          title: 'plan-change-record.content',
          align: "center",
          width: 200,
          dataIndex: "description",
          key: "description",
					visible: true,
         ellipsis: true
        },
        {
          title: 'plan.change-record.cause',
          align: "center",
          width: 200,
          dataIndex: "cause",
          key: "cause",
					visible: true,
          ellipsis: true
        },
        {
          title: 'plan-change-record.changer',
          align: "center",
          width: 100,
          dataIndex: "ownerName",
          key: "ownerName",
					visible: true,
          ellipsis: true
        },
        {
          title: 'plan-change-record.changeTime',
          align: "center",
          width: 150,
          dataIndex: "upgradeChangeTime",
          key: "upgradeChangeTime",
					visible: true,
          ellipsis: true
        },
        {
          title: 'plan-change-record.version',
          align: "center",
          dataIndex: "versionCode",
          width: 100,
          key: "versionCode",
					visible: true,
          ellipsis: true
        },
        {
          title: 'plan.correlate-pfmea.operate',
          align: "center",
					dataIndex: "action",
          scopedSlots: {
            customRender: "action"
          },
          width: 100,
					fixed: "right",
					visible: true,
					cantHide: true,
					cantHandle: true,
          ellipsis: true
        },
      ],
      queryParam: {},
      changeRecordData: [],
      loading: false,
      tg1Date: [],
      //模态窗口的状态
      visible: false,
      recordData: {},
      //当前版本
      currentVersionCode:1,
    }
  },
	watch: {
		sortedColumns: {
			handler() {
				this.$nextTick(() => {
					// 获取表格滚动区域的总宽度
					let scrollX = $('.ant-table-fixed').width();
					// 获取表格的总宽度
					let tableWidth = $('.ant-table-body').width();
					// a-table的scrollX宽度需要减去固定列宽度
					this.scrollWidth = scrollX - 150;
					if (scrollX <= tableWidth) {
						this.cancelFixedColmuns();
					} else {
						this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
					}
				});
			},
			deep: true,
			immediate: true
		}
	},
  methods: {
		/**
		 * 初始化加载已保存的表格列顺序及显隐
		 */
		async initTableColumns() {
			// 获取用户信息，如果当前组件的userInfo为空，则从localStorage中获取
			let userInfo = this.userInfo || JSON.parse(localStorage.getItem('userInfo'));
			try {
				// 调用接口获取表格列数据
				let res = await this.$api.getTableColumnsData({
					userId: userInfo.userId,
					pagePath: this.$route.path,
					pageName: this.$route.name,
				});
				// 如果接口返回成功
				if (res.flag) {
					// 如果返回的数据中包含当前表格的配置映射，并且映射中有数据
					if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
						// 获取当前表格的配置信息
						let tableConfig = res.data.currentTableConfigMap['change-record-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);
			}
		},
		/**
		 * 处理窗口大小调整事件
		 *
		 * @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() - 150;
			// 获取表格的总宽度
			let tableWidth = $('.ant-table-body').width();
			// 超过2K屏时取消固定列
			if (width > 2560 || scrollX <= tableWidth) {
				this.cancelFixedColmuns();
			} else {
        this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
			}
		},
		/**
		 * 移动事件处理函数
		 *
		 * @param event 事件对象
		 * @returns 如果当前元素不包含禁止移动属性则返回true，否则返回false
		 */
		onMove(event) {
			// 禁止移动到包含禁止移动元素的行
			return !event.relatedContext.element.cantHandle;
		},
		/**
		 * 处理表格列显隐复选框变化事件
		 *
		 * @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);
			});
		},
		/**
		 * 保存表格配置信息
		 */
		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-record-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();
			});
		},
		/**
		 * 取消固定列
		 *
		 * @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';
				}
			});
		},
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getchangeRecordPageList();
    },
    collapseChange() {
        this.getchangeRecordPageList();
    },
    // 变更时间
    tg1Change(date, dateString) {
      this.tg1Date = date;
      this.queryParam.tg1_start = dateString[0] || undefined;
      this.queryParam.tg1_end = dateString[1] || undefined;
    },
    //分页查询
    getchangeRecordPageList() {
      this.loading = true;
      let data = {
        fmeaId: this.$route.query.rfmeaId,
        cause: this.queryParam.cause,
        description: this.queryParam.content,
        insertUserName: this.queryParam.userName,
        createDateEnd: this.queryParam.tg1_end,
        createDateStart: this.queryParam.tg1_start,
        versionCode: this.queryParam.version,
        pagination: {
          pageCurrent: this.pagination.current,
          pageSize: this.pagination.pageSize,
        }
      };

      this.$api.getchangeRecordPageList(data).then(res => {
        if (res.flag) {
          this.currentVersionCode=res.data.currentVersionCode;
          this.changeRecordData = res.data.upgradeChanges;
          this.pagination.total = res.data.pagination.rowTotal;
          this.loading=false;
        } else {
          this.$message.error(res.message, 1);
        }
      })
    },
    //查询
    search() {
      this.pagination.current = 1;
      this.getchangeRecordPageList();
    },
    //新建
    add() {
      this.$refs.ChangeRecordAdd.visible = true;
    },

    /**
     * Excel导出
     */
    excelExport() {
      let url = this.$api.baseUrl + "/DFMEA/mfmeaUpgrade/exportRecord?fmeaId=" +  this.$route.query.rfmeaId
          + "&cause=" + (this.queryParam.cause || "")
          + "&description=" + (this.queryParam.content || "")
          + "&insertUserName=" + (this.queryParam.userName || "")
          + "&createDateEnd=" + (this.queryParam.tg1_end || "")
          + "&createDateStart=" + (this.queryParam.tg1_start|| "")
          + "&versionCode=" + (this.queryParam.version|| "")
      window.open(url);
    },

    //编辑
    edit(record) {
      this.$refs.EditChangeRecord.init(record);
      this.$refs.EditChangeRecord.visible = true;
    },
    //删除
    del(record) {
      var _that = this;
      this.$confirm({
        title: this.$t('global-message.warn'),
        /** 措施追踪表格数据存在修改，是否确认离开？ */
        content: this.$t('plan-change-record.whether-to-delete'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onOk() {
          let data = {
            changeId: record.changeId,
          };
          _that.$api.deleteChangeRecord(data).then(res => {
            if (res.flag) {
              _that.$message.success(res.message, 1);
              _that.getchangeRecordPageList();
            } else {
              _that.$message.error(res.message, 1);
            }
          })
        },
        onCancel() {
        },
      });
    }
  },
  mounted() {
    this.getchangeRecordPageList();
		// 获取表格配置
		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>
