<script setup>
import { getCurrentInstance, onMounted, watch, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
const {
  proxy
} = getCurrentInstance()

/* 通用方法： 重置list数据 */
const basicReset = () => {
  finished.value = false;
  loading.value = true;
  pageNum.value = 1
  resultData.value = []
}


const dictList = ref([])

/* 返回上一级页面 */
const router = useRouter()

/* 在线预览实现 */
import {Base64} from "js-base64";
const linShiFid=ref({
  fileId:''
})
const handlePreview = (fileId) => {
  if (fetchData.value.ruleName) {
    sessionStorage.setItem("ruleName", fetchData.value.ruleName)
  }
  if (fetchData.value.ruleScope) {
    sessionStorage.setItem("ruleScope", fetchData.value.ruleScope)
  }
  linShiFid.value.fileId= fileId
  getTableDataQueryFile()
}
const bucket = ref(import.meta.env.VITE_BUCKET)
const getTableDataQueryFile = () => {
  var url = 'framework/Common/queryFileWithValues'
  var param = {
    fId: linShiFid.value.fileId,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      const downloadPath = import.meta.env.VITE_BASE_API + '/framework/Common/downloadFileS3?bucket='+ bucket.value + '&id='
      const fileListWithUrls = response.data.data.map(file => ({
        ...file,
        url: `${downloadPath}${file.id}`, // 添加完整的下载路径
        thumbUrl: `${downloadPath}${file.id}`, // 如果需要缩略图，可以使用相同的路径
        name: file.fileName, // 确保有文件名属性
        status: file.status, // 确保有状态属性
        id: file.id
      }));

      var originUrl = import.meta.env.VITE_PREVIEW_BASE_API + 'framework/Common/downloadFileS3?bucket=' + bucket.value +'&id=' + fileListWithUrls[0].id
      var previewUrl = originUrl + '&fullfilename=' + Date.now() + fileListWithUrls[0].name
      var url = import.meta.env.VITE_PREVIEW_API + 'onlinePreview?url=' + encodeURIComponent(Base64.encode(
        previewUrl)) + '&officePreviewType=pdf'
      window.open(url);
    } else {
      showFailToast('失败！' + response.data.msg)
    }
  })
}

/* 查询数据 */
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalMoney = ref(0) // 费用总金额

// 计算平均单笔费用
const averageExpense = computed(() => {
  return total.value > 0 ? (totalMoney.value / total.value).toFixed(2) : '0.00'
})
const resultData = ref([])
// const fetchData = ref({
//   ruleName:'',
//   ruleScope: ''
// })

const onSearch = () => {
  basicReset()
  onLoad()
}

const resetCondition = () => {
  basicReset()
  fetchData.value = {
    moneyDept: '',
    moneyType: '',
    moneyTypeId: '',
    useTimeStart: '',
    useTimeEnd: ''
  }
  onLoad()
}

const queryList = ref([])

