<template>
  <AttachmentS3Image v-if="false" :f-id="startPhoto" />
  <div v-if="true" class="h5-container">
    <van-nav-bar title="作业管理" @click-right="handAdd">
      <template #right>
        <van-icon name="add" size="25" color="#000" />
      </template>
    </van-nav-bar>
    <van-search v-model="query.projectName" show-action placeholder="请输入发现人" @search="onRefresh"
                @cancel="handdelect" />

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list v-model:loading="isLoading" :finished="isFinished" finished-text="没有更多了" offset="200"
                @load="onLoad">
        <div v-for="(item, idx) in resultData" :key="item.id">
          <van-swipe-cell @open="handleSwipeOpen(item,idx)" @close="handleSwipeClose(item,idx)"
                          title-style="color: #007aff" style="height: 100px;" :ref="el => getSwipeCellRef(el, idx)">
            <template #default>
              <div class="swipe-cell-default">
                <van-cell style="height: 100px; display: flex; align-items: center; padding: 0 15px;"
                          @click="edits(item)">
                  <template #title>
                    <div class="cell-title">
                      {{ item.workName }} {{ formatDataHouZhui(item.addTime) }}
                    </div>
                  </template>
                  <template #label>
                    <div class="cell-label">
                      <div>作业开始时间：{{ item.timeStart }}</div>
                      <div>作业负责人：{{ item.addName }}</div>
                      <div class="status-wrapper"
                           :class="{'text-start':item.workStatus==='作业起草','text-middle':item.workStatus==='作业中','text-end':item.workStatus==='作业结束'}">
                        状态：{{ item.workStatus }}
                      </div>
                    </div>
                  </template>
                </van-cell>
                <div class="swipe-cell-default-icon">
                  <van-icon v-if="openStatus[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                  <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                </div>
              </div>
            </template>

            <template #right>
              <van-button square class="delete-button" text="删除" @click="handleDelete(item, idx)" />
              <van-button v-if="!item.workId  && item.workStatus==='作业结束'" square class="submit-button"
                          text="提交审批"
                          @click="handleSubmit2(item, idx)" />
              <van-button @click="switchIconState(idx)" v-if="item.workId" class="subsuccess" text="已提交无需操作" />
            </template>
          </van-swipe-cell>
        </div>

      </van-list>
    </van-pull-refresh>


    <!-- 删除确认弹窗 -->
    <van-dialog v-model:show="deleteDialogVisible" show-cancel-button @confirm="confirmDelete">
      <template #title>
        <div>删除确认</div>
      </template>
      <div style="padding: 30px;">确定要删除该项目吗？</div>
    </van-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, toRaw } from 'vue';
import { Dialog, showDialog, showSuccessToast, showToast, Toast } from 'vant';
import { wxReady, requestSignature } from '@/router/initWxSdk.js';
const { proxy } = getCurrentInstance();

