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


const columnsIn = ref([{text: '公司专项', value: '公司专项'},
    {text: '自筹', value: '自筹'},
    {text: '其他', value: '其他'},])

// 定义生成编号的函数（你已写好的逻辑）

const generateCode = () => {
  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 formattedDate = `${year}${month}${day}`;
  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);
  const paddedSequence = String(sequenceNumber).padStart(3, '0');
  return `SGAL${formattedDate}${formattedTime}${paddedSequence}`;
};

// 存储生成的编号（响应式变量）
const generatedCode = ref(generateCode());

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

const caseSourceFlag = ref(false)
const moneyTypeFlag = ref(false)
const moneyInFlag = ref(false)

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 = [];
}
const deptName = deptInformation.value[0].deptName
const deptCode = deptInformation.value[0].deptCode

const guid = () =>  {
  function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }
  return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4())
}
const formJieguo = ref({
  resultWhether:'',
  resultDetail:'',
  resultWhy:'',
  resultFile:'',
  itemsId:'',
  resultFileId:'',
  resType:''
})
const route = useRoute()

const currentDeptName = ref('')
console.log('获取路由传值信息',route)
currentDeptName.value = route.query.deptName
let planInfo = {}
const  userName1=localStorage.getItem('userName');
const isEdit = ref(route.query.mark === '1');
const isReadOnly = ref(route.query.readOnly === 'true');
const isCaseSubmitted = computed(() => isReadOnly.value && isEdit.value);
const result=ref('')

const moneySafeForm = ref({
  id: '',
  moneyDept: '', // 所属部门
  moneyNumber: '', // 投入费用
  useTime: '', // 使用日期
  moneyType: '', // 费用类型
  moneyIn: '', // 资金来源
  moneyOut: '', // 资金使用情况说明
  otherDec: '', // 备注
  fileId: guid(), // 附件ID
  moneyTypeId:'' // 费用类型ID
})
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}

console.log(planInfo);
// 新增模式
if (planInfo==-1){
  const caseNumber = generateCode();
  const fileId = ref()
  result.value= caseNumber
  //初始化 moneySafeForm
  moneySafeForm.value = {
    id: '',
    moneyDept: '', // 所属部门
    moneyNumber: '', // 投入费用
    useTime: '', // 使用日期
    moneyType: '', // 费用类型
    moneyIn: '', // 资金来源
    moneyOut: '', // 资金使用情况说明
    otherDec: '', // 备注
    fileId: guid(), // 附件ID
    moneyTypeId:'' // 费用类型ID
  };
  console.log( result.value);
}
if (planInfo==1) {
  console.log(planInfo);
  title = '查看安环费用管理'
  moneySafeForm.value= JSON.parse(route.query.data)
  if (!moneySafeForm.value.fileId) {
    const newFileId = guid();
    moneySafeForm.value.fileId = newFileId;
    result.value = newFileId;
  } else {
    result.value = moneySafeForm.value.fileId;
  }

  console.log('编辑模式 - fileId:', result.value);
}

const moneySafeFormRef = ref()
const moneySafeFormRules = ref({
  moneyDept: [{ required: true, message: '请输入所属部门' }],
  moneyNumber: [{ required: true, message: '请输入投入费用' }],
  useTime: [{ required: true, message: '请选择使用日期' }],
  moneyType: [{ required: true, message: '请选择费用类型' }],
  moneyIn: [{ required: true, message: '请选择资金来源' }],
  moneyOut: [{ required: true, message: '请输入资金使用情况说明' }]
})


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 onConfirmDatetime = () => {
  const year = currentDate.value[0];
  const month = currentDate.value[1].toString().padStart(2, '0');
  const day = currentDate.value[2].toString().padStart(2, '0');

  moneySafeForm.value.useTime = `${year}-${month}-${day}`;
  showDatetimePicker.value = false;
  dateOrTime.value = false;
};


const showDatetimePicker = ref(false);
const currentTime = ref();
const minDate = ref(new Date(1900, 0, 1)); // 初始化最小日期
const maxDate = ref(new Date(2100, 11, 31)); // 初始化最大日期

