<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="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="policyTitle" width="300">
        <template v-slot="scope">
          <el-link
            type="primary"
            :underline="false"
            @click="handlePolicyTitleClick(scope.row)"
            :title="scope.row.policyTitle"
            style="text-align: left; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
          >
            {{ scope.row.policyTitle }}
          </el-link>
        </template>
      </el-table-column>

      <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 v-if="statusType === 'pending'" label="剩余办理时限" align="center" width="160">
        <template v-slot="scope">
          <div :style="{
            color: getDeadlineColor(scope.row.remainingWorkdays),
            fontWeight: scope.row.remainingWorkdays <= 3 ? 'bold' : 'normal'
          }">
            {{ formatRemainingWorkdays(scope.row.remainingWorkdays) }}
          </div>
        </template>
      </el-table-column>

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

      <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
            v-if="statusType === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleProcess(scope.row)"
            v-hasPermi="['server:policy-communications:update']">办理</el-button>

          <!-- 已回复和已发布状态显示公开/不公开按钮，但需要满足条件 -->
          <el-button
            v-else-if="(statusType === 'replied' || statusType === 'published') && canTogglePublic(scope.row)"
            size="mini"
            type="text"
            :icon="scope.row.replayIsPublic === 1 ? 'el-icon-unlock' : 'el-icon-lock'"
            @click="handleTogglePublic(scope.row)"
            v-hasPermi="['server:policy-communications:update']">
            {{ getTogglePublicText(scope.row) }}
          </el-button>

          <!-- 不予办理状态不显示操作按钮（或显示不可操作的提示） -->
<!--          <el-button
            v-else-if="statusType === 'rejected'"
            size="mini"
            type="text"
            disabled
            icon="el-icon-close">
            不予办理
          </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 {updateStatusPolicyCommunications} from "@/api/server/policycommunications";

