<template>
  <div class="check-log-page">
    <el-card>
      <div class="toolbar"
        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.operator" placeholder="执行人" style="width: 180px;" @keyup.enter="fetchList" />
          <el-select v-model="queryParams.status" placeholder="点检状态" clearable style="width: 160px; margin-left: 12px;"
            @change="fetchList">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button @click="fetchList" style="margin-left: 12px;">查询</el-button>
        </div>
        <el-button type="primary" @click="openDialog()">新增记录</el-button>
      </div>
      <el-table :data="tableData" border stripe style="width: 100%; margin-top: 16px;">
        <el-table-column prop="recordId" label="记录ID" min-width="120" />
        <el-table-column prop="planName" label="点检计划" min-width="120" />
        <el-table-column prop="equipmentName" label="设备名称" min-width="120" />
        <el-table-column prop="operatorName" label="执行人" min-width="100" />
        <el-table-column prop="checkTime" label="点检时间" min-width="140">
          <template #default="scope">{{ formatDate(scope.row.checkTime) }}</template>
        </el-table-column>
        <el-table-column prop="finishTime" label="完成时间" min-width="140">
          <template #default="scope">{{ formatDate(scope.row.finishTime) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ statusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resultSummary" label="结果摘要" min-width="120" />
        <el-table-column prop="abnormalDesc" label="异常描述" min-width="120" />
        <!--        <el-table-column prop="photos" label="照片" min-width="120">-->
        <!--          <template #default="scope">-->
        <!--            <el-image v-for="(url, idx) in scope.row.photos || []" :key="idx" :src="url" style="width: 40px; height: 40px; margin-right: 4px;" :preview-src-list="scope.row.photos" preview-teleported />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="approver" label="验收人" min-width="100" />
        <el-table-column prop="approveTime" label="验收时间" min-width="140">
          <template #default="scope">{{ formatDate(scope.row.approveTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" min-width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除该记录吗？" @confirm="handleDelete(scope.row.recordId)">
              <template #reference>
                <el-button size="small" type="danger" plain style="margin-left: 8px;">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
        :total="pagination.total" layout="total, prev, pager, next, sizes" @current-change="fetchList"
        @size-change="fetchList" style="margin-top: 16px; text-align: right;" />
    </el-card>
    <!-- 编辑/新增对话框 -->
    <el-dialog :title="formData.recordId ? '编辑点检记录' : '新增点检记录'" v-model="dialogVisible" width="600px"
      @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="点检计划" prop="planId">
          <el-select v-model="formData.planId" placeholder="请选择点检计划" filterable @change="handlePlanChange">
            <el-option v-for="item in planOptions" :key="item.planId" :label="item.planName" :value="item.planId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备" prop="equipmentId">
          <el-input v-model="formData.equipmentName" placeholder="设备名称" readonly />
        </el-form-item>
        <el-form-item label="执行人" prop="operator">
          <el-select v-model="formData.operator" placeholder="请选择执行人" filterable @change="handleOperatorChange">
            <el-option v-for="item in userOptions" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="点检时间" prop="checkTime">
          <el-date-picker v-model="formData.checkTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择点检日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker v-model="formData.finishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择完成日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="结果摘要" prop="resultSummary">
          <el-input v-model="formData.resultSummary" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="异常描述" prop="abnormalDesc">
          <el-input v-model="formData.abnormalDesc" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="照片" prop="photos">
          <el-upload ref="uploadRef" :file-list="fileList" :http-request="customUpload" :on-remove="handleUploadRemove"
            list-type="picture-card" :limit="6" :multiple="true" :show-file-list="true" :auto-upload="true">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="验收人" prop="approver">
          <el-input v-model="formData.approver" placeholder="请输入验收人" />
        </el-form-item>
        <el-form-item label="验收时间" prop="approveTime">
          <el-date-picker v-model="formData.approveTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择验收日期" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { CheckLogApi } from '@/api/iot/check/log';
import { CheckPlanApi } from '@/api/iot/check/plan';
import { getSimpleUserList } from '@/api/system/user';
import dayjs from 'dayjs';
import type { UploadUserFile, UploadProps } from 'element-plus';

