<script setup>
import { getCurrentInstance, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

const base_url = '/sgsafe/EmergencyDrills'
const {
  proxy
} = getCurrentInstance();
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)}`;
}
let title = '新增应急演练计划';

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

/* 获取当前年度和月度 */
const currentYear = new Date().getFullYear()
const currentMonth = new Date().getMonth() + 1

const emergencyDrillPlanForm = ref({
  id: '',
  planName: '',
  planYear: currentYear,
  planMoth: currentMonth,
  planLevel: '',
  drillDeptCode: '',
  drillDeptName: '',
  planFile: guid(),
  drillName: '',
  drillAddress: '',
  publishDate: '',
  leaderName: '',
  joinDeptCode: '',
  joinDeptName: '',
  joinPerson: '',
  drillResult: '',
  drillFile: guid(),
  drillImage: guid(),
  drillEvaluate: guid(),
})

const route = useRoute();
let planInfo = {};
if (route.query.planInfo) {
  planInfo = JSON.parse(route.query.planInfo);
  if (planInfo) {
    title = '修改应急演练计划';
    emergencyDrillPlanForm.value = {
      id: planInfo.id,
      planName: planInfo.planName,
      planYear: planInfo.planYear,
      planMoth: planInfo.planMoth,
      planLevel: planInfo.planLevel,
      drillDeptCode: planInfo.drillDeptCode,
      drillDeptName: planInfo.drillDeptName,
      planFile: planInfo.planFile
    };
  }
}

/* 下拉框 */
const showActionSheet = ref(false);
const planLevelList = [
  { name: '公司级' },
  { name: '分公司级' },
  { name: '车间级' },
  { name: '班组级' }
]
const onSelect = (item) => {
  emergencyDrillPlanForm.value.planLevel = item.name;
  showActionSheet.value = false;
}

const showYearSheet = ref(false)
const yearList = [
  { name: String(currentYear - 2) },
  { name: String(currentYear - 1) },
  { name: String(currentYear) },
  { name: String(currentYear + 1) }
]
const selectYear = (item) => {
  emergencyDrillPlanForm.value.planYear = item.name
  showYearSheet.value = false
}

const showMonthSheet = ref(false)
const monthList = [
  { name: '1' },
  { name: '2' },
  { name: '3' },
  { name: '4' },
  { name: '5' },
  { name: '6' },
  { name: '7' },
  { name: '8' },
  { name: '9' },
  { name: '10' },
  { name: '11' },
  { name: '12' }
]
const selectMonth = (item) => {
  emergencyDrillPlanForm.value.planMoth = item.name
  showMonthSheet.value = false
}

/* 组织树选择 */
const showBottom = ref(false);
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
const handleTableDataUserDeptUpdate = (nodeData) => {
  const selectedDeptCode = nodeData.split('-')[0];
  if (deptInfo.value.includes(selectedDeptCode) && selectedDeptCode !== deptInfo.value) {
    showFailToast('部门选择超出范围');
    return;
  }
  emergencyDrillPlanForm.value.drillDeptCode = nodeData.split('-')[0]
  emergencyDrillPlanForm.value.drillDeptName = nodeData.split('-')[1]
  showBottom.value = false;
};

const deptInfo = ref();
const getDeptInfo = (currentDeptInfo) => {
  deptInfo.value = currentDeptInfo.split('-')[0];
  emergencyDrillPlanForm.value.drillDept = currentDeptInfo;
};

/* 增改演练计划 */
const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  });
  const url = base_url + '/save';
  const params = {
    json: JSON.stringify(emergencyDrillPlanForm.value)
  };
  proxy.$axios.post(url, params).then(res => {
    if (res.data.code === 0) {
      loadingToast.close();
      showSuccessToast('保存成功');
      onClickLeft();
    } else {
      loadingToast.close();
      showFailToast('操作失败!' + res.data.msg);
    }
  });
};

/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan();
};

</script>

<template>

  <div class="page-container">
    <van-sticky>
      <van-nav-bar :title="title">
      </van-nav-bar>
    </van-sticky>
    <div class="scroll-container">
      <van-form @submit="onSubmit">
        <van-field
          v-model="emergencyDrillPlanForm.planName"
          label="计划名称"
          name="planName"
          required
          placeholder="请输入演练计划名称"
          :rules="[{required: true, message: '请输入计划名称'}]"
        />

        <van-field
          readonly
          v-model="emergencyDrillPlanForm.planYear"
          label="年度"
          name="planYear"
          required
          placeholder="请选择年度"
          :rules="[{required: true, message: '请选择年度'}]"
          @click="showYearSheet = true"
        />

        <van-field
          readonly
          v-model="emergencyDrillPlanForm.planMoth"
          label="月度"
          name="planMonth"
          required
          placeholder="请选择月度"
          :rules="[{required: true, message: '请选择月度'}]"
          @click="showMonthSheet = true"
        />

        <van-field
          readonly
          v-model="emergencyDrillPlanForm.planLevel"
          label="层级"
          name="planLevel"
          required
          placeholder="请选择演练计划层级"
          :rules="[{required: true, message: '请输入组织层级'}]"
          @click="showActionSheet = true"
        />

        <van-field
          readonly
          v-model="emergencyDrillPlanForm.drillDept"
          label="演练范围"
          name="drillDept"
          required
          :rules="[{required: true, message: '请输入演练范围'}]"
          @click="showBottom = true"
        />

        <van-field label="附件上传">
          <template #input>
            <AttachmentS3 :f-id="emergencyDrillPlanForm.planFile" />
          </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="showYearSheet"
        :actions="yearList"
        @select="selectYear"
      />

      <van-action-sheet
        v-model:show="showMonthSheet"
        :actions="monthList"
        @select="selectMonth"
      />

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


.button-select {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 20px;
}

</style>