export default {
  name: "PolicyCommunicationsBase",
  components: {
    PolicyCommunicationsForm,
  },
  props: {
    // 状态类型：'pending', 'replied', 'published', 'rejected'
    statusType: {
      type: String,
      default: 'pending'
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原始列表数据
      originalList: [],
      // 显示列表数据（排序时会修改）
      displayList: [],
      // 是否正在排序
      isSorting: false,
      // 保存排序加载状态
      saveLoading: false,
      // 选中的行
      selectedRows: [],
      nonWorkdays: [], // 存储休息日数据
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        policyId: null,
        policyTitle: null,
        replyDept: null,
        replyDeptid: null,
        userName: null,
        mobile: null,
        submitType: null,
        title: null,
        submitTime: [],
      },
    };
  },
  created() {
    // 先加载休息日数据，再加载列表数据
    // this.loadNonWorkdays();
    this.getList();
  },
  methods: {
    /** 点击政策标题跳转 */
    handlePolicyTitleClick(row) {
      if (row.puburl) {
        // 在新标签页中打开链接
        window.open(row.puburl, '_blank');
      } else {
        this.$modal.msgWarning('该政策暂无相关链接');
      }
    },
    /** 加载休息日数据 */
    async loadNonWorkdays() {
      try {
        const res = await PolicyCommunicationsApi.getNonWorkdays();
        this.nonWorkdays = res.data || [];
      } catch (error) {
        console.error('加载休息日数据失败:', error);
        this.nonWorkdays = [];
      }
    },
    /** 根据状态类型获取对应的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, // 初始化为数据库中的排序值
          // 为待处理状态计算剩余工作日
/*          remainingWorkdays: this.statusType === 'pending'
            ? this.calculateRemainingWorkdays(item.submitTime)
            : null*/
          // 后端已经计算好了，直接使用
          remainingWorkdays: item.remainingWorkdays
        }));
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    /** 检查是否为工作日 */
    isWorkday(date) {
      // 检查是否为休息日表中的日期
      const dateStr = this.formatDate(date, 'yyyyMMdd');
      return !this.nonWorkdays.some(day => day.n_date === dateStr);
    },

    /** 格式化日期为字符串 */
    formatDate(date, format = 'yyyy-MM-dd') {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      if (format === 'yyyyMMdd') {
        return `${year}${month}${day}`;
      }
      return `${year}-${month}-${day}`;
    },

    /** 计算剩余工作日（从提交时间开始，20个工作日时限） */
    calculateRemainingWorkdays(submitTime) {
      if (!submitTime) return 20; // 如果没有提交时间，默认显示完整时限

      const submitDate = new Date(submitTime);
      const today = new Date();

      // 设置时间为0点，避免时间差影响
      today.setHours(0, 0, 0, 0);
      const submitDateStart = new Date(submitDate);
      submitDateStart.setHours(0, 0, 0, 0);

      let workdaysCounted = 0;
      let currentDate = new Date(submitDateStart);

      // 计算从提交日开始到今天的完整天数
      // 如果今天已经过完，从第二天开始算
      const startDate = new Date(submitDateStart);

      // 循环计算已经过去的工作日
      while (startDate < today) {
        if (this.isWorkday(startDate)) {
          workdaysCounted++;
        }
        startDate.setDate(startDate.getDate() + 1);
      }

      // 计算剩余工作日
      let remainingWorkdays = 20 - workdaysCounted;

      // 如果剩余为负数，表示已超期
      if (remainingWorkdays < 0) {
        return remainingWorkdays;
      }

      return remainingWorkdays;
    },

    /** 格式化剩余工作日显示 */
    formatRemainingWorkdays(remaining) {
      if (remaining === 0) {
        return '0个工作日';
      }

      if (remaining < 0) {
        return `已超期${Math.abs(remaining)}天`;
      }

      if (remaining === 1) {
        return '1个工作日';
      }

      if (remaining <= 3) {
        return `${remaining}个工作日`;
      }

      return `${remaining}个工作日`;
    },

    /** 获取截止日期的颜色 */
    getDeadlineColor(remaining) {
      if (remaining < 0) {
        return '#F56C6C'; // 红色：已超期
      }

      if (remaining === 0) {
        return '#E6A23C'; // 橙色：今日截止
      }

      if (remaining <= 3) {
        return '#E6A23C'; // 橙色：紧急（3天内）
      }

      return '#67C23A'; // 绿色：正常
    },

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

    /** 办理操作 */
    handleProcess(row) {
      this.$refs["formRef"].open(row.id, false, 'process');
    },

    /** 检查是否可以切换公开状态 */
    canTogglePublic(row) {
      // 如果用户提交时不公开，则不能设置为公开
      if (row.submitIsPublic === 0) {
        return false;
      }

      // 只有已回复或已发布的状态才能切换
      // 这里我们假设已回复和已发布的状态都能切换
      // 可以根据实际业务需求调整
      return true;
    },

    /** 获取切换公开状态的按钮文本 */
    getTogglePublicText(row) {
      if (!this.canTogglePublic(row)) {
        return '不可操作';
      }

      // 如果当前是公开状态，按钮显示"设为不公开"
      if (row.replayIsPublic === 1) {
        return '设为不公开';
      }

      // 如果当前是不公开状态，需要检查是否可以设置为公开
      // 如果用户提交时选择公开，可以设置为公开
      if (row.submitIsPublic === 1) {
        return '设为公开';
      }

      // 其他情况返回不可操作
      return '不可操作';
    },

    /** 切换公开状态 */
    async handleTogglePublic(row) {
      try {
        // 检查是否可以切换
        if (!this.canTogglePublic(row)) {
          this.$modal.msgWarning('该记录不可设置公开状态');
          return;
        }

        const newStatus = row.replayIsPublic === 1 ? 0 : 1;
        const statusText = newStatus === 1 ? '公开' : '不公开';

        // 额外检查：如果用户提交时不公开，不能设置为公开
        if (newStatus === 1 && row.submitIsPublic === 0) {
          this.$modal.msgWarning('用户提交时选择不公开，不能设置为公开状态');
          return;
        }

        await this.$modal.confirm(`是否确认将该记录设置为${statusText}状态？`);

        const data = {
          id: row.id,
          replayIsPublic: newStatus
        };

        await PolicyCommunicationsApi.updateStatusPolicyCommunications(data);
        this.$modal.msgSuccess(`已成功设置为${statusText}`);

        // 重新加载数据
        await this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('切换公开状态失败:', error);
          this.$modal.msgError('操作失败');
        }
      }
    },

    /** 表格行类名 */
    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;

        const sortData = this.displayList.map((item) => ({
          id: item.id,
          sortOrder: item.customSortOrder || 0
        }));

        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>