import axios from 'axios';
import qs from 'qs';
const location = ref('118.17453689329058,36.84945955106316')
const initLocation1 = async (currentGps) => {
  const response = await axios.get('http://localhost:4200/map/v3/geocode/regeo', {
    params: {
      location: currentGps, // 原始经纬度，不手动编码
      key: 'a3e93e66422b9b620bfdeeed9f0aef6e'
    },
    paramsSerializer: (params) => {
      return qs.stringify(params, {
        encode: false, // 关键：禁止qs对特殊字符编码
        allowDots: true
      });
    }
  })
  console.log('res',response.data.regeocode.formatted_address)
  localStorage.setItem("realLocation",JSON.stringify(response.data.regeocode.formatted_address))
  console.log('localStorage.getItem("realLocation")',localStorage.getItem("realLocation"))
}
const initLocation = async (currentGps) => {
  try {
    // 1. 定义请求参数（和原axios参数一致）
    const params = {
      location: currentGps, // 原始经纬度，不手动编码
      key: 'a3e93e66422b9b620bfdeeed9f0aef6e'
    };



    // 2. 手动序列化参数（替代qs.stringify，保持encode: false的效果）
    // 遍历参数，拼接成 "key=value&key2=value2" 格式，不编码特殊字符
    const paramStr = Object.entries(params)
      .map(([key, value]) => `${key}=${value}`)
      .join('&');

    // 3. 构造完整请求URL
    const url = `https://restapi.amap.com/v3/geocode/regeo?${paramStr}`;

    // 4. 发起fetch请求
    const response = await fetch(url);

    // 5. 检查响应是否成功（HTTP状态码2xx）
    if (!response.ok) {
      throw new Error(`请求失败，状态码：${response.status}`);
    }

    // 6. 解析JSON响应
    const data = await response.json();

    // 7. 提取地址并存入localStorage（修复原代码的键名大小写问题）
    const formattedAddress = data.regeocode?.formatted_address;
    if (formattedAddress) {
      var longitude = currentGps.split(',')[0]
      var latitude = currentGps.split(',')[1]
      localStorage.setItem("realLocation", JSON.stringify(formattedAddress));
      localStorage.setItem("longitude", JSON.stringify(longitude))
      localStorage.setItem("latitude", JSON.stringify(latitude))
      console.log('存入localStorage的地址：', formattedAddress);
      // 读取时用正确的键名（原代码是"reallocation"，这里统一为"realLocation"）
      console.log('从localStorage读取的地址：', JSON.parse(localStorage.getItem("realLocation")));
      console.log('从localStorage读取的经度：', JSON.parse(localStorage.getItem("longitude")));
      console.log('从localStorage读取的纬度：', JSON.parse(localStorage.getItem("latitude")));
      await fetch(`https://api.open-elevation.com/api/v1/lookup?locations=${latitude},${longitude}`)
        .then(response => response.json())
        .then(data => {
          if (data.results && data.results.length > 0) {
            const elevation = data.results[0].elevation;
            console.log(`海拔高度: ${elevation.toFixed(2)} 米`);
            localStorage.setItem("elevation", JSON.stringify(elevation));
            console.log('从localStorage读取的海拔高度：', JSON.parse(localStorage.getItem("elevation")));
          }
        })
        .catch(error => console.error("Open Topo Data请求失败:", error));
      const url = `https://api.open-meteo.com/v1/forecast?` +
        `latitude=${latitude}&` +
        `longitude=${longitude}&` +
        `hourly=temperature_2m,relativehumidity_2m,windspeed_10m,apparent_temperature,weathercode&` +
        `current_weather=true&` +
        `timezone=auto&` +
        `past_days=0`;

      await fetch(url)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          if (data.current_weather) {
            // 处理当前天气数据
            const weatherInfo = {
              current: {
                temperature: Math.round(data.current_weather.temperature),
                humidity: Math.round(data.hourly.relativehumidity_2m[0]),
                windSpeed: Math.round(data.current_weather.windspeed),
                feelsLike: Math.round(data.hourly.apparent_temperature[0]),
                weatherCode: data.current_weather.weathercode,
                weatherDesc: getWeatherDescription(data.current_weather.weathercode)
              },
              hourly: data.hourly.time.slice(0, 8).map((time, index) => ({
                time: formatHour(time),
                temperature: Math.round(data.hourly.temperature_2m[index]),
                weatherCode: data.hourly.weathercode[index]
              })),
              timestamp: new Date().getTime()
            };
            var weathers = {
              weather: weatherInfo.current.weatherDesc,
              temperature: weatherInfo.current.temperature+'℃',
            }
            console.log('天气信息:', weatherInfo);
            localStorage.setItem("weatherInfo", JSON.stringify(weathers));
            console.log('从localStorage读取的天气信息：', JSON.parse(localStorage.getItem("weatherInfo")));
          }
        })
        .catch(error => {
          console.error("天气信息请求失败:", error);
          // 尝试从localStorage读取缓存数据
          const cachedWeather = localStorage.getItem("weatherInfo");
          if (cachedWeather) {
            const parsedWeather = JSON.parse(cachedWeather);
            // 检查缓存是否过期（2小时）
            if (new Date().getTime() - parsedWeather.timestamp < 7200000) {
              console.log('使用缓存的天气信息');
              return parsedWeather;
            }
          }
          throw error;
        });
    } else {
      console.warn('未获取到有效地址信息', data);
    }

  } catch (error) {
    console.error('initLocation请求失败：', error.message);
    throw error; // 抛出错误，让上层onMounted的catch捕获
  }
};
// 辅助函数：获取天气描述
function getWeatherDescription(weatherCode) {
  const descMap = {
    // 晴天/少云（细分）
    0: '☀️ 晴天',    // 晴空万里
    2: '🌤️ 少云',   // 少云（晴间多云）

    // 多云/阴天（细分）
    1: '⛅ 多云',    // 多云（半晴半云）
    3: '☁️ 阴天',    // 阴天（全云）

    // 雾（不同浓度）
    45: '🌫️ 薄雾',   // 薄雾
    48: '🌁 浓雾',    // 浓雾

    // 雨（细分强度和类型）
    51: '🌦️ 小雨夹晴',   // 毛毛雨（小雨夹晴）
    53: '🌧️ 小雨',   // 小雨
    55: '🌧️🌧️ 中雨', // 中雨（双雨滴强调）
    56: '❄️🌧️ 冻雨', // 冻雨（雪+雨）
    57: '❄️🌧️🌧️ 强冻雨', // 强冻雨
    61: '🌧️ 小雨',   // 小雨
    63: '🌧️🌧️ 中雨', // 中雨
    65: '🌧️🌧️🌧️ 大雨', // 大雨（三雨滴强调）
    66: '❄️🌧️ 冻雨', // 冻雨
    67: '❄️🌧️🌧️ 强冻雨', // 强冻雨
    80: '🌦️🌧️ 阵雨', // 阵雨（短时雨）
    81: '🌧️🌧️ 中阵雨', // 中阵雨
    82: '🌧️🌧️🌧️ 强阵雨', // 强阵雨

    // 雪（细分强度和类型）
    71: '❄️ 小雪',   // 小雪
    73: '❄️❄️ 中雪', // 中雪
    75: '❄️❄️❄️ 大雪',  // 大雪（双雪花）
    77: '❄️ 雪粒',    // 雪粒
    85: '🌨️❄️ 阵雪', // 阵雪（短时雪）
    86: '❄️❄️❄️ 强阵雪', // 强阵雪（三雪花）

    // 雷阵雨（细分）
    95: '⛈️ 雷阵雨',    // 普通雷阵雨
    96: '⛈️❄️ 雷阵雨夹雪',  // 雷阵雨夹雪
    99: '⛈️❄️🌧️ 强雷阵雨夹雪' // 强雷阵雨夹雪
  };
  return descMap[weatherCode] || '未知天气';
}
// 辅助函数：格式化小时时间
function formatHour(timeStr) {
  const date = new Date(timeStr);
  return date.getHours() + ':00';
}
// initLocation('115.96990387417725,36.444144956567925');
onMounted(async () => {
  // await initLocation(location.value)
  /*测试定位*/
  try {
    // 1. 获取签名配置
    const signResult = await requestSignature();
    console.log('signResult==签名配置', signResult);
    if (!signResult.result) {
      return;
    }

    // 2. 初始化微信SDK
    const wxReadya = await wxReady(signResult.data);
    console.log('微信SDK初始化成功', wxReadya);

    // 3. 获取地理位置（需要将回调函数转换为Promise）
    const locationResult = await new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84', // 使用GPS原始坐标
        success: function(res) {
          console.log('位置返回值：', res);
          resolve(res); // 将结果传递给Promise
        },
        fail: function(err) {
          console.error('获取位置失败：', err);
          reject(err); // 将错误传递给Promise
        }
      });
    });

    // 4. 使用获取到的位置信息
    const { latitude, longitude, speed, accuracy, gps_status } = locationResult;
    console.log('纬度：', latitude);
    console.log('经度：', longitude);
    console.log('GPS状态：', gps_status);
    
    // 根据GPS状态进行处理
    switch (gps_status) {
      case -1:
        console.error('应用未获取GPS权限');
        break;
      case 0:
        console.error('已获取GPS权限，但GPS信号异常');
        break;
      case 1:
        console.log('已获取GPS权限，GPS信号正常，AGPS信号异常');
        break;
      case 2:
        console.log('已获取GPS权限，GPS信号异常，AGPS信号正常');
        break;
      case 3:
        console.log('已获取GPS权限，GPS/AGPS信号正常');
        break;
    }
    // let realLocation = await initLocation('119.388252'+","+'35.218899')
    await initLocation(longitude+","+latitude)
  } catch (error) {
    console.error('获取位置信息失败：', error);
    // 这里可以添加用户提示，如"请检查GPS权限和信号"
  }
  /*测试定位*/
});

