<template>
  <div>
    <el-dialog v-model="showSearch" title="巡查结果" width="80%" @close="$emit('close')">
      <div class="app-container">
        <transition name="fade">
          <div v-show="showSearch">
            <el-form ref="queryFormRef" :model="queryParams">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="所属区划：" prop="area" label-width="auto">
                    <el-tree-select
                      v-model="divisionSelectedId"
                      :data="formattedDivisionData"
                      :props="{ label: 'label', value: 'code', children: 'children' }"
                      :render-after-expand="false"
                      style="width: 468px"
                      @change="onDivisionChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="巡查结果：" prop="inspection_result" label-width="auto">
                    <el-select v-model="queryParams.inspection_result" placeholder="全部" clearable>
                      <el-option v-for="item in cycleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="nick_name" label-width="auto">
                    <el-input v-model="queryParams.nick_name" placeholder="请输入巡查人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </transition>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleExport">导出</el-button>
          </el-col>
        </el-row>
        <!-- 表格组件 -->
        <el-table ref="multipleTable" v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column label="巡查点" align="center" prop="point_name" />
          <el-table-column label="所属区划" align="center" prop="area" />
          <el-table-column label="执行日期" align="center" prop="create_time" />
          <el-table-column label="巡查人" align="center" prop="nick_name" />
          <el-table-column label="巡查结果" align="center">
            <template #default="{ row }">
              {{ getInspectionResultText(row.inspection_result) }}
            </template>
          </el-table-column>
          <el-table-column label="现场照片" align="center" prop="fileList">
            <template #default="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.url"
                :preview-src-list="scope.row.urlList"
                :preview-teleported="true"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
        </el-table>
        <pagination v-show="total > 0" v-model:page="queryParams.page" v-model:limit="queryParams.pageSize" :total="total" @pagination="tableData" />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { inspectorDivision, resultList } from '@/api/inspectionWork/riskManagement';
import { ElMessage } from 'element-plus';
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const downLoadApi = import.meta.env.VITE_APP_BASE_DOWNLOAD_API;
const loading = ref(true);
const showSearch = ref(true);
const multiple = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const total = ref(0);
const tableData = ref([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const divisionSelectedId = ref(null);
const formattedDivisionData = ref([]);
const rawDivisionData = ref([]);
const props = defineProps<{
  eventId: string | number;
}>();
const initFormData = reactive({
  id: '',
  children_task_id: '',
  point_name: '',
  area: '',
  create_time: '',
  nick_name: '',
  inspection_result: '',
  remark: '',
  fileList: ''
});
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    page: 1,
    pageSize: 10,
    inspection_result: '',
    area_code: '',
    nick_name: ''
  }
});
const { queryParams, form } = toRefs(data);
const cycleOptions = ref([
  { label: '全部', value: '' }, // 通常“全部”对应空值或者特定的标识符，表示不按此条件过滤
  { label: '正常', value: '1' },
  { label: '异常', value: '2' }
]);
const getInspectionResultText = (resultCode) => {
  switch (resultCode) {
    case '1':
      return '正常';
    case '2':
      return '异常';
    default:
      return '全部';
  }
};

const fetchResulData = () => {
  loading.value = true; // 开始加载
  return resultList(props.eventId, queryParams.value)
    .then((res) => {
      res.data.forEach((item) => {
        if (item.fileList && item.fileList.length > 0) {
          let urlList = [];
          item.fileList.forEach((item2) => {
            urlList.push(baseUrl + downLoadApi + item2.url);
          });
          item.urlList = urlList;
          item.url = urlList[0];
        }
      });
      tableData.value = res.data || []; // 确保tableData是一个数组
      total.value = res.total || 0; // 确保total是一个数字
      console.log('Fetched subtasks data:', tableData.value);
      loading.value = false; // 结束加载
    })
    .catch((error) => {
      console.error('Error fetching sub tasks:', error);
      loading.value = false; // 结束加载
    });
};
const handleQuery = () => {
  queryParams.value.page = 1;
  fetchResulData();
};
const handleExport = () => {
  ElMessage.info('导出成功');
};
// 重置查询条件
const resetQuery = () => {
  queryParams.value = { page: 1, pageSize: 10, nick_name: '', area_code: '', inspection_result: '' };
  handleQuery();
};
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const fetchDivisionData = async () => {
  const response = await inspectorDivision();
  if (response.code === 200) {
    rawDivisionData.value = response.data;
    formattedDivisionData.value = formatDivisionData(rawDivisionData.value);
    console.log('Formatted Division Data:', formattedDivisionData.value);
  } else {
    ElMessage.error(response.msg);
  }
};
const onDivisionChange = (value) => {
  // 确认选中的项存在
  const selectedDivision = findNode(formattedDivisionData.value, value);
  if (!selectedDivision) {
    ElMessage.warning('未找到匹配的责任区划。');
    // 将选中的值重置为 null 或空字符串，防止后续逻辑错误
    divisionSelectedId.value = null;
  } else {
    console.log('Selected Division:', selectedDivision); // 调试输出
  }
};
// 递归查找节点
const findNode = (nodes, code) => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.code === code) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findNode(node.children, code);
      if (found) {
        return found;
      }
    }
  }
  return null;
};
// 格式化责任区划数据
const formatDivisionData = (data) => {
  return data.map((item) => ({
    id: item.id,
    label: item.label,
    code: item.code,
    children: item.children ? formatDivisionData(item.children) : []
  }));
};
onMounted(() => {
  fetchResulData();
  fetchDivisionData();
});
</script>
