<script setup>
import { getCurrentInstance, onMounted, ref, computed, nextTick,reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';
import tools from '@/tools'

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

const onClickLeft = () => {
  router.go(-1)
}

// 获取用户部门信息
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 isEdit = ref(route.query.mark === '1')
const title = computed(() => isEdit.value ? '编辑费用预算' : '新增费用预算')

// 费用类型选择器
//const moneyTypeFlag = ref(false)
const columnsLevel = ref([])
const moneyTypeMap = 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 budgetForm = reactive({
  id: null,
  tempId: null,
  moneyType: '',
  oneMonth: '',
  twoMonth: '',
  threeMonth: '',
  fourMonth: '',
  fiveMonth: '',
  sixMonth: '',
  sevenMonth: '',
  eightMonth: '',
  nineMonth: '',
  tenMonth: '',
  elevenMonth: '',
  twelveMonth: '',
  moneyNumber: '',
  yearTime: route.query.year || String(currentYear),
  moneyDept: deptNameTree,
  addDeptCode: deptCode
})

// 初始化表单数据
// if (isEdit.value && route.query.data) {
//   try {
//     const editData = JSON.parse(route.query.data)
//     budgetForm.value = {
//       ...budgetForm.value,
//       ...editData
//     }
//   } catch (error) {
//     console.error('解析编辑数据失败:', error)
//   }
// } else {
//   // 新增模式，生成临时ID
//   budgetForm.value.tempId = 'temp_' + Date.now()
// }

// 初始化表单数据
if (isEdit.value && route.query.data) {
  try {
    const editData = JSON.parse(route.query.data)
    // 只更新已有字段，避免破坏 reactive 响应性
    for (const key in budgetForm) {
      if (key in editData) {
        budgetForm[key] = editData[key]
      }
    }
  } catch (error) {
    console.error('解析编辑数据失败:', error)
  }
} else {
  budgetForm.tempId = 'temp_' + Date.now()
}

// 费用类型选择确认
// const moneyTypeLevelConfirm = ({ selectedOptions }) => {
//   moneyTypeFlag.value = false;
//   budgetForm.value.moneyType = selectedOptions[0].text;
// };

// 获取费用类型字典
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 || []
      columnsLevel.value = moneyTypeList.map(item => ({
        text: item.dicName,
        value: item.dicName
      }))
      
      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)
    columnsLevel.value = []
  })
}

// 格式化数字输入
const formatNumberInput = (value) => {
  if (value === '' || value === null || value === undefined) {
    return null
  }
  const num = Number(value)
  return isNaN(num) ? null : num
}

// 保存数据
const saveBudget = async () => {
  // 验证必填字段
  if (!budgetForm.moneyType) {
    showFailToast('请选择费用类型')
    return
  }

  const loadingToast = showLoadingToast({
    duration: 0,
    message: '保存中...',
    forbidClick: true
  })

  try {
    const submitData = { ...budgetForm }
    delete submitData.tempId

    const response = await proxy.$axios.post('/sgsafe/expect/save', {
      json: JSON.stringify(submitData)
    })

    if (response.data.code == '0') {
      loadingToast.close()
      showSuccessToast('保存成功')
      
      // 如果是新增且返回了ID，更新表单ID
      if (!budgetForm.id && response.data.data?.id) {
        budgetForm.id = response.data.data.id
      }
      
      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        onClickLeft()
      }, 500)
    } else {
      loadingToast.close()
      showFailToast('保存失败：' + response.data.msg)
    }
  } catch (error) {
    loadingToast.close()
    showFailToast('保存失败，请检查网络')
    console.error('保存错误:', error)
  }
}

// 月份字段列表
const monthFields = [
  { 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月' }
]
const showYearPicker = ref(false)
const onYearConfirm = ({ selectedOptions }) => {
  // 处理对象数组格式的选中值
  let selectedYear = ''
  if (selectedOptions && selectedOptions.length > 0) {
    const selectedOption = selectedOptions[0]
    selectedYear = typeof selectedOption === 'string' 
      ? selectedOption 
      : selectedOption.value || selectedOption.text
  }
  budgetForm.yearTime = selectedYear
  showYearPicker.value = false
}
// 计算 1-9 月合计
const sum1To9 = computed(() => {
  const months = [
    budgetForm.oneMonth,
    budgetForm.twoMonth,
    budgetForm.threeMonth,
    budgetForm.fourMonth,
    budgetForm.fiveMonth,
    budgetForm.sixMonth,
    budgetForm.sevenMonth,
    budgetForm.eightMonth,
    budgetForm.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
})

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

<template>
  <div class="page-container">
    <van-sticky class="header">
      <van-nav-bar
        :title="title"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </van-sticky>

    <div class="scroll-container">
      <van-form @submit="saveBudget">
        <!-- 费用类型 -->
        <van-field
          v-model="budgetForm.moneyType"
          label="费用类型"
          name="moneyType"
          placeholder="请输入费用类型"
          type="textarea"
          autosize="ture"
          :rules="[{required: true, message: '请输入费用类型'}]"
          required

        />

        <!-- 1-12月输入 -->
        <div class="months-section">
          <div class="section-title">月度预算</div>
          <div class="months-grid">
            <van-field
                v-for="month in monthFields"
                :key="month.key"
                v-model.number="budgetForm[month.key]"
                :label="month.label"
                :name="month.key"
                type="number"
                placeholder="0"
            />
          </div>
        </div>

        <!-- 1-9月合计（只读显示） -->
        <van-field
          :model-value="sum1To9"
          label="1-9月合计"
          name="sum1To9"
          readonly
          placeholder="自动计算"
        />

        <!-- 预计投入费用 -->
        <van-field
          v-model.number="budgetForm.moneyNumber"
          label="预计投入费用"
          name="moneyNumber"
          type="number"
          placeholder="请输入预计投入费用"
          :rules="[{ pattern: /^\d+(\.\d+)?$/, message: '请输入有效数字' }]"
        />

        <!-- 年份（只读显示） -->
        <van-field
          :model-value="budgetForm.yearTime"
          label="年份"
          name="yearTime"
          readonly
          is-link
          placeholder="请选择年份"
          @click="showYearPicker = true"
        />
        <van-popup v-model:show="showYearPicker" position="bottom">
          <van-picker
              :columns="yearOptions"
              @confirm="onYearConfirm"
              @cancel="showYearPicker = false"
          />
        </van-popup>

        <!-- 所属部门（只读显示） -->
        <van-field
            v-if="false"
          :model-value="budgetForm.moneyDept"
          label="所属部门"
          name="moneyDept"
          readonly
        />

        <!-- 提交按钮 -->
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            保存
          </van-button>
        </div>
      </van-form>

      <!-- 费用类型选择器 -->
<!--      <van-popup v-model:show="moneyTypeFlag" round position="bottom">-->
<!--        <van-picker-->
<!--          :columns="columnsLevel"-->
<!--          @cancel="moneyTypeFlag = false"-->
<!--          @confirm="moneyTypeLevelConfirm"-->
<!--        />-->
<!--      </van-popup>-->
    </div>
  </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;
}

.months-section {
  margin: 16px 0;
  background-color: #fff;
}

.section-title {
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  border-bottom: 1px solid #ebedf0;
}

.months-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0;
}

.months-grid .van-field {
  border-bottom: 1px solid #ebedf0;
  border-right: 1px solid #ebedf0;
}

.months-grid .van-field:nth-child(3n) {
  border-right: none;
}

.header {
  flex-shrink: 0;
  background: #fff;
}
</style>