const formatDataHouZhui = (date) => {
  date = date.split(' ')[0].split('-');
  return date[0] + date[1] + date[2];
};
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  dept: JSON.parse(localStorage.getItem('dept'))[0].deptCode
});
const switchIconState = (idx) => {
  openStatus.value[idx] = !openStatus.value[idx];
  openStatus.value = new Array(resultData.value.length).fill(true);
};

const searchShow = ref(false);
const query = ref({
  projectName: ''
});

function formatDate(date, format) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  return format
    .replace('yyyy', year)
    .replace('MM', month.toString().padStart(2, '0'))
    .replace('dd', day.toString().padStart(2, '0'))
    .replace('HH', hours.toString().padStart(2, '0'))
    .replace('mm', minutes.toString().padStart(2, '0'))
    .replace('ss', seconds.toString().padStart(2, '0'));
}

const tableData = ref([]);
const selectedRows = ref([]);
const dialogVisibleLook = ref(false);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref([]);
const dialogVisible = ref(false);
const dialogVisibleFile = ref(false);
const date = ref(null);

const kz = ref(true);
const handAdd = async () => {
  kz.value = false;
  resetForma();
  form.value.discoverer = localStorage.getItem('userCode');
  let tree = JSON.parse(localStorage.getItem('dept'));
  console.log('数', tree);

  const item = {};

  proxy.$router.push({
    path: '/projectManage/projectConstructionOperation/projectConstructionOperation_detail',
    query: {
      hdId: form.value.hdId,
      hdPicId: form.value.hdPicId,
      discoverer: form.value.discoverer,
      discovererDept: form.value.discovererDept,
      discovererDesc: form.value.discovererDesc,
      discovererDeptCode: form.value.discovererDeptCode
    }
  });
};
const form = ref({});
const resetForma = () => {
  form.value = {
    hdPicId: '',
    hdId: '',
    hdType: '',
    discoveryTime: '',
    hdSubtype: '',
    discoverer: '',
    discovererOther: '',
    hdDescription: '',
    hdLevel: '',
    bz: '',
    hdLocation: '',
    picBefore: '',

    equipmentId: '',
    hdmanageLevel: '',
    handlingProcesses: '',
    companyId: '',
    repairLeader: '',
    repairOther: '',
    repairSuggest: '',
    repairDdl: '',
    repairDept: '',
    acceptLeader: '',
    acceptOther: '',
    picAfter: '',
    picTemp: '',
    repairDescription: '',
    status: '',
    discovererDept: '',
    discovererDeptCode: '',
    hdLocationCode: '',
    hdLocationName: '',

    hdSelect: '正常登记',
    id: ''
  };
};

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);

