<script setup>
import { getCurrentInstance, ref } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';

const {
  proxy
} = getCurrentInstance();
const base_url = '/sgsafe/EmergencyDrills';
let title = '修改应急演练记录';

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)}`;
};

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

const emergencyDrillActForm = ref({
  id: '',
  planName: '',
  drillName: '',
  drillAddress: '',
  publishDate: '',
  leaderName: '',
  joinDeptCode: '',
  joinDeptName: '',
  joinPerson: '',
  drillResult: '',
  drillFile: guid(),
  drillImage: guid(),
  drillEvaluate: guid()
});

/* 增改应急演练记录 */
const addEmergencyDrillAct = async (item) => {
  const url = base_url + '/save';
  const params = {
    json: JSON.stringify(emergencyDrillActForm.value)
  };
  proxy.$axios.post(url, params).then(res => {
    if (res.data.code === 0) {
      showSuccessToast('保存成功');
      onClickLeft();
    } else {
      showFailToast('操作失败!' + res.data.msg);
    }
  });
};

/* 组织树选择 */
const showBottom = ref(false);
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

const handleTableDataUserDeptUpdate = (nodeData) => {
  const selectedDeptCode = nodeData.split('-')[0];
  if (deptInfo.value.includes(selectedDeptCode) && selectedDeptCode !== deptInfo.value) {
    showFailToast('部门选择超出范围');
    return;
  }
  emergencyDrillActForm.value.joinDeptCode = nodeData.split('-')[0];
  emergencyDrillActForm.value.joinDeptName = nodeData.split('-')[1];
  showBottom.value = false;
};

const deptInfo = ref();
const getDeptInfo = (currentDeptInfo) => {
  deptInfo.value = currentDeptInfo.split('-')[0];
  if (!emergencyDrillActForm.value.joinDeptCode.includes('D')) {
    emergencyDrillActForm.value.joinDept = currentDeptInfo;
  }
};


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

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

const showDatePicker = ref(false);
const onDatePicker = (value) => {
  const dateArr = value.selectedValues;
  emergencyDrillActForm.value.publishDate = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2];
  showDatePicker.value = false;
};

/* 上次图片组件 */
import AttachmentS3Image from '@/components/AttachmentS3Image.vue';

/* 人员选择 */
import OrganizationalWithLeafUser from '@/components/OrganizationalWithLeafUser.vue';

/* 总指挥 */
const leaderKey = guid();
const PopupDepartmentLeaderNameRef = ref();
const handleDepartmentLeaderName = () => {
  PopupDepartmentLeaderNameRef.value.open();
};

const codeAndDesc = ref([]);
const getDepartmentLeaderName = (userArray) => {
  codeAndDesc.value = [];
  for (let item of userArray) {
    codeAndDesc.value.push(item.userCode + '-' + item.userDesc);
  }
  emergencyDrillActForm.value.leaderName = codeAndDesc.value.join(',');
};
/* 参演人员 */
const joinKey = guid();
const PopupDepartmentJoinPersonRef = ref();
const handleDepartmentJoinPerson = () => {
  PopupDepartmentJoinPersonRef.value.open();
};
const getDepartmentJoinPerson = (userArray) => {
  codeAndDesc.value = [];
  for (let item of userArray) {
    codeAndDesc.value.push(item.userCode + '-' + item.userDesc);
  }
  emergencyDrillActForm.value.joinPerson = codeAndDesc.value.join(',');
};

const selectedUserArr = ref([]);
const selectedUsers = ref([]);
const selectedUser = {
  userCode: '',
  userDesc: ''
};

const createDeptUsers = (row) => {
  if (row.leaderName) {
    selectedUsers.value = [];
    selectedUserArr.value = row.leaderName.split(',');
    for (let item of selectedUserArr.value) {
      //console.log(item);
      selectedUser.userCode = item.split('-')[0];
      selectedUser.userDesc = item.split('-')[1];
      selectedUsers.value.push({ ...selectedUser });
    }
    sessionStorage.setItem(leaderKey, JSON.stringify(selectedUsers.value));
  }
  if (row.joinPerson) {
    selectedUsers.value = [];
    selectedUserArr.value = row.joinPerson.split(',');
    for (let item of selectedUserArr.value) {
      selectedUser.userCode = item.split('-')[0];
      selectedUser.userDesc = item.split('-')[1];
      selectedUsers.value.push({ ...selectedUser });
    }
    sessionStorage.setItem(joinKey, JSON.stringify(selectedUsers.value));
  }
};

const clearDeptUsers = () => {
  if (sessionStorage.getItem(leaderKey)) {
    sessionStorage.removeItem(leaderKey);
  }
  if (sessionStorage.getItem(joinKey)) {
    sessionStorage.removeItem(joinKey);
  }
};

/* 处理修改演练记录 */
const handleUpdate = (info) => {
  title = '修改演练记录';
  emergencyDrillActForm.value = {
    id: info.id,
    planName: info.planName,
    drillName: info.drillName,
    drillAddress: info.drillAddress,
    publishDate: info.publishDate,
    leaderName: info.leaderName,
    joinDeptCode: info.joinDeptCode,
    joinDeptName: info.joinDeptName,
    joinPerson: info.joinPerson,
    drillResult: info.drillResult,
    drillFile: info.drillFile,
    drillImage: info.drillImage,
    drillEvaluate: info.drillEvaluate
  };
  Object.keys(sessionStorage)
    .filter(key => key.length === 32)
    .forEach(key => {
      sessionStorage.removeItem(key);
    });
  createDeptUsers(info);
};

/* 路由接值 */
const route = useRoute();
let actInfo = {};
if (route.query.planInfo) {
  actInfo = JSON.parse(route.query.planInfo);
  console.log(actInfo);
  handleUpdate(actInfo);
}

onBeforeRouteLeave((to, from, next) => {
  clearDeptUsers();
  next();
});

</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="emergencyDrillActForm.drillName"
          label="演练名称"
          name="drillName"
          required
          placeholder="请输入演练名称"
          :rules="[{required: true, message: '请输入演练名称'}]"
        />

        <van-field
          v-model="emergencyDrillActForm.planName"
          label="计划名称"
          name="planName"
          placeholder="请输入计划名称"
        />

        <van-field
          v-model="emergencyDrillActForm.drillAddress"
          label="演练地点"
          name="drillAddress"
          required
          placeholder="请输入演练地点"
          :rules="[{required: true, message: '请输入演练地点'}]"
        />

        <van-field
          v-model="emergencyDrillActForm.publishDate"
          label="演练日期"
          name="publishDate"
          required
          placeholder="请选择演练日期"
          :rules="[{required: true, message: '请输入演练日期'}]"
          @click="showDatePicker = true"
        />

        <van-field
          readonly
          v-model="emergencyDrillActForm.leaderName"
          label="总指挥"
          name="leaderName"
          placeholder="请选择总指挥"
          @click="handleDepartmentLeaderName"
        />

        <OrganizationalWithLeafUser ref="PopupDepartmentLeaderNameRef" @receive-from-child="getDepartmentLeaderName"
                                    :main-key="leaderKey" />

        <van-field
          v-model="emergencyDrillActForm.joinDeptName"
          label="参演部门"
          name="joinDeptName"
          placeholder="请选择参演部门"
          @click="showBottom = true"
          required
          :rules="[{required: true, message: '请输入参演部门'}]"
        />

        <van-field
          readonly
          v-model="emergencyDrillActForm.joinPerson"
          label="参演人员"
          name="joinPerson"
          placeholder="请选择参演人员"
          @click="handleDepartmentJoinPerson"
        />

        <OrganizationalWithLeafUser ref="PopupDepartmentJoinPersonRef" @receive-from-child="getDepartmentJoinPerson"
                                    :main-key="joinKey" />

        <van-field
          v-model="emergencyDrillActForm.drillResult"
          label="演练结果"
          name="drillResult"
          required
          placeholder="请选择演练效果"
          :rules="[{required: true, message: '请输入演练效果'}]"
        >
          <template #input>
            <van-radio-group v-model="emergencyDrillActForm.drillResult" direction="horizontal">
              <van-radio name="0">不合格</van-radio>
              <van-radio name="1">合格</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field label="纸质记录上传">
          <template #input>
            <AttachmentS3 :f-id="emergencyDrillActForm.drillFile" />
          </template>
        </van-field>

        <van-field label="演练图片上传">
          <template #input>
            <AttachmentS3Image :f-id="emergencyDrillActForm.drillImage" />
          </template>
        </van-field>

        <van-field label="效果评价记录">
          <template #input>
            <AttachmentS3 :f-id="emergencyDrillActForm.drillEvaluate" />
          </template>
        </van-field>

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

      <!--   日期选择   -->
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-date-picker @confirm="onDatePicker" @cancel="showDatePicker = false" />
      </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>
    </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>