const tableData = ref<any[]>([]);
const pagination = reactive({ pageNum: 1, pageSize: 10, total: 0 });
const queryParams = reactive({ operator: '', status: '' });
const dialogVisible = ref(false);
const formRef = ref();
const formData = reactive<any>({ planId: '', operatorName: '' });
const rules = {
  planId: [{ required: true, message: '请选择点检计划', trigger: 'change' }],
  operator: [{ required: true, message: '请选择执行人', trigger: 'change' }],
  checkTime: [{ required: true, message: '请选择点检时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};
const statusOptions = [
  { value: 'pending', label: '待点检' },
  { value: 'completed', label: '已完成' },
  { value: 'abnormal', label: '异常' },
  { value: 'timeout', label: '超时' },
];

const planOptions = ref<any[]>([]);
const userOptions = ref<any[]>([]);
const fileList = ref<UploadUserFile[]>([]);

async function fetchList() {
  try {
    console.log('开始获取列表数据');
    const params = {
      ...queryParams,
      pageNo: pagination.pageNum,
      pageSize: pagination.pageSize,
    };
    console.log('请求参数:', params);
    const res = await CheckLogApi.getCheckLogPage(params);
    console.log('列表数据响应:', res);
    if (res && res.data) {
      tableData.value = res.list || [];
      // 打印每条记录的photos字段
      tableData.value.forEach((item, index) => {
        console.log(`记录${index} photos:`, item.photos);
      });
      pagination.total = res.total || 0;
    } else {
      tableData.value = res.list || [];
      // 打印每条记录的photos字段
      tableData.value.forEach((item, index) => {
        console.log(`记录${index} photos:`, item.photos);
      });
      pagination.total = res.total || 0;
    }
  } catch (error) {
    console.error('获取列表数据失败:', error);
    ElMessage.error('获取列表数据失败');
  }
}

function openDialog(row?: any) {
  console.log('openDialog row:', row);
  if (row) {
    Object.assign(formData, row);
    formData.planId = String(row.planId || '');
    formData.operatorName = row.operatorName || '';
    console.log('编辑记录的photos原始值:', row.photos);

    // 兼容 photos 为字符串或数组，赋值为图片对象数组
    let photosArr: any[] = [];
    if (Array.isArray(row.photos)) {
      photosArr = row.photos;
      console.log('photos是数组类型');
    } else if (typeof row.photos === 'string' && row.photos) {
      try {
        const parsed = JSON.parse(row.photos);
        if (Array.isArray(parsed)) {
          photosArr = parsed;
          console.log('photos是JSON字符串，已解析为数组');
        }
      } catch (e) {
        console.error('解析photos字符串失败:', e);
      }
    } else {
      console.log('photos既不是数组也不是字符串:', typeof row.photos);
    }

    console.log('处理后的photosArr:', photosArr);

    fileList.value = (photosArr || []).map((url: string | { url: string, name?: string }, idx: number) => {
      if (typeof url === 'string') {
        return { url, name: `图片${idx + 1}`, status: 'success', uid: idx }; // 将uid改为数字
      } else {
        return { url: url.url, name: url.name || `图片${idx + 1}`, status: 'success', uid: idx }; // 将uid改为数字
      }
    });

    console.log('设置的fileList:', fileList.value);
  } else {
    Object.keys(formData).forEach(k => delete formData[k]);
    formData.planId = '';
    formData.operatorName = '';
    fileList.value = [];
    formData.status = 'pending';
    formData.equipmentId = '';
    formData.equipmentName = '';
    formData.planName = '';
  }
  dialogVisible.value = true;
}

function resetForm() {
  if (formRef.value) formRef.value.resetFields();
  fileList.value = [];
}

function handleSubmit() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    // 确保设备ID存在
    if (!formData.equipmentId) {
      ElMessage.error('请先选择点检计划');
      return;
    }
    // photos为图片对象数组
    formData.photos = fileList.value
      .filter(file => file.url && file.url.trim() !== '')
      .map(file => ({ url: file.url, name: file.name || '未命名图片' }));

    console.log('提交的photos数据:', JSON.stringify(formData.photos));

    if (formData.recordId) {
      await CheckLogApi.updateCheckLog(formData);
      ElMessage.success('修改成功');
    } else {
      await CheckLogApi.createCheckLog(formData);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    fetchList();
  });
}

async function handleDelete(recordId: number) {
  try {
    await CheckLogApi.deleteCheckLog(recordId);
    ElMessage.success('删除成功');
    fetchList();
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
}

function handleUploadRemove(file: any, fileListArr: any[]) {
  // 前端 fileList 兜底同步删除
  const idx = fileList.value.findIndex(f => f.uid === file.uid);
  if (idx !== -1) {
    fileList.value.splice(idx, 1);
  }
}

function statusLabel(val: string) {
  return statusOptions.find(i => i.value === val)?.label || val;
}
function statusTagType(val: string) {
  switch (val) {
    case 'completed': return 'success';
    case 'abnormal': return 'danger';
    case 'timeout': return 'warning';
    default: return 'info';
  }
}
function formatDate(val: string) {
  if (!val) return '';
  return val.length > 10 ? val.replace('T', ' ').slice(0, 19) : val;
}

function handlePlanChange(planId: string) {
  const selectedPlan = planOptions.value.find(plan => String(plan.planId) === String(planId));
  if (selectedPlan) {
    formData.planId = String(selectedPlan.planId);
    formData.equipmentId = selectedPlan.equipmentId;
    formData.equipmentName = selectedPlan.equipmentName;
    formData.planName = selectedPlan.planName;
  }
}

function handleOperatorChange(userId) {
  const user = userOptions.value.find(u => u.id === userId);
  formData.operatorName = user ? user.nickname : '';
}

async function fetchOptions() {
  try {
    console.log('开始获取选项数据');
    // 点检计划 - 使用分页接口获取所有数据
    const planRes = await CheckPlanApi.getCheckPlanPage({ pageNo: 1, pageSize: 1000 });
    // 兼容后端返回格式
    const list = planRes?.data?.list || planRes?.list || [];
    planOptions.value = list.map(item => ({
      ...item,
      planId: String(item.planId)
    }));
    console.log('设置计划选项:', planOptions.value);
    // 用户
    const userRes = await getSimpleUserList();
    userOptions.value = userRes || [];
    console.log('设置用户选项:', userOptions.value);
  } catch (error) {
    console.error('获取选项数据失败:', error);
    ElMessage.error('获取选项数据失败');
  }
}

// 上传图片自定义请求
const customUpload: UploadProps['httpRequest'] = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    // 假设你有CheckLogImageApi.uploadImage方法，返回{url, name}
    const response = await CheckLogApi.uploadImage(file);
    fileList.value.push({
      name: response.name || file.name,
      url: response.url,
      status: 'success',
      uid: file.uid
    });
    ElMessage.success('上传成功');
    onSuccess({ url: response.url, name: response.name || file.name });
  } catch (error) {
    ElMessage.error('上传失败');
    onError({ status: 500, method: 'POST', url: '', name: 'UploadError', message: error instanceof Error ? error.message : '上传失败' });
  }
};

onMounted(() => {
  fetchList();
  fetchOptions();
});
</script>

<style scoped>
.check-log-page .toolbar {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}
</style>