const getTableData = async () => {
  const url = 'sgsafe/ProjectWork/query';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  };
  const response = await proxy.$axios.get(url, param);
  if (response.data.code === 0) {
    tableData.value = response.data.data.records;
    totalRows.value = response.data.data.total;
  } else {
    showToast({
      type: 'error',
      message: '操作失败！' + response.data.msg
    });
  }
};

const onRefresh = () => {
  basicReset();
  onLoad();
};

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }
  try {
    await getTableData();
    if (pageSize.value * currentPage.value < totalRows.value) {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      currentPage.value++;

    } else {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      isFinished.value = true;
    }
  } catch (error) {
    console.log(error);
    isFinished.value = true;
  } finally {
    isLoading.value = false;
  }
};
const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

const handdelect = () => {
  query.value.discoverer = '';
  onRefresh();
};

const handleDetailLook = (row) => {
  form.value = { ...row };
  proxy.$router.push({
    name: 'taiZhang_detail',
    query: {
      form: form.value.id
    }
  });
};

const handleDelete = (item, idx) => {
  openStatus.value[idx] = !openStatus.value[idx];
  openStatus.value = new Array(resultData.value.length).fill(true);
  currentDeleteItem.value.push(item);
  deleteDialogVisible.value = true;
};

const confirmDelete = () => {
  var url = 'sgsafe/ProjectWork/remove';
  var param = {
    params: JSON.stringify({ ...currentDeleteItem.value.map(x => x.id) })
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '删除成功'
      });
      onRefresh();
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const edits = (row) => {
  kz.value = true;
  form.value = { ...row };
  if (row.workId) {
    sessionStorage.setItem('workflowQuery', JSON.stringify({
      flowId: row.flowId,
      workId: row.workId,
      trackId: row.trackId,
      type: '1',
      date: new Date().getTime()
    }));
    proxy.$router.push({
      path: '/projectManage/todo_detail/index'
    });
  } else if (form.value.overTask === '是') {
    proxy.$router.push({
      path: '/projectManage/projectConstructionOperation/projectConstructionOperation_detail3',
      query: {
        id: form.value.id
      }
    });
  } else {
    proxy.$router.push({
      path: '/projectManage/projectConstructionOperation/projectConstructionOperation_detail2',
      query: {
        id: form.value.id
      }
    });
  }

};


