<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="政策标题" prop="policyTitle">
        <el-input v-model="queryParams.policyTitle" placeholder="请输入政策标题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="沟通主题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入沟通主题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="沟通类型" prop="submitType">
        <el-select v-model="queryParams.submitType" placeholder="请选择沟通类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_SUBMIT_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="留言时间" prop="submitTime">
        <el-date-picker v-model="queryParams.submitTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['server:policy-communications:create']">新增</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['server:policy-communications:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="handleSort"
                   v-hasPermi="['server:policy-communications:update']">排序</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 排序提示 -->
    <el-alert
      v-if="isSorting"
      title="排序模式：可手动输入序号，或选择要排序的项使用下方按钮调整位置，调整完成后点击保存排序"
      type="warning"
      show-icon
      :closable="false"
      class="mb8"
    />

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="displayList"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" align="center" />

      <!-- 序号输入列（排序模式下显示） -->
      <el-table-column v-if="isSorting" label="序号" align="center" width="120">
        <template v-slot="scope">
          <el-input-number
            v-model="scope.row.customSortOrder"
            :min="1"
            :max="9999"
            size="mini"
            controls-position="right"
            @change="handleManualSortChange(scope.row, scope.$index)"
            style="width: 80px;"
          />
          <span v-if="scope.row.sortOrder" class="original-sort">原：{{ scope.row.sortOrder }}</span>
        </template>
      </el-table-column>

      <!-- 原有列 -->
      <el-table-column label="政策标题" align="center" prop="policyTitle" />
      <el-table-column label="沟通主题" align="center" prop="title" />
      <el-table-column label="沟通类型" align="center" prop="submitType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.TRS_SUBMIT_TYPE" :value="scope.row.submitType" />
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.submitTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="回复单位" align="center" prop="replyDept" />

<!--      <el-table-column label="状态" align="center" prop="dealStatus">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.TRS_STATUS" :value="scope.row.dealStatus" />
        </template>
      </el-table-column>-->
      <el-table-column label="回复时间" align="center" prop="replayTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.replayTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否公开" align="center" prop="replayIsPublic">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.TRS_IS_PUBLIC" :value="scope.row.replayIsPublic" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
                     v-hasPermi="['server:policy-communications:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['server:policy-communications:update']">办理</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['server:policy-communications:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 排序操作栏 -->
    <div class="sort-actions" v-if="isSorting">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-sort-up" size="mini" @click="moveToTop"
                     :disabled="selectedRows.length !== 1">置顶</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-top" size="mini" @click="moveUp"
                     :disabled="selectedRows.length !== 1">上移</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-bottom" size="mini" @click="moveDown"
                     :disabled="selectedRows.length !== 1">下移</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-sort-down" size="mini" @click="moveToBottom"
                     :disabled="selectedRows.length !== 1">置底</el-button>
        </el-col>
        <el-col :span="1.5" :offset="1">
          <el-button type="primary" plain icon="el-icon-check" size="mini" @click="saveSort"
                     :loading="saveLoading">保存排序</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-close" size="mini" @click="cancelSort">取消排序</el-button>
        </el-col>
      </el-row>
      <div class="sort-tip">
        <span v-if="selectedRows.length > 0">已选择 1 项（{{ selectedRows[0]?.policyTitle }}）</span>
        <span v-else>请选择一项进行按钮排序，或直接输入序号</span>
      </div>
    </div>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <PolicyCommunicationsForm ref="formRef" @success="getList" />
  </div>
</template>

<script>
import * as PolicyCommunicationsApi from '@/api/server/policycommunications';
import PolicyCommunicationsForm from './PolicyCommunicationsForm.vue';
import {getRejectedPolicyCommunicationsPage} from "@/api/server/policycommunications";

export default {
  name: "PolicyCommunicationsBase",
  components: {
    PolicyCommunicationsForm,
  },
  props: {
    // 状态类型：'pending', 'replied', 'published'
    statusType: {
      type: String,
      default: 'pending'
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原始列表数据
      originalList: [],
      // 显示列表数据（排序时会修改）
      displayList: [],
      // 是否正在排序
      isSorting: false,
      // 保存排序加载状态
      saveLoading: false,
      // 选中的行
      selectedRows: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        policyId: null,
        policyTitle: null,
        replyDept: null,
        replyDeptid: null,
        userName: null,
        mobile: null,
        submitType: null,
        title: null,
        submitTime: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 根据状态类型获取对应的API方法 */
    getApiMethod() {
      const apiMap = {
        pending: PolicyCommunicationsApi.getPendingPolicyCommunicationsPage,
        replied: PolicyCommunicationsApi.getRepliedPolicyCommunicationsPage,
        published: PolicyCommunicationsApi.getPublishedPolicyCommunicationsPage,
        rejected: PolicyCommunicationsApi.getRejectedPolicyCommunicationsPage,
        all: PolicyCommunicationsApi.getPolicyCommunicationsPage,
      };
      return apiMap[this.statusType] || PolicyCommunicationsApi.getPolicyCommunicationsPage;
    },

    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const apiMethod = this.getApiMethod();
        const res = await apiMethod(this.queryParams);
        this.originalList = res.data.list;
        // 初始化自定义排序序号
        this.displayList = res.data.list.map(item => ({
          ...item,
          customSortOrder: item.sortOrder || 0 // 初始化为数据库中的排序值
        }));
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    /** 查看详情 */
    handleView(row) {
      this.$refs["formRef"].open(row.id, true);
    },

    /** 表格行类名 */
    tableRowClassName({ row }) {
      const isSelected = this.selectedRows.some(item => item.id === row.id);
      return isSelected ? 'selected-row' : '';
    },

    /** 选择行变化 */
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    },

    /** 开启排序模式 */
    handleSort() {
      this.isSorting = true;
      // 重置选择
      this.selectedRows = [];
      // 为每条数据初始化自定义排序序号
      this.displayList = this.displayList.map(item => ({
        ...item,
        customSortOrder: item.sortOrder || this.displayList.indexOf(item) + 1
      }));
    },

    /** 取消排序 */
    cancelSort() {
      this.isSorting = false;
      this.selectedRows = [];
      // 恢复原始顺序
      this.displayList = this.originalList.map(item => ({
        ...item,
        customSortOrder: undefined
      }));
    },

    /** 手动输入序号变化 */
    handleManualSortChange(row, index) {
      // 可以在这里添加序号冲突检查逻辑
      console.log(`第${index + 1}行的序号改为:`, row.customSortOrder);
    },

    /** 置顶 */
    moveToTop() {
      if (this.selectedRows.length !== 1) {
        this.$modal.msgWarning('请选择一项进行操作');
        return;
      }

      const selectedId = this.selectedRows[0].id;
      const index = this.displayList.findIndex(item => item.id === selectedId);

      if (index > 0) {
        // 移除选中的项目
        const [selectedItem] = this.displayList.splice(index, 1);
        // 添加到最前面
        this.displayList.unshift(selectedItem);
        // 更新序号
        this.updateSortNumbers();
        // 保持选中状态
        this.$nextTick(() => {
          this.$refs.tableRef.toggleRowSelection(selectedItem);
        });
      }
    },

    /** 上移 */
    moveUp() {
      if (this.selectedRows.length !== 1) {
        this.$modal.msgWarning('请选择一项进行操作');
        return;
      }

      const selectedId = this.selectedRows[0].id;
      const index = this.displayList.findIndex(item => item.id === selectedId);

      if (index > 0) {
        // 与上一项交换位置
        [this.displayList[index - 1], this.displayList[index]] =
          [this.displayList[index], this.displayList[index - 1]];

        // 更新序号
        this.updateSortNumbers();
        // 保持选中状态
        this.$nextTick(() => {
          const newItem = this.displayList[index - 1];
          this.$refs.tableRef.clearSelection();
          this.$refs.tableRef.toggleRowSelection(newItem);
        });
      }
    },

    /** 下移 */
    moveDown() {
      if (this.selectedRows.length !== 1) {
        this.$modal.msgWarning('请选择一项进行操作');
        return;
      }

      const selectedId = this.selectedRows[0].id;
      const index = this.displayList.findIndex(item => item.id === selectedId);

      if (index < this.displayList.length - 1) {
        // 与下一项交换位置
        [this.displayList[index], this.displayList[index + 1]] =
          [this.displayList[index + 1], this.displayList[index]];

        // 更新序号
        this.updateSortNumbers();
        // 保持选中状态
        this.$nextTick(() => {
          const newItem = this.displayList[index + 1];
          this.$refs.tableRef.clearSelection();
          this.$refs.tableRef.toggleRowSelection(newItem);
        });
      }
    },

    /** 置底 */
    moveToBottom() {
      if (this.selectedRows.length !== 1) {
        this.$modal.msgWarning('请选择一项进行操作');
        return;
      }

      const selectedId = this.selectedRows[0].id;
      const index = this.displayList.findIndex(item => item.id === selectedId);

      if (index < this.displayList.length - 1) {
        // 移除选中的项目
        const [selectedItem] = this.displayList.splice(index, 1);
        // 添加到最后面
        this.displayList.push(selectedItem);
        // 更新序号
        this.updateSortNumbers();
        // 保持选中状态
        this.$nextTick(() => {
          this.$refs.tableRef.toggleRowSelection(selectedItem);
        });
      }
    },

    /** 更新序号（按位置重新编号） */
    updateSortNumbers() {
      this.displayList.forEach((item, index) => {
        item.customSortOrder = index + 1;
      });
    },

    /** 保存排序 */
    async saveSort() {
      if (this.displayList.length === 0) {
        this.$modal.msgWarning('没有数据可保存');
        return;
      }

      try {
        this.saveLoading = true;

        // 1. 获取排序后的顺序（使用手动输入的序号或位置序号）
        const sortData = this.displayList.map((item) => ({
          id: item.id,
          sortOrder: item.customSortOrder || 0
        }));

        // 2. 调用后端API保存排序
        await PolicyCommunicationsApi.batchUpdateSort(sortData);

        this.$modal.msgSuccess('排序保存成功');
        this.isSorting = false;
        this.selectedRows = [];
        // 重新加载数据，确保获取到最新的排序
        await this.getList();
      } catch (error) {
        console.error('保存排序失败:', error);
        this.$modal.msgError('排序保存失败: ' + (error.message || '未知错误'));
      } finally {
        this.saveLoading = false;
      }
    },

    /** 打开表单 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },

    /** 删除操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除政策沟通交流编号为"' + id + '"的数据项?')
      try {
        await PolicyCommunicationsApi.deletePolicyCommunications(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 导出操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有政策沟通交流数据项?');
      try {
        this.exportLoading = true;
        const data = await PolicyCommunicationsApi.exportPolicyCommunicationsExcel(this.queryParams);
        this.$download.excel(data, '政策沟通交流.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  }
};
</script>

<style scoped>
.sort-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.sort-tip {
  margin-top: 10px;
  color: #606266;
  font-size: 13px;
  text-align: center;
}

.original-sort {
  display: block;
  font-size: 10px;
  color: #909399;
  margin-top: 2px;
}

/* 调整输入框样式 */
::v-deep .el-input-number--mini {
  width: 80px;
}

::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
  width: 20px;
}

/* 选中行样式 */
::v-deep .el-table .selected-row {
  background-color: #ecf5ff !important;
}

::v-deep .el-table .selected-row:hover > td {
  background-color: #ecf5ff !important;
}
</style>
