<script setup>
import { getCurrentInstance, onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showFailToast, showSuccessToast, showDialog, showLoadingToast } from 'vant';
import tools from "@/tools/index.js";

const { proxy } = getCurrentInstance()
const router = useRouter()

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

/* 查询数据 */
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const resultData = ref([])
const queryList = ref([])

// 年份选择
const currentYear = new Date().getFullYear();
const yearOptions = Array.from({ length: 10 }, (_, i) => {
  const year = currentYear - 5 + i;
  return {
    text: String(year),
    value: String(year)
  };
}).reverse();
const showYearPicker = ref(false);

const formData = ref({
  year: String(currentYear),
  quarter: null
})

// 获取用户部门信息
const jsonArray = localStorage.getItem('dept')
const deptInformation = ref([])
try {
  deptInformation.value = jsonArray ? JSON.parse(jsonArray) : [];
} catch (error) {
  deptInformation.value = [];
}

const jsonArrayTree = localStorage.getItem('deptTree')
const deptInformationTree = ref([])
try {
  deptInformationTree.value = jsonArrayTree ? JSON.parse(jsonArrayTree) : [];
} catch (error) {
  deptInformationTree.value = [];
}

const deptNameTree = deptInformationTree.value[0]?.deptName || ''
const deptCode = deptInformation.value[0]?.deptCode?.substring(0, 5) || ''

const tableData = ref([])
const loading = ref(false)

// 格式化数字显示（0 显示为空）
const formatterZero = (value) => {
  return value === 0 || value === '0' || value === null || value === undefined ? '' : value
}

// 计算 1-9 月合计
const formatterSum1To9 = (row) => {
  const months = [
    row.oneMonth,
    row.twoMonth,
    row.threeMonth,
    row.fourMonth,
    row.fiveMonth,
    row.sixMonth,
    row.sevenMonth,
    row.eightMonth,
    row.nineMonth
  ]
  const sum = months
    .map(val => {
      const num = Number(val)
      return isNaN(num) ? 0 : num
    })
    .reduce((a, b) => a + b, 0)
  return sum === 0 && months.every(v => !v) ? '' : sum
}

// 年份选择确认
const onConfirmYear = (value) => {
  let selectedYear = '';
  if (value && value.selectedOptions && value.selectedOptions.length > 0) {
    const selectedOption = value.selectedOptions[0];
    selectedYear = typeof selectedOption === 'string' ? selectedOption : selectedOption.value || selectedOption.text;
  } else if (typeof value === 'string') {
    selectedYear = value;
  }
  
  formData.value.year = selectedYear;
  showYearPicker.value = false;
  search();
}

// 查询
const search = async () => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth()
  const currentQuarter = Math.ceil((currentMonth + 1) / 3)

  if (!formData.value.year) {
    formData.value.year = String(currentYear)
  }
  if (!formData.value.quarter) {
    formData.value.quarter = currentQuarter
  }

  loading.value = true
  await getTableData()
}

// 重置
const reset = () => {
  formData.value.year = String(currentYear)
  formData.value.quarter = null
  search()
}

// 获取表格数据
const getTableData = async () => {
  try {
    const res = await proxy.$axios.post('/sgsafe/expect/query', {
      params: JSON.stringify(formData.value)
    })

    if (res.data.code == '0') {
      tableData.value = res.data.data || []
      resultData.value = tableData.value
      total.value = tableData.value.length
    } else {
      showFailToast('加载失败：' + res.data.msg)
    }
  } catch (error) {
    console.error('请求失败:', error)
    showFailToast('网络错误，请重试')
  } finally {
    loading.value = false
    finished.value = true
  }
}

// 新增行
const addRow = () => {
  router.push({ 
    path: "/safeMoneyBudgetList",
    query: {
      mark: -1,
      year: formData.value.year
    }
  });
}

// 编辑行
const editRow = (row) => {
  router.push({ 
    path: "/safeMoneyBudgetList",
    query: {
      mark: 1,
      data: JSON.stringify(row),
      year: formData.value.year
    }
  });
}