const resetForm = () => {
  form.value = {
    projectName: '',
    projectLeader: '',
    phone: '',
    dept: ''
  };
};

const baocun = () => {
  nextTick(() => {
    if (form.value.hdSelect === '正常登记') {
      form.value.status = '0';
    } else if (form.value.hdSelect === '下发隐患') {
      form.value.status = '2';
    } else {
      form.value.status = '-1';
    }
  });
  var url = 'sgsafe/Hiddendanger/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      showSuccessToast('保存成功！');
      getTableData();
      orJsons();
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const repairLL = ref('');
const repairOO = ref('');
const acceptLL = ref('');
const orJsons = () => {
  if (form.value.hdSelect === '正常登记') {
    nextTick(() => {
      nextTick(() => {
        repairLL.value = qq('repairLL', form.value.discoverer);
        nextTick(() => {
          repairOO.value = qq('repairOO', form.value.discovererOther);
          nextTick(() => {
            acceptLL.value = qq('acceptLL', form.value.discoverer);
          });
        });
      });
    });
  } else {
    nextTick(() => {
      nextTick(() => {
        repairLL.value = qq('repairLL', form.value.acceptLeader);
        nextTick(() => {
          repairOO.value = qq('repairOO', form.value.acceptOther);
          nextTick(() => {
            acceptLL.value = qq('acceptLL', form.value.discoverer);
          });
        });
      });
    });
  }
};

const jsons = ref({});
const qq = async (a, val) => {
  let aa = '';
  var url = 'sgsafe/Hiddendanger/qqId';
  var param = {
    params: val
  };
  await proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {

      aa = response.data.data;

      repairLL.value = response.data.data;
      jsons.value = {
        projectSafePerson: repairLL.value
      };

      function processValue(value) {
        const replacedValue = value.replace(/,/g, ';');
        const parts = replacedValue.split(';');
        const processedParts = parts.map(part => `U_${part.trim()}`);
        return processedParts.join(';');
      }

      const processedData = {};
      for (const key in jsons.value) {
        if (jsons.value.hasOwnProperty(key)) {
          processedData[key] = processValue(jsons.value[key]);
        }
      }
      aa = processedData.projectSafePerson;

    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
  return toRaw(aa);
};

const reback = () => {
};

const deleteRow = (row) => {
  selectedRows.value = [row];
  handleDelete(row);
};

const deleteRowa = (row) => {
  deleteRow(row);
};

const bm = (val) => {
};

import { workflowSubmit, workflowCancel } from '@/tools/workflow.js';
import AttachmentS3Image from '@/components/AttachmentS3ImageSY.vue';

const flowId = ref('');
flowId.value = 'ProjectWorkFlowId';
const handleSubmit2 = async (val, idx) => {
  openStatus.value[idx] = !openStatus.value[idx];
  openStatus.value = new Array(resultData.value.length).fill(true);
  console.log('提交');
  console.log('selectedRows', selectedRows.value);
  let row = val;
  form.value = { ...row };

  let b = {
    id: form.value.id,
    projectSafePerson: await qq('', form.value.projectSafePersonCode)
  };
  const aaa = JSON.stringify(toRaw(b));
  console.log('对象', aaa);
  sessionStorage.setItem('variables', aaa);

  flowId.value = 'ProjectWorkFlowId';

  console.log('----');
  console.log('flowData', form.value);
  console.log(flowId.value);
  console.log(sessionStorage.getItem('variables'));
  console.log(row.workId);
  console.log(row.trackId);
  showDialog({
      title: '提示',
      message: '确定提交审批？',
      showCancelButton: true,
      confirmButtonText: '确定',
      type: 'warning',
      cancelButtonText: '取消'
    }
  ).then(() => {
    return workflowSubmit(
      flowId.value,
      '风险告知人签字',
      '初始化提交',
      sessionStorage.getItem('variables'),
      row.workId,
      row.trackId);
  }).then((result) => {
    if (result.status === 'success') {
      var url = 'sgsafe/ProjectWork/saveProcessInfo';
      console.log('id', result, row.id);
      var process = {
        'id': form.value.id,
        'workId': result.workId,
        'trackId': result.trackId
      };
      var param = {
        json: JSON.stringify(process)
      };
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
          form.value = response.data.data;
          console.log('我要进来啦保存成功');
          showToast({
            type: 'success',
            message: '提交审批成功'
          });
          sendMessage(form.value.projectSafePersonCode, '项目作业管理流程', 'projectManage/todo_detail/index?id=' + form.value.id);
          onRefresh();
        }
      });
    } else {
      showToast({
        type: 'error',
        message: '提交审批失败，' + result.msg
      });
    }
  }).catch(() => {
    showToast({
      type: 'info',
      message: '已取消提交'
    });
  });
};

