<template>
  <div class="p-2 inspection-task-page">
    <!-- 顶部数据卡片 -->
    <el-row :gutter="20" class="mb-2">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-info">
              <div class="stat-title">今日应打卡</div>
              <div class="stat-value">{{ stats.todayShould || 0 }}</div>
            </div>
            <div class="stat-icon stat-icon-blue">
              <el-icon><Calendar /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-info">
              <div class="stat-title">今日已打卡</div>
              <div class="stat-value">{{ stats.todayChecked || 0 }}</div>
            </div>
            <div class="stat-icon stat-icon-green">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-info">
              <div class="stat-title">异常打卡</div>
              <div class="stat-value">{{ stats.abnormal || 0 }}</div>
            </div>
            <div class="stat-icon stat-icon-orange">
              <el-icon><Warning /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-info">
              <div class="stat-title">未打卡</div>
              <div class="stat-value">{{ stats.unchecked || 0 }}</div>
            </div>
            <div class="stat-icon stat-icon-red">
              <el-icon><Clock /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="巡检类型" prop="taskType">
              <el-select v-model="queryParams.taskType" placeholder="全部" clearable style="width: 180px">
                <el-option v-for="dict in inspection_type_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="门店" prop="storeId">
              <el-select
                v-model="queryParams.storeId"
                placeholder="全部"
                clearable
                filterable
                style="width: 200px"
                @change="handleQuery"
              >
                <el-option v-for="d in storeOptions" :key="d.value" :label="d.label" :value="d.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="打卡状态" prop="recordStatus">
              <el-select v-model="queryParams.recordStatus" placeholder="全部" clearable style="width: 180px">
                <el-option v-for="dict in inspection_status_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="打卡结果" prop="checkResult">
              <el-select v-model="queryParams.checkResult" placeholder="全部" clearable style="width: 180px">
                <el-option v-for="dict in inspection_result_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 数据表格区域 -->
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb-2">
          <el-col :span="1.5">
            <el-button v-hasPermi="['risk:qualityInspectionTask:add']" type="primary" plain icon="Plus" @click="handleAdd">新增巡检打卡</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="taskList" border>
        <el-table-column label="巡检任务名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
        <el-table-column label="巡检类型" align="center" prop="taskType" width="160" :show-overflow-tooltip="true" />
        <el-table-column label="打卡方式" align="center" prop="checkMethod" width="100">
          <template #default="scope">
            <el-tag :type="getMethodTag(scope.row.checkMethod)">{{ scope.row.checkMethod || '常规' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="门店" align="center" prop="storeName" width="140" :show-overflow-tooltip="true" />
        <el-table-column label="打卡地点" align="center" prop="location" width="160" :show-overflow-tooltip="true" />
        <el-table-column label="责任人" align="center" prop="inspectorName" width="100" />
        <el-table-column label="打卡状态" align="center" prop="recordStatus" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.recordStatus)">{{ scope.row.recordStatus || '未打卡' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="打卡结果" align="center" prop="checkResult" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.checkResult" :type="getResultTag(scope.row.checkResult)">{{ scope.row.checkResult }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="240" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['risk:qualityInspectionTask:list']" link type="primary" icon="Document" @click="handleViewRecords(scope.row)">打卡记录</el-button>
            <el-button v-hasPermi="['risk:qualityInspectionTask:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-hasPermi="['risk:qualityInspectionTask:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body @close="closeDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入巡检任务名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择巡检类型" style="width: 100%">
                <el-option v-for="dict in inspection_type_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店" prop="storeName">
              <el-input v-model="form.storeName" placeholder="请输入门店/总部名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置区域" prop="location">
              <el-input v-model="form.location" placeholder="巡检点物理名称(如XX车间XX工位)" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡检周期" prop="cycle">
              <el-select v-model="form.cycle" placeholder="请选择巡检周期" style="width: 100%" @change="onCycleChange">
                <el-option v-for="dict in inspection_cycle_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开启扫码打卡" prop="scanEnabled">
              <el-switch v-model="form.scanEnabled" active-text="是" inactive-text="否" @change="onScanChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.scanEnabled" :span="12">
            <el-form-item label="打卡设备编码" prop="punchDeviceCode">
              <el-input
                v-model="form.punchDeviceCode"
                placeholder="请输入巡检点设备编码(与现场二维码一致)"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="纬度" prop="lat">
              <el-input-number v-model="form.lat" :precision="6" :min="-90" :max="90" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="lng">
              <el-input-number v-model="form.lng" :precision="6" :min="-180" :max="180" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 巡检时间:根据周期动态适配 -->
        <el-form-item label="巡检时间" prop="timeConfig">
          <div v-if="form.cycle === '每日' || !form.cycle">
            <el-tag v-for="(t, idx) in timeSlotList" :key="idx" closable @close="removeTimeSlot(idx)" style="margin-right: 8px">
              {{ t }}
            </el-tag>
            <el-button size="small" type="primary" plain @click="openAddTimeSlot">添加时间段</el-button>
          </div>
          <div v-else-if="form.cycle === '每周'">
            <el-checkbox-group v-model="weekDayList">
              <el-checkbox v-for="d in weekDayOptions" :key="d.value" :label="d.value">{{ d.label }}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-else-if="form.cycle === '每月'">
            <el-select v-model="monthDayList" multiple placeholder="选择执行日期" style="width: 100%">
              <el-option v-for="d in 31" :key="d" :label="`${d}号`" :value="d" />
            </el-select>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="责任人" prop="inspectorId">
              <el-select
                v-model="form.inspectorId"
                placeholder="请选择责任人(本部门及下级部门)"
                style="width: 100%"
                filterable
                clearable
                @change="onInspectorChange"
              >
                <el-option v-for="u in deptChainUserOptions" :key="String(u.userId)" :label="u.nickName" :value="u.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人" prop="auditorId">
              <el-select
                v-model="form.auditorId"
                placeholder="请选择审核人(本部门及下级部门)"
                style="width: 100%"
                filterable
                clearable
                @change="onAuditorChange"
              >
                <el-option v-for="u in deptChainUserOptions" :key="String(u.userId)" :label="u.nickName" :value="u.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 打卡项目:多行 -->
        <el-divider content-position="left">
          <span style="font-weight: bold">打卡项目</span>
          <el-button link type="primary" icon="Plus" @click="addInspectionItem">添加项目</el-button>
        </el-divider>
        <el-table :data="form.itemList" border>
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="项目大类" align="center" width="160">
            <template #default="scope">
              <el-select v-model="scope.row.itemType" placeholder="请选择" size="small" style="width: 100%">
                <el-option v-for="dict in inspection_item_type_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="巡检内容" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.itemContent" placeholder="请输入巡检内容" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="巡检标准" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.itemStandard" placeholder="请输入巡检标准" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="是否拍照" align="center" width="80">
            <template #default="scope">
              <el-switch v-model="scope.row.needPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button link type="danger" size="small" icon="Delete" @click="removeInspectionItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存巡检任务</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加时间段弹窗 -->
    <el-dialog v-model="timeSlotDialog.visible" title="添加时间段" width="420px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="开始时间">
          <el-time-picker v-model="timeSlotForm.start" placeholder="开始时间" value-format="HH:mm" format="HH:mm" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-time-picker v-model="timeSlotForm.end" placeholder="结束时间" value-format="HH:mm" format="HH:mm" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="timeSlotDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddTimeSlot">确定</el-button>
      </template>
    </el-dialog>

    <!-- 打卡记录对话框 -->
    <el-dialog v-model="recordDialog.visible" title="打卡记录" width="900px" append-to-body>
      <el-table v-loading="recordLoading" :data="recordList" border>
        <el-table-column label="打卡时间" align="center" prop="checkInTime" width="180" />
        <el-table-column label="打卡人" align="center" prop="inspectorName" width="100" />
        <el-table-column label="打卡地点" align="center" prop="checkInLocation" :show-overflow-tooltip="true" />
        <el-table-column label="问题数" align="center" prop="problemCount" width="80" />
        <el-table-column label="总数" align="center" prop="totalCount" width="80" />
        <el-table-column label="打卡状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.recordStatus)">{{ scope.row.recordStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="打卡结果" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.checkResult" :type="getResultTag(scope.row.checkResult)">{{ scope.row.checkResult }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus" :type="getAuditStatusTag(scope.row.auditStatus)">{{ scope.row.auditStatus }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
            <el-button
              v-if="!scope.row.auditStatus || scope.row.auditStatus === '待审核'"
              v-hasPermi="['risk:qualityInspectionRecord:review']"
              link
              type="primary"
              @click="handleAuditRecord(scope.row)"
            >审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="recordDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 打卡详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="打卡详情" width="700px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="任务名称">{{ detailForm.taskName }}</el-descriptions-item>
        <el-descriptions-item label="打卡时间">{{ detailForm.checkInTime }}</el-descriptions-item>
        <el-descriptions-item label="打卡人">{{ detailForm.inspectorName }}</el-descriptions-item>
        <el-descriptions-item label="打卡状态">
          <el-tag :type="getStatusTag(detailForm.recordStatus)">{{ detailForm.recordStatus }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="打卡结果">
          <el-tag v-if="detailForm.checkResult" :type="getResultTag(detailForm.checkResult)">{{ detailForm.checkResult }}</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="打卡地点">{{ detailForm.checkInLocation }}</el-descriptions-item>
        <el-descriptions-item label="问题数/总数">{{ detailForm.problemCount || 0 }}/{{ detailForm.totalCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="detailForm.auditStatus" :type="getAuditStatusTag(detailForm.auditStatus)">{{ detailForm.auditStatus }}</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailForm.auditorName" label="审核人">{{ detailForm.auditorName }} ({{ detailForm.auditTime || '-' }})</el-descriptions-item>
        <el-descriptions-item v-if="detailForm.auditOpinion" label="审核意见" :span="1">
          <span :class="['audit-opinion', detailForm.auditStatus === '审核不通过' ? 'reject' : 'pass']">
            {{ detailForm.auditOpinion }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <h4 style="margin: 16px 0 8px">巡检项目明细</h4>
      <el-table :data="detailForm.itemList" border size="small">
        <el-table-column label="项目大类" prop="itemType" width="120" />
        <el-table-column label="巡检内容" prop="itemContent" />
        <el-table-column label="巡检结果" prop="checkResult" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.checkResult" :type="getResultTag(scope.row.checkResult)" size="small">{{ scope.row.checkResult }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="照片" width="80">
          <template #default="scope">
            <span v-if="scope.row.checkPhotos">{{ scope.row.checkPhotos }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialog.visible"
      title="巡检打卡审核"
      width="520px"
      append-to-body
      :close-on-click-modal="false"
      @close="closeAuditDialog"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="任务名称">
          <span class="readonly-text">{{ auditForm.taskName }}</span>
        </el-form-item>
        <el-form-item label="打卡人">
          <span class="readonly-text">{{ auditForm.inspectorName }}</span>
        </el-form-item>
        <el-form-item label="打卡时间">
          <span class="readonly-text">{{ auditForm.checkInTime }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio value="审核通过">通过</el-radio>
            <el-radio value="审核不通过">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditForm.auditStatus === '审核不通过'" label="不通过原因" prop="auditOpinion">
          <el-input
            v-model="auditForm.auditOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入不通过原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取消</el-button>
          <el-button v-hasPermi="['risk:qualityInspectionRecord:review']" type="primary" @click="submitAudit">确认审核</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="QualityInspectionTask" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import {
  listQualityInspectionTask,
  getQualityInspectionTask,
  addQualityInspectionTask,
  updateQualityInspectionTask,
  delQualityInspectionTask,
  getQualityInspectionStats,
  listQualityInspectionRecordByTask
} from '@/api/risk/qualityInspectionTask';
// 巡检项目明细(项目大类/巡检内容/巡检标准/是否拍照)的保存,暂时复用风控同一张 risk_inspection_item 表
// 后续如果品控需要单独字段,可以新增 /quality/inspectionItem 路由
import { listInspectionItemByTask } from '@/api/risk/inspectionItem';
import { auditInspectionRecord } from '@/api/risk/inspectionRecord';
import type {
  RiskInspectionTaskBo,
  RiskInspectionTaskVo,
  RiskInspectionItemVo,
  RiskInspectionRecordVo,
  RiskInspectionRecordBo,
  InspectionStatsVo
} from '@/api/risk/types';
import { listByCurrentDeptChainUsers } from '@/api/system/user';
import type { UserVO } from '@/api/system/user/types';
import { listDept } from '@/api/system/dept';
import { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import { Calendar, Check, Warning, Clock } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface InspectionItemForm {
  id?: number;
  itemType: string;
  itemContent: string;
  itemStandard: string;
  needPhoto: boolean;
}

const taskList = ref<RiskInspectionTaskVo[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
const recordList = ref<RiskInspectionRecordVo[]>([]);
const recordLoading = ref(false);
// 责任人/审核人选择器数据(当前登录用户所在部门及所有下级部门用户)
const deptChainUserOptions = ref<UserVO[]>([]);
// 门店下拉(集团总部 + 65 个门店)
const storeOptions = ref<Array<{ label: string; value: number }>>([]);
// 字典(品控专用字典 quality_inspection_type / quality_project_category,
//  通用字典 inspection_status / inspection_result / inspection_cycle 与风控共用)
const {
  quality_inspection_type: inspection_type_dict,
  quality_project_category: inspection_item_type_dict,
  inspection_status: inspection_status_dict,
  inspection_result: inspection_result_dict,
  inspection_cycle: inspection_cycle_dict
} = toRefs<any>(
  proxy?.useDict(
    'quality_inspection_type',
    'quality_project_category',
    'inspection_status',
    'inspection_result',
    'inspection_cycle'
  )
);

// 统计
const stats = ref<InspectionStatsVo>({
  todayShould: 0,
  todayChecked: 0,
  abnormal: 0,
  unchecked: 0
});

// 时间配置
const timeSlotList = ref<string[]>([]);
const weekDayList = ref<string[]>([]);
const monthDayList = ref<number[]>([]);
const weekDayOptions = [
  { value: '1', label: '周一' },
  { value: '2', label: '周二' },
  { value: '3', label: '周三' },
  { value: '4', label: '周四' },
  { value: '5', label: '周五' },
  { value: '6', label: '周六' },
  { value: '7', label: '周日' }
];

const timeSlotDialog = reactive({ visible: false });
const timeSlotForm = reactive({ start: '', end: '' });

const data = reactive<any>({
  form: {
    id: undefined,
    taskName: '',
    taskType: '',
    storeName: '',
    location: '',
    cycle: '每日',
    scanEnabled: false,
    checkMethod: '常规',
    punchDeviceCode: '',
    lng: undefined,
    lat: undefined,
    inspectorName: '',
    auditorName: '',
    dayOfWeek: '',
    dayOfMonth: '',
    timeSlot: '',
    itemList: [] as InspectionItemForm[]
  } as any,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: '',
    taskType: '',
    storeId: undefined as number | undefined,
    recordStatus: '',
    checkResult: ''
  },
  rules: {
    taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    taskType: [{ required: true, message: '请选择巡检类型', trigger: 'change' }],
    cycle: [{ required: true, message: '请选择巡检周期', trigger: 'change' }],
    storeName: [{ required: true, message: '请输入门店', trigger: 'blur' }],
    location: [{ required: true, message: '请输入位置区域', trigger: 'blur' }],
    inspectorId: [{ required: true, message: '请选择责任人', trigger: 'change' }],
    auditorId: [{ required: true, message: '请选择审核人', trigger: 'change' }]
  }
});

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

const dialog = reactive<DialogOption>({ visible: false, title: '' });
const recordDialog = reactive<DialogOption>({ visible: false, title: '打卡记录' });
const detailDialog = reactive({ visible: false });
const detailForm = ref<any>({ itemList: [] });
const auditDialog = reactive({ visible: false, title: '巡检打卡审核' });
const auditFormRef = ref<FormInstance>();
const getList = async () => {
  loading.value = true;
  try {
    const res = await listQualityInspectionTask(queryParams.value);
    // RuoYi-Vue-Plus 返回 { code, msg, data: { rows, total } }
    taskList.value = (res as any).data?.rows ?? [];
    total.value = (res as any).data?.total ?? 0;
  } finally {
    loading.value = false;
  }
};

const loadStats = async () => {
  const res = await getQualityInspectionStats();
  if (res.data) {
    stats.value = res.data;
  }
};

const loadAll = async () => {
  await Promise.all([getList(), loadStats()]);
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.storeId = undefined as number | undefined;
  handleQuery();
};

const resetForm = () => {
  form.value = {
    id: undefined,
    taskName: '',
    taskType: '',
    storeName: '',
    location: '',
    cycle: '每日',
    scanEnabled: false,
    checkMethod: '常规',
    punchDeviceCode: '',
    lng: undefined,
    lat: undefined,
    inspectorId: undefined,
    inspectorName: '',
    auditorId: undefined,
    auditorName: '',
    dayOfWeek: '',
    dayOfMonth: '',
    timeSlot: '',
    itemList: [] as InspectionItemForm[]
  };
  timeSlotList.value = [];
  weekDayList.value = [];
  monthDayList.value = [];
  formRef.value?.resetFields();
};

/**
 * 拉取当前登录用户所在部门及所有下级部门的用户列表(责任人/审核人选择器数据源)
 */
const loadDeptChainUsers = async () => {
  try {
    const res = await listByCurrentDeptChainUsers();
    deptChainUserOptions.value = res.data || [];
  } catch (e) {
    deptChainUserOptions.value = [];
  }
};

/**
 * 选择责任人后,同步回填 inspectorName 字段(便于提交到后端)
 */
const onInspectorChange = (val: string | number | undefined) => {
  if (val === undefined || val === null || val === '') {
    form.value.inspectorName = '';
    return;
  }
  const user = deptChainUserOptions.value.find((u) => String(u.userId) === String(val));
  form.value.inspectorName = user?.nickName || user?.userName || '';
};

/**
 * 选择审核人后,同步回填 auditorName 字段
 */
const onAuditorChange = (val: string | number | undefined) => {
  if (val === undefined || val === null || val === '') {
    form.value.auditorName = '';
    return;
  }
  const user = deptChainUserOptions.value.find((u) => String(u.userId) === String(val));
  form.value.auditorName = user?.nickName || user?.userName || '';
};

const onCycleChange = (val: string) => {
  timeSlotList.value = [];
  weekDayList.value = [];
  monthDayList.value = [];
};

const onScanChange = (val: boolean | string | number) => {
  form.value.checkMethod = val ? '扫码' : '常规';
};

const openAddTimeSlot = () => {
  timeSlotForm.start = '';
  timeSlotForm.end = '';
  timeSlotDialog.visible = true;
};

const confirmAddTimeSlot = () => {
  if (!timeSlotForm.start || !timeSlotForm.end) {
    proxy?.$modal.msgWarning('请选择开始和结束时间');
    return;
  }
  timeSlotList.value.push(`${timeSlotForm.start}-${timeSlotForm.end}`);
  timeSlotDialog.visible = false;
};

const removeTimeSlot = (idx: number) => {
  timeSlotList.value.splice(idx, 1);
};

const addInspectionItem = () => {
  form.value.itemList.push({
    itemType: '',
    itemContent: '',
    itemStandard: '',
    needPhoto: false
  });
};

const removeInspectionItem = (idx: number) => {
  form.value.itemList.splice(idx, 1);
};

const handleAdd = () => {
  resetForm();
  dialog.visible = true;
  dialog.title = '新增品控巡检打卡';
};

const handleUpdate = async (row: RiskInspectionTaskVo) => {
  resetForm();
  // 编辑时,确保选择器数据源已加载(避免选择器中无对应选项)
  if (deptChainUserOptions.value.length === 0) {
    await loadDeptChainUsers();
  }
  const res = await getQualityInspectionTask(row.id);
  Object.assign(form.value, res.data);
  // 恢复时间配置
  if (res.data?.timeSlot) {
    timeSlotList.value = res.data.timeSlot.split(',').filter((s: string) => s);
  }
  if (res.data?.dayOfWeek) {
    weekDayList.value = res.data.dayOfWeek.split(',').filter((s: string) => s);
  }
  if (res.data?.dayOfMonth) {
    monthDayList.value = res.data.dayOfMonth.split(',').filter((s: string) => s).map((n: string) => Number(n));
  }
  // 加载打卡项目
  try {
    const itemRes = await listInspectionItemByTask(row.id);
    form.value.itemList = (itemRes.data || []).map((it: RiskInspectionItemVo) => ({
      id: it.id,
      itemType: it.itemType,
      itemContent: it.itemContent,
      itemStandard: it.itemStandard,
      needPhoto: false
    }));
  } catch (e) {
    form.value.itemList = [];
  }
  dialog.visible = true;
  dialog.title = '编辑品控巡检任务';
};

const handleViewRecords = async (row: RiskInspectionTaskVo) => {
  recordLoading.value = true;
  try {
    const res = await listQualityInspectionRecordByTask(row.id);
    recordList.value = res.data || [];
  } finally {
    recordLoading.value = false;
  }
  recordDialog.visible = true;
};

const handleViewDetail = (row: RiskInspectionRecordVo) => {
  detailForm.value = { ...row, itemList: [] };
  detailDialog.visible = true;
};

// ============ 审核相关 ============
const auditData = reactive({
  auditForm: {
    id: undefined as string | number | undefined,
    taskName: '',
    inspectorName: '',
    checkInTime: '',
    auditStatus: '审核通过',
    auditOpinion: ''
  },
  auditRules: {
    auditStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    auditOpinion: [
      {
        validator: (_rule: any, value: any, callback: any) => {
          if (auditData.auditForm.auditStatus === '审核不通过' && !value) {
            callback(new Error('审核不通过时必须填写原因'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});

const { auditForm, auditRules } = toRefs(auditData);

/** 打卡记录列表 - 打开审核弹窗 */
const handleAuditRecord = (row: RiskInspectionRecordVo) => {
  auditForm.value = {
    id: row.id,
    taskName: row.taskName || '',
    inspectorName: row.inspectorName || '',
    checkInTime: row.checkInTime || '',
    auditStatus: '审核通过',
    auditOpinion: ''
  };
  auditDialog.visible = true;
};

/** 审核弹窗 - 提交 */
const submitAudit = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    const submitData: RiskInspectionRecordBo = {
      id: auditForm.value.id,
      auditStatus: auditForm.value.auditStatus,
      auditOpinion: auditForm.value.auditOpinion
    };
    await auditInspectionRecord(submitData);
    proxy?.$modal.msgSuccess('审核成功');
    auditDialog.visible = false;
    // 刷新当前打卡记录列表(若弹窗开着则一起刷新)
    if (recordDialog.visible && recordList.value.length > 0) {
      const taskId = recordList.value[0]?.taskId;
      if (taskId) {
        const res = await listQualityInspectionRecordByTask(taskId);
        recordList.value = res.data || [];
      }
    }
  });
};

const cancelAudit = () => {
  auditDialog.visible = false;
  auditFormRef.value?.resetFields();
};

const closeAuditDialog = () => {
  auditDialog.visible = false;
  auditFormRef.value?.resetFields();
};

/** 审核状态 tag 颜色(待审核=warning/审核通过=success/审核不通过=danger) */
const getAuditStatusTag = (s: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    待审核: 'warning',
    审核通过: 'success',
    审核不通过: 'danger'
  };
  return (map[s] || 'info') as any;
};

const handleDelete = async (row: RiskInspectionTaskVo) => {
  await proxy?.$modal.confirm('是否确认删除任务 "' + row.taskName + '" ?');
  await delQualityInspectionTask(row.id);
  proxy?.$modal.msgSuccess('删除成功');
  await loadAll();
};

const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    // 同步时间配置
    if (form.value.cycle === '每日') {
      form.value.timeSlot = timeSlotList.value.join(',');
      form.value.dayOfWeek = '';
      form.value.dayOfMonth = '';
    } else if (form.value.cycle === '每周') {
      form.value.dayOfWeek = weekDayList.value.join(',');
      form.value.timeSlot = '';
      form.value.dayOfMonth = '';
    } else if (form.value.cycle === '每月') {
      form.value.dayOfMonth = monthDayList.value.join(',');
      form.value.timeSlot = '';
      form.value.dayOfWeek = '';
    }
    form.value.scanEnabled = form.value.scanEnabled ? '1' : '0';

    if (form.value.id) {
      await updateQualityInspectionTask(form.value as RiskInspectionTaskBo);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await addQualityInspectionTask(form.value as RiskInspectionTaskBo);
      proxy?.$modal.msgSuccess('新增成功');
    }
    dialog.visible = false;
    await loadAll();
  });
};

const cancel = () => {
  dialog.visible = false;
  resetForm();
};

const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

const getMethodTag = (m: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    扫码: 'warning',
    常规: 'primary'
  };
  return (map[m] || 'info') as any;
};

const getStatusTag = (s: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    已打卡: 'success',
    未打卡: 'danger',
    异常打卡: 'warning'
  };
  return (map[s] || 'info') as any;
};

const getResultTag = (r: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    正常: 'success',
    异常: 'danger'
  };
  return (map[r] || 'info') as any;
};

onMounted(async () => {
  await loadAll();
  await loadDeptChainUsers();
  await loadStores();
});

/** 加载门店下拉(集团总部 + dept_category='门店' 的所有门店) */
const loadStores = async () => {
  try {
    const res: any = await listDept({});
    const list: any[] = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
    storeOptions.value = list
      .filter((d: any) => d.deptCategory === '门店' || d.deptId === 100)
      .filter((d: any) => d.status === '0' || d.status === undefined || d.status === null)
      .map((d: any) => ({ label: d.deptName, value: d.deptId }))
      .sort((a, b) => a.value - b.value);
  } catch (e) {
    console.error('加载门店列表失败', e);
    storeOptions.value = [];
  }
};
</script>

<style scoped lang="scss">
.inspection-task-page {
  padding: 16px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.stat-card {
  border-radius: 8px;
  :deep(.el-card__body) { padding: 20px; }
}
.stat-card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.stat-info { flex: 1; }
.stat-title {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
  white-space: nowrap;
}
.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}
.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}
.stat-icon-blue { background: #ecf5ff; color: #409EFF; }
.stat-icon-orange { background: #fdf6ec; color: #E6A23C; }
.stat-icon-green { background: #f0f9eb; color: #67C23A; }
.stat-icon-red { background: #fef0f0; color: #F56C6C; }
.mb-2 { margin-bottom: 8px; }
.mt-2 { margin-top: 8px; }
.readonly-text {
  color: #303133;
}
.audit-opinion.pass {
  color: #67c23a;
}
.audit-opinion.reject {
  color: #f56c6c;
}
</style>