// 删除行
const deleteRow = async (row) => {
  try {
    await showDialog({
      title: '删除确认',
      message: '确定要删除该条记录吗？此操作不可恢复。',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    loading.value = true
    const deleteDataItem = { ...row }
    deleteDataItem.cancelFlag = '1'
    
    const res = await proxy.$axios.post('/sgsafe/expect/save', {
      json: JSON.stringify(deleteDataItem)
    })
    
    if (res.data.code == '0') {
      showSuccessToast('删除成功')
      tableData.value = tableData.value.filter(r => r.id !== row.id)
      resultData.value = tableData.value
    } else {
      showFailToast('删除失败：' + res.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      showFailToast('删除操作异常')
    }
  } finally {
    loading.value = false
  }
}

// 列表加载与下拉刷新
const refreshing = ref(false)
const finished = ref(false)

const onRefresh = async () => {
  refreshing.value = true
  basicReset()
  await search()
  refreshing.value = false
};

const onLoad = async () => {
  // 如果是下拉刷新，已经在 onRefresh 中处理了
  if (refreshing.value) {
    return
  }
  
  // 上拉加载更多（如果需要分页的话）
  if (finished.value) {
    return
  }
  
  await search()
};

// 获取费用类型字典
const moneyTypeMap = ref({})
const getMoneyTypeName = (value) => {
  if (!value) return ''
  if (moneyTypeMap.value[value]) {
    return moneyTypeMap.value[value]
  }
  const strValue = String(value)
  if (moneyTypeMap.value[strValue]) {
    return moneyTypeMap.value[strValue]
  }
  return value
}

const getDicList = () => {
  tools.dic.getDicList(['MONEY_TYPE']).then((response => {
    if (response.data && response.data.code === 0 && response.data.data) {
      const moneyTypeList = response.data.data.MONEY_TYPE || []
      moneyTypeMap.value = {}
      moneyTypeList.forEach(item => {
        if (item.dicCode && item.dicName) {
          moneyTypeMap.value[item.dicCode] = item.dicName
          moneyTypeMap.value[String(item.dicCode)] = item.dicName
        }
        if (item.dicName) {
          moneyTypeMap.value[item.dicName] = item.dicName
        }
      })
    }
  })).catch(error => {
    console.error('获取字典数据出错:', error)
  })
}

onMounted(() => {
  getDicList()
  search()
})
</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="安全费用预算" @click-right="addRow">
        <template #right>
          <van-icon name="add" size="25" color="#000" />
        </template>
      </van-nav-bar>
    </van-sticky>

    <!-- 查询区域 -->
    <div class="query-area">
      <van-field
        :model-value="formData.year"
        is-link
        readonly
        name="year"
        label="年份"
        placeholder="点击选择年份"
        @click="showYearPicker = true"
      />
      <div class="query-buttons">
        <van-button type="primary" size="small" @click="search">查询</van-button>
        <van-button size="small" @click="reset">重置</van-button>
      </div>
    </div>

    <van-popup v-model:show="showYearPicker" position="bottom">
      <van-picker
        :columns="yearOptions"
        @confirm="onConfirmYear"
        @cancel="showYearPicker = false"
      />
    </van-popup>

    <div class="scroll-container">
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-list
          v-model:loading="loading"
          :finished="finished"
          :immediate-check="false"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-for="item in resultData" :key="item.id || item.tempId" class="card">
            <van-swipe-cell>
              <template #default>
                <van-cell @click="editRow(item)" :border="false" is-link>
                  <template #title>
                    <div class="card-title">
                      <div class="title-row">
                        <span class="label">费用类型：</span>
                        <span class="value">{{ getMoneyTypeName(item.moneyType) || '未设置' }}</span>
                      </div>
                    </div>
                  </template>
                  <template #label>
                    <div class="card-content">
                      <div class="content-row">
                        <span class="label">预计投入费用：</span>
                        <span class="value">{{ formatterZero(item.moneyNumber) || '0' }}</span>
                      </div>
                      <div class="content-row">
                        <span class="label">1-9月合计：</span>
                        <span class="value">{{ formatterSum1To9(item) || '0' }}</span>
                      </div>
<!--                      <div class="months-grid">-->
<!--                        <div class="month-item" v-for="(month, index) in [-->
<!--                          { key: 'oneMonth', label: '1月' },-->
<!--                          { key: 'twoMonth', label: '2月' },-->
<!--                          { key: 'threeMonth', label: '3月' },-->
<!--                          { key: 'fourMonth', label: '4月' },-->
<!--                          { key: 'fiveMonth', label: '5月' },-->
<!--                          { key: 'sixMonth', label: '6月' },-->
<!--                          { key: 'sevenMonth', label: '7月' },-->
<!--                          { key: 'eightMonth', label: '8月' },-->
<!--                          { key: 'nineMonth', label: '9月' },-->
<!--                          { key: 'tenMonth', label: '10月' },-->
<!--                          { key: 'elevenMonth', label: '11月' },-->
<!--                          { key: 'twelveMonth', label: '12月' }-->
<!--                        ]" :key="month.key">-->
<!--                          <span class="month-label">{{ month.label }}：</span>-->
<!--                          <span class="month-value">{{ formatterZero(item[month.key]) || '0' }}</span>-->
<!--                        </div>-->
<!--                      </div>-->
                    </div>
                  </template>
                </van-cell>
              </template>
              <template #right>
                <van-button 
                  square 
                  class="delete-button" 
                  text="删除" 
                  @click="deleteRow(item)" 
                />
              </template>
            </van-swipe-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

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

.query-area {
  background-color: #f8f9fa;
  padding: 12px;
  border-bottom: 1px solid #ebedf0;
}

.query-buttons {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.query-buttons .van-button {
  flex: 1;
}

.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;
}

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

.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.card-content {
  margin-top: 8px;
}

.content-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #969799;
  margin-right: 8px;
  min-width: 80px;
}

.value {
  color: #323233;
  font-weight: 500;
}

.months-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #ebedf0;
}

.month-item {
  display: flex;
  flex-direction: column;
  font-size: 12px;
}

.month-label {
  color: #969799;
  margin-bottom: 4px;
}

.month-value {
  color: #323233;
  font-weight: 500;
}

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