/* 查询请求 */
const queryFetch = async () => {

  fetchData.value.ruleScope = postBackRegimeScope.value

  if (sessionStorage.getItem("ruleName")) {
    fetchData.value.ruleName = sessionStorage.getItem("ruleName")
    sessionStorage.removeItem("ruleName")
  }
  if (sessionStorage.getItem("ruleScope")) {
    const deptInfo = sessionStorage.getItem("ruleScope")
    fetchData.value.ruleScope = deptInfo
    postBackRegimeScope.value = deptInfo
    currentDeptName.value = deptInfo.split('-')[1]
    sessionStorage.removeItem("ruleScope")
  }
  // if(currentDeptName.value) {
  //   fetchData.value.moneyDept = currentDeptName.value
  // }

  // 构建查询参数，确保 moneyType 字段正确传递
  // 如果 moneyType 是 dicCode，需要转换为名称进行查询（因为后端使用 like 查询，数据库中存储的是名称）
  let moneyTypeForQuery = fetchData.value.moneyType || ''
  if (moneyTypeForQuery && moneyTypeMap.value[moneyTypeForQuery]) {
    // 如果是 dicCode，转换为名称进行查询
    moneyTypeForQuery = moneyTypeMap.value[moneyTypeForQuery]
  } else if (moneyTypeForQuery && moneyTypeMap.value[String(moneyTypeForQuery)]) {
    // 兼容字符串类型的 dicCode
    moneyTypeForQuery = moneyTypeMap.value[String(moneyTypeForQuery)]
  }
  
  const queryParams = {
    moneyDept: fetchData.value.moneyDept || '',
    moneyType: moneyTypeForQuery, // 传递名称（因为后端使用 like 查询）
    useTimeStart: fetchData.value.useTimeStart || '',
    useTimeEnd: fetchData.value.useTimeEnd || ''
  }
  
  console.log('查询参数:', queryParams)

  const url = '/sgsafe/MoneySafe/query'
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(queryParams)
  }
  try {
    const res = await proxy.$axios.post(url,param);
    console.log('查询结果:', res.data)
    if (res.data.code === 0) {
      total.value = res.data.data.total
      // 添加 canDelete 属性
      const currentUserId = String(localStorage.getItem('userId') || '');
      queryList.value = res.data.data.records.map(item => ({
        ...item,
        canDelete: String(item.addId || '') === currentUserId
      }))
      // 获取费用总金额
      totalMoney.value = res.data.data.totalMoney || 0
    } else {
      console.log('操作失败!' + res.data.msg)
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
/* 列表加载与下拉刷新 */
// const list = ref([]);
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

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

const onLoad = async () => {
  if (refreshing.value) {
    resultData.value = [];
    pageNum.value = 1;
    refreshing.value = false;
  }
  getDicList()
  try {
    await  queryFetch();
    if (pageSize.value * pageNum.value < total.value) {
      resultData.value = [...queryList.value,...resultData.value ]
      pageNum.value++;
    } else {
      resultData.value = [...queryList.value,...resultData.value ]
      finished.value = true;
    }
  } catch (error) {
    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

/* 组织树选择 */
const showBottom = ref(false)
const postBackRegimeScope = ref()
const currentDeptName = ref()
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast, showDialog, showSuccessToast } from 'vant';
import tools from "@/tools/index.js";
const showPickerHandle = () => {
  showBottom.value = true
}

const handleTableDataUserDeptUpdate = async (nodeData) => {
  postBackRegimeScope.value = nodeData
  currentDeptName.value = nodeData.split('-')[1]
  // 关键：用户主动选择部门时，设置查询条件
  fetchData.value.moneyDept = nodeData
  basicReset()
  await onLoad()
  showBottom.value = false
}

const getDeptInfo = (currentDeptInfo) => {
  // 只用于初始化显示当前组织名称，不设置查询条件
  postBackRegimeScope.value = currentDeptInfo
  currentDeptName.value = currentDeptInfo.split('-')[1]
  // 注意：这里不设置 fetchData.value.moneyDept，让查询条件保持为空
  // 这样页面初始化时会显示所有数据
}

// 添加页面初始化逻辑
onMounted(() => {
  // 页面加载时，先查询所有数据（不设置部门条件）
  getDicList()
  basicReset()
  onLoad()
})

//日期
const fetchData = ref({
  moneyDept: '', // 所属部门
  moneyType: '', // 费用类型（dicCode，用于查询）
  moneyTypeId: '', // 费用类型ID（兼容字段）
  useTimeStart: '', // 使用日期开始
  useTimeEnd: '' // 使用日期结束
})

// 添加日期范围处理
const dateRange = ref([])
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    fetchData.value.useTimeStart = newVal[0]
    fetchData.value.useTimeEnd = newVal[1]
  } else {
    fetchData.value.useTimeStart = ''
    fetchData.value.useTimeEnd = ''
  }
})

const guid = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyz'
  const length = chars.length
  const randomString = (len) => {
    const array = new Uint8Array(len)
    crypto.getRandomValues(array)
    return Array.from(array)
        .map(byte => chars[byte % length])
        .join('');
  }
  return `${randomString(8)}${randomString(8)}${randomString(8)}${randomString(8)}`;
}
const moneySafeForm = ref({
  id: '',
  moneyDept: '', // 所属部门
  moneyNumber: '', // 投入费用
  useTime: '', // 使用日期
  moneyType: '', // 费用类型
  moneyIn: '', // 资金来源
  moneyOut: '', // 资金使用情况说明
  otherDec: '', // 备注
  fileId: guid(), // 附件ID
  moneyTypeId:'' // 费用类型ID
})

const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);

// 临时存储选中的日期（因为 van-date-picker 需要数组格式）
const tempStartTime = ref([2024, 1, 1]);
const tempEndTime = ref([2024, 1, 1]);

// 格式化日期为 YYYY-MM-DD
const formatDate = (dateArray) => {
  const [year, month, day] = dateArray;
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
};

 const confirmStartTime = async () => {
  fetchData.value.useTimeStart = formatDate(tempStartTime.value);
  showStartTimePicker.value = false;
  if(fetchData.value.useTimeStart) {
   await queryFetch()
    resultData.value = queryList.value

  }
};