const dateOrTime = ref(false);
const onDateConfirm = () => {
  // 日期选择确认后的处理
  moneySafeForm.value.useTime = currentDate.value[0] + '-' + currentDate.value[1] + '-' + currentDate.value[2];
  showDatetimePicker.value = false
};
const resetDatetime = () => {
  dateOrTime.value = false;

  // 初始化日期和时间
  if (moneySafeForm.value.useTime) {
    // 修复：使用 useTime 而不是 accidentTime
    const dt = new Date(moneySafeForm.value.useTime);
    currentDate.value = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
  } else {
    const now = new Date();
    currentDate.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
  }
};
const cancelDatePicker = () => {
  // 先关闭弹窗，避免在关闭过程中触发重置导致错误
  showDatetimePicker.value = false;
  // 使用 nextTick 确保弹窗关闭后再重置，避免状态冲突
  nextTick(() => {
    resetDatetime();
  });
};

// 时间选择器取消
const cancelTimePicker = () => {
  resetDatetime();
  // 重置为当前时间或从表单获取时间
  if (moneySafeForm.value.useTime) {
    const dt = new Date(moneySafeForm.value.useTime);
  } else {
    const now = new Date();
    currentTime.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};


/* 下拉框 */
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) => {
  moneySafeForm.value.fileContent = item.name

  showActionSheet.value=false
}

const onSelect2 = (item) => {
  moneySafeForm.value.fileType=item.name
  showActionSheet2.value=false
  }

const onCaseSourseSelect = (item) => {
  moneySafeForm.value.caseSource=item.dicCode
  caseSourceFlag.value = false
}

const onAccidentLevelSelect = (item) => {
  moneySafeForm.value.accidentLevel = item.dicCode
  moneyTypeFlag.value = false

}

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 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


      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) => {
  moneySafeForm.value.moneyDept = nodeData
  showBottom.value = false
}

const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })

  moneySafeForm.value.fileId = result.value

  var url = '/sgsafe/MoneySafe/save';
  const params = {
    json: JSON.stringify(moneySafeForm.value)
  }
  proxy.$axios.post(url,params).then(res=>{
    if (res.data.code === 0) {
      loadingToast.close()
      showSuccessToast('保存成功')
      onClickLeft()

    } else {
      loadingToast.close()
      showFailToast('操作失败!' + res.data.msg)
    }
  })
}
const showDatePicker = ref(false)
const onDatePicker = (value) => {
  const dateArr = value.selectedValues
  moneySafeForm.value.checkTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker.value = false
}
const currentDate = ref([2025, 7, 25])
//定义字典集合
const dicList = ref([])
const dictList = ref([])

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

    dictList.value = response.data.data
    columnsLevel.value = dictList.value.MONEY_TYPE.map(item => ({
      text: item.dicName,
      value: item.dicName
    }))
  })).catch(error => {
    console.error('获取字典数据出错:', error)
    columns.value = []
  })
}
onMounted(() => {
  //getAccidentDicList()
  console.log('这是编辑页面')
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1 // 月份从 0 开始
  const day = today.getDate()
  currentDate.value = [year, month, day]
  
  // 确保 minDate 和 maxDate 已初始化
  if (!minDate.value) {
    minDate.value = new Date(1900, 0, 1);
  }
  if (!maxDate.value) {
    maxDate.value = new Date(2100, 11, 31);
  }
  
  // 初始化时间
  currentTime.value = [today.getHours(), today.getMinutes(), today.getSeconds()];
  // 如果是编辑模式且有已有的使用日期，解析并初始化
  if (isEdit.value && moneySafeForm.value.useTime) {
    try {
      // 解析格式如 "2025-01-15" 的日期字符串
      const dateStr = moneySafeForm.value.useTime;
      const [year, month, day] = dateStr.split('-').map(Number);
      if (year && month && day) {
        currentDate.value = [year, month, day];
      }
    } catch (error) {
      console.error('解析使用日期失败:', error);
    }
  }
  getDicList()
})
const showActionSheet2=ref(false)
/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan()
}
const leaderKeyysr = guid();
const PopupDepartmentLeaderNameRefysr = ref();
const handleDepartmentLeaderNameysr = () => {
  PopupDepartmentLeaderNameRefysr.value.open();
};
const getDepartmentLeaderNameysr = (item) => {
  moneySafeForm.value.punCode = item.user.userCode;
  moneySafeForm.value.punName = item.user.userDesc;
  moneySafeForm.value.punId = item.user.id
};