const sendMessage = (userCodes, content, routing) => {
  var url = 'sgsafe/ProjectWork/sendMessageProjectWork';
  var param = {
    params: JSON.stringify({
      userCodes,
      content,
      routing
    })
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '发送成功'
      });
    }
  });
};


const getStatusClass = (status) => {
  switch (status) {
    case '-1':
      return 'status-pending';
    case '0':
      return 'status-registered';
    case '1':
      return 'status-analyzing';
    case '2':
      return 'status-rectifying';
    case '3':
      return 'status-accepting';
    case '4':
      return 'status-closed';
    case '5':
      return 'status-finished';
    default:
      return 'status-unknown';
  }
};

const openStatus = ref([]);
const swipeCellRefs = ref([]);
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
};
const openSwipe = (idx) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = false;
    swipeCellRefs.value[idx].open('right');
  }
  document.addEventListener('click', handleDocumentClick);
};
const handleDocumentClick = (event) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
};

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = true;
    swipeCellRefs.value[idx].close();
  }
};

const handleSwipeOpen = (item, idx) => {
  console.log('handleSwipeOpen', idx);
  console.log('handleSwipeOpen数据', item);
  openStatus.value[idx] = false;
};

const handleSwipeClose = (item, idx) => {
  openStatus.value[idx] = true;
  console.log('handleSwipeClose', idx);
  console.log('handleSwipeClose数据', item);
};

</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-registered {
  background-color: #d1ecf1;
  color: #0c5460;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-analyzing {
  background-color: #fff8e1;
  color: #ff8f00;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-rectifying {
  background-color: #e8f5e9;
  color: #2e7d32;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-accepting {
  background-color: #e3f2fd;
  color: #1565c0;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-closed {
  background-color: #f8bbd0;
  color: #b71c1c;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-finished {
  background-color: #e8eaf6;
  color: #311b92;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-unknown {
  background-color: #efebe9;
  color: #424242;
  padding: 2px 4px;
  border-radius: 4px;
}

.cell-title {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1; /* 限制为1行，避免高度溢出 */
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px; /* 增加与下方内容的间距 */
}

/* 调整标签区域样式，避免内容溢出 */
.cell-label {
  font-size: 13px; /* 适当缩小字体 */
  line-height: 1.4; /* 调整行高 */
  color: #666;
}

/* 状态标签样式优化 */
.status-wrapper {
  display: inline-block;
  padding: 2px 8px; /* 用padding替代固定height */
  border-radius: 4px;
  color: white;
  margin-top: 2px;
}

.text-start {
  background-color: yellow;
  color: black;
}

.text-middle {
  background-color: green;
}

.text-end {
  background-color: #8d8989;
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
  align-items: center; /* 图标垂直居中 */
}

/* 滑动按钮高度与swipe-cell保持一致 */
.delete-button, .submit-button, .subsuccess {
  height: 100px; /* 与swipe-cell高度一致 */
  width: 80px; /* 适当加宽按钮 */
  border: none;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.delete-button {
  color: #ff0000;
  background-image: url('@/assets/img/del.png');
}

.submit-button {
  color: #07c160;
  background-image: url('@/assets/img/sub.png');
}

.subsuccess {
  color: #07c160;
  background-image: url('@/assets/img/sub1.png');
}

/* 修复van-cell默认样式影响 */
:deep(.van-cell) {
  background-color: transparent;
}

:deep(.van-swipe-cell) {
  margin-bottom: 5px; /* 增加列表项间距 */
  background-color: #fff;
  border-radius: 4px; /* 轻微圆角，优化视觉 */
}
</style>
