<template>
  <div class="app-container">
    <div class="header-container box-card">
      <div class="left-title">
        <span class="title-text">订单申诉管理</span>
      </div>
      <div class="right-search">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item prop="orderCode">
            <el-input v-model="queryParams.orderCode" placeholder="订单号" clearable style="width: 200px"
              @keyup.enter="handleQuery">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="fulfillerName">
            <el-input v-model="queryParams.fulfillerName" placeholder="履约者姓名" clearable style="width: 150px"
              @keyup.enter="handleQuery">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="service">
            <el-select v-model="queryParams.service" placeholder="实际服务" clearable style="width: 160px"
              @change="handleQuery">
              <el-option v-for="item in serviceOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="content-container box-card">
      <el-table v-loading="loading" :data="subOrderAppealList"
        :header-cell-style="{ background: '#f8f9fa', color: '#606266', fontWeight: 'bold' }">
        <el-table-column label="关联订单号" align="left" prop="orderCode" min-width="150" />
        <el-table-column label="实际服务" align="center" prop="serviceName" min-width="120" />
        <el-table-column label="履约者" align="center" prop="fulfillerName" min-width="100" />
        <el-table-column label="上报图片" align="center" prop="photoUrls" min-width="120">
          <template #default="scope">
            <div style="display: flex; gap: 5px; justify-content: center; flex-wrap: wrap;">
              <template v-if="scope.row.photoUrls">
                <image-preview v-for="(url, index) in scope.row.photoUrls.split(',')" :key="index" :src="url"
                  :width="40" :height="40" />
              </template>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="提交内容" align="left" prop="reason" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="提交时间" align="center" prop="createTime" width="180" sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus !== undefined"
              :type="subOrderAppealDict.AuditStatus[scope.row.auditStatus]?.tagType || 'info'">
              {{ subOrderAppealDict.AuditStatus[scope.row.auditStatus]?.label || scope.row.auditStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" v-hasPermi="['order:appeal:query']"
              @click="handleDetail(scope.row)">详情</el-button>
            <el-button v-if="scope.row.auditStatus === 0 && checkPermi(['order:appeal:audit'])" link type="primary"
              @click="handleAudit(scope.row)">审核</el-button>
            <el-button link type="danger" v-hasPermi="['order:appeal:remove']"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 详情对话框 -->
    <el-dialog title="申诉详情" v-model="openDetail" width="600px" append-to-body custom-class="detail-dialog">
      <div class="detail-container">
        <div class="detail-item">
          <span class="label">订单号：</span>
          <span class="value">{{ form.orderCode }}</span>
        </div>
        <div class="detail-item">
          <span class="label">实际服务：</span>
          <span class="value">{{ form.serviceName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">履约者：</span>
          <span class="value">{{ form.fulfillerName }}</span>
        </div>

        <div class="detail-item full-width">
          <span class="label">提交时间：</span>
          <span class="value">{{ parseTime(form.createTime) }}</span>
        </div>
        <div class="detail-item full-width">
          <span class="label">申诉理由：</span>
          <div class="reason-content">{{ form.reason }}</div>
        </div>
        <div class="detail-item full-width">
          <span class="label">图片展示：</span>
          <div class="photo-list" v-if="form.photoUrls">
            <image-preview v-for="(url, index) in form.photoUrls.split(',')" :key="index" :src="url" :width="120"
              :height="120" style="margin-right: 10px; margin-bottom: 10px;" />
          </div>
        </div>
        <div class="detail-item">
          <span class="label">审核状态：</span>
          <span class="value">
            <el-tag v-if="form.auditStatus !== undefined"
              :type="subOrderAppealDict.AuditStatus[form.auditStatus]?.tagType || 'info'">
              {{ subOrderAppealDict.AuditStatus[form.auditStatus]?.label || form.auditStatus }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">审核人：</span>
          <span class="value">{{ form.auditorName || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">审核时间：</span>
          <span class="value">{{ parseTime(form.auditTime) || '-' }}</span>
        </div>
        <div class="detail-item full-width" v-if="form.rejectReason">
          <span class="label">驳回理由：</span>
          <div class="reason-content">{{ form.rejectReason }}</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openDetail = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认详情展示 -->
    <el-dialog title="确认删除申诉" v-model="openView" width="600px" append-to-body custom-class="detail-dialog">
      <div class="detail-container">
        <div class="detail-item">
          <span class="label">订单号：</span>
          <span class="value">{{ form.orderCode }}</span>
        </div>
        <div class="detail-item">
          <span class="label">实际服务：</span>
          <span class="value">{{ form.serviceName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">履约者：</span>
          <span class="value">{{ form.fulfillerName }}</span>
        </div>

        <div class="detail-item full-width">
          <span class="label">提交时间：</span>
          <span class="value">{{ parseTime(form.createTime) }}</span>
        </div>
        <div class="detail-item full-width">
          <span class="label">申诉理由：</span>
          <div class="reason-content">{{ form.reason }}</div>
        </div>
        <div class="detail-item full-width">
          <span class="label">图片展示：</span>
          <div class="photo-list" v-if="form.photoUrls">
            <image-preview v-for="(url, index) in form.photoUrls.split(',')" :key="index" :src="url" :width="120"
              :height="120" style="margin-right: 10px; margin-bottom: 10px;" />
          </div>
        </div>
        <div class="detail-item">
          <span class="label">审核状态：</span>
          <span class="value">
            <el-tag v-if="form.auditStatus !== undefined"
              :type="subOrderAppealDict.AuditStatus[form.auditStatus]?.tagType || 'info'">
              {{ subOrderAppealDict.AuditStatus[form.auditStatus]?.label || form.auditStatus }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">审核人：</span>
          <span class="value">{{ form.auditorName || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">审核时间：</span>
          <span class="value">{{ parseTime(form.auditTime) || '-' }}</span>
        </div>
        <div class="detail-item full-width" v-if="form.rejectReason">
          <span class="label">驳回理由：</span>
          <div class="reason-content">{{ form.rejectReason }}</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitDelete">确认删除</el-button>
          <el-button @click="openView = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="申诉审核处理" v-model="openAudit" width="500px" append-to-body class="audit-dialog">
      <div class="audit-content">
        <el-form :model="auditForm" :rules="auditRules" ref="auditRef" label-position="top">
          <el-form-item label="审核结果判定" prop="result">
            <el-radio-group v-model="auditForm.result" class="full-width-radio">
              <el-radio-button :label="1">
                <el-icon>
                  <CircleCheck />
                </el-icon> 审核通过
              </el-radio-button>
              <el-radio-button :label="2">
                <el-icon>
                  <CircleClose />
                </el-icon> 驳回申请
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <transition name="el-zoom-in-top">
            <el-form-item label="驳回原因说明" prop="reason" v-if="auditForm.result === 2">
              <el-input v-model="auditForm.reason" type="textarea" :rows="4" placeholder="请详细说明驳回该申请的具体原因..." />
            </el-form-item>
          </transition>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" size="large" @click="submitAudit" class="submit-btn">确认提交审核</el-button>
          <el-button size="large" @click="openAudit = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SubOrderAppeal">
import { listSubOrderAppeal, delSubOrderAppeal, auditSubOrderAppeal, getSubOrderAppeal } from "@/api/order/subOrderAppeal";
import { listAllService } from "@/api/service/list";
import { parseTime } from "@/utils/ruoyi";
import { checkPermi } from "@/utils/permission";
import subOrderAppealDict from "@/json/subOrderAppeal.json";
import { useRoute } from "vue-router";

const route = useRoute();
const { proxy } = getCurrentInstance();

const subOrderAppealList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const openView = ref(false);
const openDetail = ref(false);
const openAudit = ref(false);
const serviceOptions = ref([]);

const auditForm = ref({
  id: undefined,
  result: 1,
  reason: undefined
});

const auditRules = ref({
  result: [{ required: true, message: "请选择审核结果", trigger: "change" }],
  reason: [{ required: true, message: "请输入驳回原因", trigger: "blur" }]
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderCode: undefined, // 改为 orderCode
    fulfillerName: undefined, // 履约者名称
    service: undefined,
    reason: undefined,
  },
});

const { queryParams, form } = toRefs(data);

/** 查询服务列表用于下拉框 */
function getServiceList() {
  listAllService().then(response => {
    serviceOptions.value = response.data;
    // 数据记载后重新渲染列表，确保 serviceName 正确映射
    getList();
  });
}

/** 查询列表 */
function getList() {
  loading.value = true;
  listSubOrderAppeal(queryParams.value).then(response => {
    subOrderAppealList.value = response.rows.map(item => {
      // 匹配服务名称
      const serviceObj = serviceOptions.value.find(s => s.id === item.service);
      return {
        ...item,
        serviceName: serviceObj ? serviceObj.name : item.service
      };
    });
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置查询操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 详情按钮操作 */
function handleDetail(row) {
  openDetail.value = true;
  form.value = { ...row };
}

/** 删除获取详情操作 */
function handleDelete(row) {
  openView.value = true;
  form.value = { ...row };
}

/** 确认删除请求 */
function submitDelete() {
  delSubOrderAppeal(form.value.id).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    openView.value = false;
    getList();
  });
}

/** 审核按钮操作 */
function handleAudit(row) {
  auditForm.value = {
    id: row.id,
    result: 1,
    reason: undefined
  };
  openAudit.value = true;
  if (proxy.$refs["auditRef"]) {
    proxy.$refs["auditRef"].resetFields();
  }
}

/** 提交审核 */
function submitAudit() {
  proxy.$refs["auditRef"].validate(valid => {
    if (valid) {
      auditSubOrderAppeal(auditForm.value).then(response => {
        proxy.$modal.msgSuccess("审核成功");
        openAudit.value = false;
        getList();
      });
    }
  });
}

// 初始化加载
getServiceList();

// 处理从消息跳转过来的情况
onMounted(() => {
  const id = route.query.id;
  if (id) {
    getSubOrderAppeal(id).then(response => {
      const data = response.data;
      const serviceObj = serviceOptions.value.find(s => s.id === data.service);
      form.value = {
        ...data,
        serviceName: serviceObj ? serviceObj.name : data.service
      };
      openDetail.value = true;
    });
  }
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.box-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 25px;

  .left-title {
    .title-text {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .right-search {
    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 12px;
    }

    :deep(.el-input__wrapper) {
      border-radius: 20px;
      padding-left: 15px;
    }

    :deep(.el-select .el-input__wrapper) {
      border-radius: 20px;
    }
  }
}

.content-container {
  padding: 0;
  overflow: hidden;

  :deep(.el-table) {
    --el-table-header-bg-color: #f8f9fa;
    border-radius: 8px 8px 0 0;
  }
}

.detail-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px;

  .detail-item {
    width: 45%;
    display: flex;
    align-items: center;

    &.full-width {
      width: 100%;
      align-items: flex-start;
      flex-direction: column;
    }

    .label {
      color: #909399;
      font-weight: bold;
      margin-right: 10px;
      white-space: nowrap;
    }

    .value {
      color: #303133;

      &.highlighting {
        color: #f56c6c;
        font-weight: bold;
      }
    }

    .reason-content {
      margin-top: 8px;
      padding: 12px;
      background: #f8f9fa;
      border-radius: 4px;
      width: 100%;
      color: #606266;
      line-height: 1.6;
    }

    .photo-list {
      margin-top: 10px;
    }
  }
}

:deep(.el-button--primary) {
  border-radius: 20px;
  padding: 8px 20px;
}

:deep(.dialog-footer) {
  text-align: center;
  padding-top: 10px;
  padding-bottom: 10px;
}

.audit-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    padding: 20px 25px;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-weight: bold;
      color: #303133;
    }
  }

  .audit-content {
    padding: 10px 15px;
  }

  .full-width-radio {
    width: 100%;
    display: flex;

    :deep(.el-radio-button) {
      flex: 1;

      .el-radio-button__inner {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        height: 45px;
        font-size: 15px;
      }
    }
  }

  .full-width-input {
    width: 100%;

    :deep(.el-input__wrapper) {
      height: 40px;
    }
  }

  .input-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    line-height: 1.4;
  }

  :deep(.el-form-item__label) {
    font-weight: bold;
    padding-bottom: 8px;
  }

  .submit-btn {
    width: 160px;
    height: 45px;
    font-size: 16px;
    font-weight: bold;
    background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
    border: none;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

    &:hover {
      opacity: 0.9;
      transform: translateY(-1px);
    }
  }
}
</style>