const onCaseSourceConfirm = ({ selectedOptions }) => {
  caseSourceFlag.value = false;
  moneySafeForm.value.caseSource = selectedOptions[0].text;
};

const moneyTypeLevelConfirm = ({ selectedOptions }) => {
  moneyTypeFlag.value = false;
  moneySafeForm.value.moneyTypeId = selectedOptions[0].value;
  moneySafeForm.value.moneyType = selectedOptions[0].text;
};

const moneyInConfirm = ({ selectedOptions }) => {
  moneyInFlag.value = false;
  moneySafeForm.value.moneyIn = selectedOptions[0].text;
};

const getDeptInfo = (currentDeptInfo) => {
  // 如果需要初始化部门信息，可以在这里处理
  // 例如：moneySafeForm.value.moneyDept = currentDeptInfo
}
</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="moneySafeForm.moneyDept"
        label="所属部门"
        name="moneyDept"
        readonly
        placeholder="请选择所属部门"
        @click="!isCaseSubmitted && (showBottom = true)"
        :rules="[{required: true, message: '请选择所属部门'}]"
        required
      />

        <van-field
          v-model="moneySafeForm.moneyNumber"
          label="投入费用"
          name="moneyNumber"
          :readonly="isCaseSubmitted"
          required
          placeholder="请输入投入费用"
          :rules="[{required: true, message: '请输入投入费用'}]"
        />

        <!--        //时间-->
        <van-field
            v-model="moneySafeForm.useTime"
            is-link
            readonly
            name="useTime"
            label="使用日期"
            :colon="true"
            placeholder="点击选择日期"
            @click="showDatetimePicker = !isCaseSubmitted"
            :rules="[{ required:true, message: '请点击选择日期' }]"
            required
        />
        <van-popup
            v-model:show="showDatetimePicker"
            position="bottom"
            round
            style="max-height: 50vh;"
        >
          <van-date-picker
              v-model="currentDate"
              title="选择日期"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onDateConfirm"
              @cancel="cancelDatePicker"
          >
            <template #confirm>
              <van-button type="primary" @click="onDateConfirm">确认</van-button>
            </template>
            <template #cancel>
              <van-button type="danger" @click="cancelDatePicker">取消</van-button>
            </template>
          </van-date-picker>

        </van-popup>


        <van-field
          v-model="moneySafeForm.moneyType"
          is-link
          readonly
          label="费用类型"
          name="moneyType"
          placeholder="请选择"
          @click="!isCaseSubmitted && (moneyTypeFlag = true)"
          :rules="[{required: true, message: '请选择费用类型'}]"
          required
        />

        <van-field
            v-model="moneySafeForm.moneyIn"
            is-link
            readonly
            label="资金来源"
            name="moneyIn"
            placeholder="请选择"
            :rules="[{required: true, message: '请选择资金来源'}]"
            @click="!isCaseSubmitted && (moneyInFlag = true)"
            required
        />

        <van-field
            v-model="moneySafeForm.moneyOut"
            label="资金使用情况说明"
            name="casualtyCount"
            rows="1"
            autosize
            type="textarea"
            placeholder="请输入事故造成后果"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入事故造成后果'}]"
            required
        />
        <van-field
            v-model="moneySafeForm.otherDec"
            label="备注"
            name="accidentSummary"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入事故简要经过"
            :readonly="isCaseSubmitted"
        />
        <div style="margin: 16px;">
          <van-button v-if="!isReadOnly" round block type="primary" native-type="submit">
            {{ isEdit ? '保存' : '提交' }}
          </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="caseSourceFlag"
          :actions="accidentDictList.case_source"
          @select="onCaseSourseSelect"
      />

      <van-popup v-model:show="caseSourceFlag" round position="bottom">
        <van-picker
            :columns="columns"
            @cancel="caseSourceFlag = false"
            @confirm="onCaseSourceConfirm"
        />
      </van-popup>

      <van-popup v-model:show="moneyTypeFlag" round position="bottom">
        <van-picker
            :columns="columnsLevel"
            @cancel="moneyTypeFlag = false"
            @confirm="moneyTypeLevelConfirm"
        />
      </van-popup>

      <van-popup v-model:show="moneyInFlag" round position="bottom">
        <van-picker
            :columns="columnsIn"
            @cancel="moneyInFlag = false"
            @confirm="moneyInConfirm"
        />
      </van-popup>

      <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>
      <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;
}
</style>
