<script setup>
import { getCurrentInstance, onMounted, ref , computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
const {
  proxy
} = getCurrentInstance()

let title = '新增安全文件'

/* 返回上一级页面 */
const router = useRouter()
const onClickLeft = () => {
  router.go(-1)
}

const currentYear = ref()
currentYear.value = new Date().getFullYear()

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


const deptName = deptInformation.value[0]?.deptName || ''
const deptCode = deptInformation.value[0]?.deptCode || ''

//  如果部门信息为空，给出提示
if (!deptCode) {
  console.warn('部门编码为空，可能影响数据保存')
}



// 添加：与Web端一致的 generateCode 函数
const generateCode = () => {
  // 获取当前日期并格式化为 YYYYMMDD
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
  const day = String(now.getDate()).padStart(2, '0');
  const formattedDate = `${year}${month}${day}`;
  
  // 时间部分：HHmmss
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${hours}${minutes}${seconds}`;
  
  // 模拟生成三位流水号（可以根据需要替换为递增逻辑）
  const sequenceNumber = Math.floor(Math.random() * 1000); // 随机生成 0-999
  const paddedSequence = String(sequenceNumber).padStart(3, '0'); // 补零到三位
  
  // 拼接编号
  return `LZFJ${formattedDate}${formattedTime}${paddedSequence}`;
};

// 使用 ref 存储生成的编号
const generatedCode = ref(generateCode());

// 定义重新生成编号的方法
const regenerateCode = () => {
  generatedCode.value = generateCode();
};

const formJieguo = ref({
  resultWhether:'',
  resultDetail:'',
  resultWhy:'',
  resultFile:'',
  itemsId:'',
  resultFileId:'',
  resType:''
})
const route = useRoute()
let planInfo = {}
const  userName1=localStorage.getItem('userName');

const result=ref('')
const fromVue=ref({})

// 修复：新增时初始化基础字段（与Web端保持一致）
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}

console.log(planInfo);
if (planInfo==-1){
  // 新增模式：初始化基础字段（与Web端handAdd函数保持一致）
  regenerateCode() // 重新生成编号
  result.value = generatedCode.value // 使用 generateCode 生成的编号
  fromVue.value = {
    id: '',  // 新增时 id 为空字符串
    fileName: '',
    fileType: '',
    fileContent: '',
    fileTime: '',  // 添加：Web端有此字段
    filePeoples: '',  // 添加：Web端有此字段
    fileSubmit: '',
    remarks: '',
    enable: '',
    fileNumber: '',
    yearValue: '',  // H5端特有
    fileId: result.value
  }
  console.log('生成的 fileId:', result.value);
}

const resDetail=ref('')
const ruleIds = ref([]);
/*const getRuleId = () => {
  var url = '/sgsafe/ExamHead/getCheckRuleId'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      ruleIds.value = response.data.data
    } else {
      console.log("1111111");
    }
  })
  console.log('ruleIds', ruleIds)
}
getRuleId()*/
const showRule=ref(false);

const distestType=ref(false)
if (planInfo==1) {
  console.log(planInfo);
  title = '修改安全文件'
  fromVue.value= JSON.parse(route.query.data)
  result.value=fromVue.value.fileId
  console.log(result.value);
}
 const  whether=ref(false)

const planLevelList1=ref([])


/* 下拉框 */
const showActionSheet = ref(false)
const showActionSheet1 = ref(false)
const planLevelList = [
  { name: '转发', value: '转发' },
  { name: '内部', value: '内部' },
  { name: '文章', value: '文章' }
];
const isdisabled=ref(true)
const isdisabled2=ref(true)
const onSelect = (item) => {
  fromVue.value.fileContent = item.name
  showActionSheet.value=false
  // 性质改变时也触发文件编号生成
  generateFileSumbmit()
}

const onSelect2 = (item) => {
  fromVue.value.fileType=item.name
  showActionSheet2.value=false
  // 文件类别改变时触发文件编号生成
  generateFileSumbmit()
}

const displayFileName = ref('')
const onSelect1 = (item) => {
  console.log(item);
  formJieguo.value.resultFile = item.value
  result.value=formJieguo.value.resultFile
  displayFileName.value = item.name
  console.log(result.value);
  showActionSheet1.value = false
}

const yearOptions = Array.from({ length: 10 }, (_, i) => {
  const year = currentYear.value - 5 + i;  // 修复：使用 currentYear.value
  return {
    text: String(year),
    value: String(year)
  };
}).reverse();
const showYearPicker = ref(false);

const formData = ref({
  year: String(currentYear.value),  // 修复：使用 currentYear.value
  quarter: null
})

// 年份选择确认
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;
  fromVue.value.yearValue = selectedYear; // 修复：同步到 fromVue
  showYearPicker.value = false;
  // 触发文件编号生成，而不是调用不存在的 search()
  generateFileSumbmit();
}


const questionIds = ref([])
const actions=ref([])
/*const getQuestionId = () => {
  var url = '/sgsafe/AssessmentRecord/queryRuleNoPage';
  var param = {};
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      questionIds.value = response.data.data; // 先赋值给 questionIds.value


      // 关键：使用 questionIds.value.map
      actions.value = questionIds.value.map(item => ({
        name: item.ruleName,
        value: item.id
      }));
      console.log('actions:', actions.value); // 看看有没有输出
    } else {
      ElMessage.error('操作失败！' + response.data.msg);
    }
  });
};
getQuestionId()*/

const baocun3 = (ruleFormRef) => {
  console.log(formJieguo.value)
  ruleFormRef.validate((valid, fields) => {
    if (valid) {

      var url = '/sgsafe/ItemsResult/save';
      var param = {
        json: JSON.stringify(formJieguo.value)
      };
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {
          getTableData1()
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          if (ruleFormRef.value) {
            ruleFormRef.value.resetFields();
          }
          dialogVisibletemplate.value=false
        } else {
          ElMessage.error('操作失败！' + response.data.msg)
        }

      })
    }
  })
}

/* 组织树选择 */
const showBottom = ref(false)
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';
const handleTableDataUserDeptUpdate = async (nodeData) => {
  formJieguo.value.drillDept = nodeData.deptCode + '-' + nodeData.deptName
  showBottom.value = false
}

const addEmergencyDrillPlan = async () => {
  // 参数验证
  if (!deptCode) {
    showFailToast('获取部门信息失败，请重新登录')
    return
  }
  
  if (!result.value) {
    showFailToast('文件ID生成失败，请重试')
    return
  }
  
  // 表单验证
  if (!fromVue.value.fileName) {
    showFailToast('请输入文件名称')
    return
  }
  
  if (!fromVue.value.fileType) {
    showFailToast('请选择文件类别')
    return
  }
  
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })
  
  try {
    // 与Web端保持一致：只设置 addDeptCode，其他字段已经在 fromVue.value 中
    fromVue.value.addDeptCode = deptCode
    
    // 确保 fileId 正确设置
    if (!fromVue.value.fileId) {
      fromVue.value.fileId = result.value
    }
    
    // 确保文件编号已生成
    if (!fromVue.value.fileSubmit && fromVue.value.fileType && fromVue.value.yearValue) {
      generateFileSumbmit()
    }
    
    // 调试：打印完整数据（与Web端保持一致）
    console.log('保存的数据：', JSON.stringify(fromVue.value))
    
    var url = '/sgsafe/ResponFile/save1';
    const params = {
      json: JSON.stringify(fromVue.value)
    }
    
    const res = await proxy.$axios.post(url, params)
    
    if (res.data.code === 0) {
      loadingToast.close()
      showSuccessToast('保存成功')
      onClickLeft()
    } else {
      loadingToast.close()
      showFailToast('操作失败!' + (res.data.msg || '未知错误'))
    }
  } catch (error) {
    loadingToast.close()
    console.error('保存失败：', error)
    // 打印详细错误信息
    console.error('错误详情：', error.response?.data || error)
    showFailToast('保存失败：' + (error.message || '网络错误，请稍后重试'))
  }
}
const showDatePicker = ref(false)
const onDatePicker = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.checkTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker.value = false
}
const currentDate = ref([2025, 7, 25])
//定义字典集合
const dicList = ref([])
//获取字典集合
import tools from '@/tools'
const getDicList = () => {
  // 修复：使用 'fileTypes' 而不是 'systemTypes'
  tools.dic.getDicList(['fileTypes']).then((response => {
    const rawData = response.data.data
    // 修复：使用 fileTypes 而不是 systemTypes，value 使用 dicName
    dicList.value = rawData.fileTypes.map(item => ({
      name: item.dicName,      // 使用 dicName
      value: item.dicName       // value 也使用 dicName，与 web 端保持一致
    }));
    console.log(JSON.stringify(dicList.value))
  }))
}

// 新增：文件编号自动生成函数
const generateFileSumbmit = () => {
  let fileSubmit = ''
  
  // 1. 根据文件类别拼接前缀
  if (fromVue.value.fileType && fromVue.value.fileType !== '其他') {
    const prefixMap = {
      '安全正式发文': '山信安管便字',
      '安全管理便文': '山信软件安字',
      '环保正式发文': '山信软件环字',
      '安委会纪要': '山信软件纪要安委字'
    }
    const prefix = prefixMap[fromVue.value.fileType]
    if (prefix) {
      fileSubmit += prefix
    }
  }
  
  // 2. 拼接年份
  if (fromVue.value.yearValue) {
    fileSubmit += `〔${fromVue.value.yearValue}〕`
  }
  
  // 3. 拼接编号
  if (fromVue.value.fileNumber) {
    fileSubmit += `${fromVue.value.fileNumber}号`
  }
  
  // 更新文件编号
  fromVue.value.fileSubmit = fileSubmit
}

onMounted(() => {
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1
  const day = today.getDate()
  currentDate.value = [year, month, day]
  
  // 新增：初始化年份值
  if (!fromVue.value.yearValue) {
    fromVue.value.yearValue = String(year)
    formData.value.year = String(year)
  }
  
  getDicList()
  
  // 新增：如果是编辑模式，初始化文件编号生成
  if (planInfo == 1) {
    generateFileSumbmit()
  }
})
const showActionSheet2=ref(false)
/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan()
}
const leaderKeyysr = generateCode(); // 或者保留 guid 用于其他用途
const PopupDepartmentLeaderNameRefysr = ref();
const handleDepartmentLeaderNameysr = () => {
  PopupDepartmentLeaderNameRefysr.value.open();
};
const getDepartmentLeaderNameysr = (item) => {
  fromVue.value.punCode = item.user.userCode;
  fromVue.value.punName = item.user.userDesc;
  fromVue.value.punId = item.user.id
};

</script>

<template>

  <div class="page-container">
    <van-sticky class="header">
      <van-nav-bar
        :title="title"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft" >
      </van-nav-bar>
    </van-sticky>
    <div class="scroll-container">
      <van-form @submit="onSubmit">
        <!-- 修复：文件编号改为只读，提示自动生成 -->
        <van-field
          v-model="fromVue.fileSubmit"
          label="文件编号"
          name="fileSubmit"
          required
          placeholder="选择文件类别、年份、编号后自动生成"
          readonly
          :rules="[{required: true, message: '请输入文件编号'}]"
        />

        <van-field
          v-model="fromVue.fileName"
          label="名称"
          name="fileName"
          required
          placeholder="请输入文件名称"
          :rules="[{required: true, message: '请输入文件名称'}]"
        />

        <van-field
          v-model="fromVue.fileType"
          readonly
          label="文件类别"
          name="fileType"
          required
          @click="showActionSheet2 = true"
        />
        
        <van-field
          :model-value="fromVue.yearValue"
          is-link
          readonly
          name="yearValue"
          label="年份"
          placeholder="点击选择年份"
          @click="showYearPicker = true"
        />
        <van-popup v-model:show="showYearPicker" position="bottom">
          <van-picker
            :columns="yearOptions"
            @confirm="onConfirmYear"
            @cancel="showYearPicker = false"
          />
        </van-popup>
        
        <!-- 新增：编号输入框 -->
        <van-field
          v-model="fromVue.fileNumber"
          label="编号"
          name="fileNumber"
          placeholder="请输入编号"
          @input="generateFileSumbmit"
        />
        
        <van-field
          readonly
          v-model="fromVue.fileContent"
          label="性质"
          name="fileContent"
          @click="showActionSheet = true"
        />

        <van-field
          v-model="fromVue.remarks"
          label="备注"
          name="remarks"
        />
        
        <van-field label="附件上传" >
          <template #input>
            <AttachmentS3 :f-id="result" />
          </template>
        </van-field>
        
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>

      <van-action-sheet
        v-model:show="showActionSheet"
        :actions="planLevelList"
        @select="onSelect"
      />
      <van-action-sheet
        v-model:show="showActionSheet2"
        :actions="dicList"
        @select="onSelect2"
      />

      <van-action-sheet
        v-model:show="showActionSheet1"
        :actions="planLevelList1"
        field-names="{ text: 'fileName', value: 'fileId' }"
        @select="onSelect1"
      />

      <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '30%' }">
        <OrganizationalWithLeaf @update:selected-node="handleTableDataUserDeptUpdate" />
      </van-popup>
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-date-picker
          v-model="currentDate"
          @confirm="onDatePicker"
          @cancel="showDatePicker = false" />
      </van-popup>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;

}
/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.header, .footer {
  /* 固定高度区域 */
  flex-shrink: 0; /* 防止被压缩 */
  background: #f5f5f5;
  padding: 12px;
}
.row-container {
  display: flex;
  justify-content: space-between; /* 关键：左右分布 */
  align-items: center;             /* 垂直居中 */

}

.cell-period-text {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

}

.mini-btn {
  height: 22px;
  font-size: 12px;
  padding: 0 8px;
  min-width: 60px;                 /* 可选：保持按钮最小宽度一致 */
}
</style>