const confirmEndTime = async () => {
  fetchData.value.useTimeEnd = formatDate(tempEndTime.value);
  showEndTimePicker.value = false;
  if(fetchData.value.useTimeEnd) {
    await queryFetch()
    resultData.value = queryList.value

  }
  console.log('选中的日期：', fetchData.value.useTimeEnd)
};

const showPicker = ref(false)
// const columns = ref([{ text: '劳动保护用品', value: '劳动保护用品' },
//   { text: '安全工作激励', value: '安全工作激励' },
//   { text: '安全培训教育', value: '安全培训教育' },
//   { text: '检测与检验', value: '检测与检验' },
//   { text: '职业健康查体', value: '职业健康查体' },
//   { text: '应急与防护设施', value: '应急与防护设施' },
//   { text: '安全改造整改', value: '安全改造整改' },
//   { text: '其他', value: '其他' },
//
// ])
const columns = ref([])
const dicList = ref([])
const moneyTypeMap = ref({}) // 映射表：dicCode -> dicName，用于将数字转换为名称显示


const getDicList = () => {
  tools.dic.getDicList(['MONEY_TYPE']).then((response => {

    dictList.value = response.data.data
    columns.value = dictList.value.MONEY_TYPE.map(item => ({
      text: item.dicName,
      value: item.dicName // Web端保存的是 dicCode
    }))
  })).catch(error => {
    console.error('获取字典数据出错:', error)
    columns.value = []
  })
}

// 根据 dicCode 获取费用类型名称（用于显示转换）
const getMoneyTypeName = (value) => {
  if (!value) return ''
  
  // 先尝试直接查找（支持 dicCode）
  if (moneyTypeMap.value[value]) {
    return moneyTypeMap.value[value]
  }
  
  // 尝试转换为字符串查找（兼容数字类型的 dicCode）
  const strValue = String(value)
  if (moneyTypeMap.value[strValue]) {
    return moneyTypeMap.value[strValue]
  }
  
  // 如果找不到，可能是 H5 端保存的名称（直接返回）
  return value
}

const onConfirm = async (value) => {
  // value 是选中的值
  const selectedOption = value.selectedOptions[0]
  // 保存 dicCode 到 moneyType（用于查询）
  fetchData.value.moneyType = selectedOption.value
  // 同时保存到 moneyTypeId（如果后端需要）
  if (!fetchData.value.moneyTypeId) {
    fetchData.value.moneyTypeId = selectedOption.value
  }
  showPicker.value = false // 关闭弹窗
  // 重置分页并查询
  basicReset()
  await queryFetch()
  resultData.value = queryList.value
  console.log('选中的值：', selectedOption)
  console.log('查询条件 moneyType:', fetchData.value.moneyType)
}

const handAdd =  () => {
  router.push({ path: "/safeMoneyManagementList",
    query: {
      mark:-1,
      deptName: '测试部门名称'
    } });
};
const kz = ref(true);

const edits = async (row) => {
  const currentUserId = localStorage.getItem('userId');
  const addId = row.addId;

  const isOwner = String(addId).trim().toLowerCase() === String(currentUserId).trim().toLowerCase();

  kz.value = true;
  moneySafeForm.value = { ...row };
  router.push({ path: "/safeMoneyManagementList",
    query: {
      mark:1,
      data:JSON.stringify(moneySafeForm.value),
      readOnly: !isOwner ? 'true' : undefined  // 如果不是所有者，设置为只读
    } });
};

// 删除数据
const deleteData = ref({})

// 处理删除
const handleDelete = (item) => {
  const currentUserId = localStorage.getItem('userId');
  const addId = item.addId;

  if (!currentUserId || !addId || String(addId).trim() !== String(currentUserId).trim()) {
    showFailToast('无权限删除！只能删除自己添加的记录。');
    return;
  }
  
  showDialog({
    title: '删除确认',
    message: '确定要删除该费用记录吗？删除后将无法恢复。',
    showCancelButton: true,
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
  }).then(() => {
    executeDelete(item);
  }).catch(() => {
    console.log('取消删除');
  });
};

