<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="right" prop="fulfillmentCommission" width="120">
          <template #default="scope">
            <span>{{ (scope.row.fulfillmentCommission / 100).toFixed(2) }}</span>
          </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="160" class-name="small-padding fixed-width">
          <template #default="scope">
            <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="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">
          <span class="label">履约佣金：</span>
          <span class="value highlighting">{{ (form.fulfillmentCommission / 100).toFixed(2) }} 元</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>
      <el-form :model="auditForm" :rules="auditRules" ref="auditRef" label-width="100px">
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="auditForm.result">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驳回原因" prop="reason" v-if="auditForm.result === 2">
          <el-input v-model="auditForm.reason" type="textarea" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="openAudit = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SubOrderAppeal">
import { listSubOrderAppeal, delSubOrderAppeal, auditSubOrderAppeal } 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";

const { proxy } = getCurrentInstance();

const subOrderAppealList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const openView = 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 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();
</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: 20px;
}
</style>