// 执行删除
const executeDelete = (item) => {
  const deleteDataItem = { ...item };
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  deleteDataItem.cancelTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  deleteDataItem.cancelFlag = '1';
  
  const url = '/sgsafe/MoneySafe/save';
  const param = {
    json: JSON.stringify(deleteDataItem)
  };
  
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0' || response.data.code === 0) {
      showSuccessToast("删除成功");
      onRefresh();
    } else {
      showFailToast('删除失败：' + (response.data.msg || '未知错误'));
    }
  }).catch(error => {
    showFailToast('删除失败：网络错误');
    console.error('删除失败:', error);
  });
};


</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="安环费用管理"  @click-right="handAdd" >
      <template #right>
        <van-icon name="add" size="25" color="#000" />
      </template>
      </van-nav-bar>
    </van-sticky>
    
    <!-- 统计信息卡片 -->
    <div class="statistics-container">
      <div class="stat-item">
        <div class="stat-label">费用总笔数</div>
        <div class="stat-value">{{ total }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">费用总金额(元)</div>
        <div class="stat-value">{{ totalMoney.toLocaleString() }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">平均单笔费用(元)</div>
        <div class="stat-value">{{ averageExpense }}</div>
      </div>
    </div>
    
    <!-- 原有的查询表单 -->
    <van-field
        v-model="currentDeptName"
        label="当前组织"
        placeholder="请选择组织架构"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle()"
    />

    <van-field
        :model-value="getMoneyTypeName(fetchData.moneyType)"
        is-link
        readonly
        name="picker"
        label="费用类型"
        placeholder="请选择"
        @click="showPicker = true"
    />
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
      />
    </van-popup>

    <van-field
        v-model="fetchData.useTimeStart"
        is-link
        readonly
        name="useTimeStart"
        label="开始时间"
        :colon="true"
        placeholder="点击选择开始时间"
        @click="showStartTimePicker = true"
    />
    <!-- 结束时间 -->
    <van-field
        v-model="fetchData.useTimeEnd"
        is-link
        readonly
        name="useTimeEnd"
        label="结束时间"
        :colon="true"
        placeholder="点击选择结束时间"
        @click="showEndTimePicker = true"
    />
    <!-- 开始时间选择器 -->
    <van-popup v-model:show="showStartTimePicker" position="bottom">
      <van-date-picker
          v-model="tempStartTime"
          type="date"
          @confirm="confirmStartTime"
          @cancel="showStartTimePicker = false"
          :columns-type="['year', 'month', 'day']"
      />
    </van-popup>

    <!-- 结束时间选择器 -->
    <van-popup v-model:show="showEndTimePicker" position="bottom">
      <van-date-picker
          v-model="tempEndTime"
          type="date"
          @confirm="confirmEndTime"
          @cancel="showEndTimePicker = false"
          :columns-type="['year', 'month', 'day']"
      />
    </van-popup>

    <div class="scroll-container">
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-list
          class="listDiv"
          v-model:loading="loading"
          :finished="finished"
          :immediate-check="false"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-for="item in resultData" :key="item.id" class="card">
            <van-swipe-cell>
              <template #default>
                <van-cell @click="edits(item)" :border="false" is-link>
                  <template #title>
                    <span class="bold-title" style="margin-left: 4px;">
                      <div>所属类型：{{ getMoneyTypeName(item.moneyType) }}</div>
                    </span>
                  </template>
                  <template #label>
                    <div class="label-content">
                      <div>费用来源：{{ item.moneyIn }}</div>
                      <div>投入费用：{{ item.moneyNumber }}</div>
                    </div>
                  </template>
                </van-cell>
              </template>
              <template #right>
                <van-button 
                  v-if="item.canDelete" 
                  square 
                  class="delete-button" 
                  text="删除" 
                  @click="handleDelete(item)" 
                />
              </template>
            </van-swipe-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-popup :close-on-click-overlay="false" :lazy-render="false" v-model:show="showBottom" position="bottom">
      <OrganizationalWithLeaf @init="getDeptInfo" @close="showBottom = false" @update:selected-node="handleTableDataUserDeptUpdate" />
    </van-popup>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;

}

.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

.scroll-container::-webkit-scrollbar {
  display: none;
}

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.bold-title {
  font-weight: bold;
  color: #333;
}

.statistics-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  margin-bottom: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-item {
  flex: 1;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-item:not(:last-child) {
  border-right: 1px solid #ebedf0;
}

.stat-label {
  font-size: 12px;
  color: #969799;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

.delete-button {
  height: 100%;
  border: none;
  color: #fff;
  background-color: #ee0a24;
  font-size: 16px;
  padding: 0 20px;
}
</style>
