<template>
  <div class="h5-container">
    <van-nav-bar title="项目作业管理" @click-left="onClickLeft" />
    <!-- 移除表单提交事件，避免意外触发 -->
    <van-form ref="formRef">
      <!-- 第一部分：基础信息（用readonly替换disabled，移除点击事件） -->
      <span>
        <!-- 项目名称：readonly+移除@click，阻止弹窗触发 -->
        <van-field
          is-link
          :colon="true"
          readonly
          v-model="form.projectName"
          required
          label="项目名称"
          placeholder="选择项目名称"
          :rules="[{ required: true, message: '请选择项目名称' }]"
        />
        <!-- 弹窗保留但无触发源，不影响 -->
        <van-popup v-model:show="showProjectNamePicker" round position="bottom">
          <van-picker :columns="projectNames" @cancel="showProjectNamePicker = false" @confirm="onConfirmProjectName" />
        </van-popup>

        <!-- 作业名称：readonly（纯输入框，仅限制输入） -->
        <van-field
          border
          readonly
          v-model="form.workName"
          label="作业名称"
          :colon="true"
          placeholder="请输入作业名称"
          required
          :rules="[{ required: true, message: '请输入作业名称' }]"
        />

        <!-- 作业内容：readonly（文本域，仅限制输入） -->
        <van-field
          border
          readonly
          v-model="form.workDesc"
          label="作业内容"
          :colon="true"
          placeholder="请输入作业内容"
          required
          :rules="[{ required: true, message: '请输入作业内容' }]"
          type="textarea"
          auto-size
        />
        <van-field
          readonly
          border
          v-model="form.workArea"
          label="作业区域"
          :colon="true"
          placeholder="请输入作业区域"
          required
          :rules="[{ required: true, message: '请输入作业区域' }]"
        />

        <!-- 作业开始时间：readonly+移除@click，阻止时间选择 -->
        <van-field
          v-model="form.timeStart"
          is-link
          readonly
          name="datetime"
          label="作业开始时间"
          :colon="true"
          placeholder="点击选择日期和时间"
          label-width="100"
          required
          :rules="[{ required:true, message: '请选择时间' }]"
        />
        <van-popup
          v-model:show="showDatetimePickerStart"
          position="bottom"
          round
          style="max-height: 50vh;"
        >
          <van-date-picker
            v-if="!dateOrTimeStart"
            v-model="currentDateStart"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onDateConfirmStart"
            @cancel="cancelDatePickerStart"
          >
            <template #confirm><van-button type="primary" @click="onDateConfirmStart">下一步</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelDatePickerStart">取消</van-button></template>
          </van-date-picker>
          <van-time-picker
            v-if="dateOrTimeStart"
            v-model="currentTimeStart"
            title="选择时间"
            :columns-type="['hour', 'minute', 'second']"
            @confirm="onConfirmDatetimeStart"
            @cancel="cancelTimePickerStart"
          >
            <template #confirm><van-button type="primary" @click="onConfirmDatetimeStart">确定</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelTimePickerStart">取消</van-button></template>
          </van-time-picker>
        </van-popup>

        <!-- 计划结束时间：readonly+移除@click -->
        <van-field
          v-model="form.planEnd"
          is-link
          readonly
          name="datetime"
          label="计划结束时间"
          :colon="true"
          placeholder="点击选择日期和时间"
          label-width="100"
          required
          :rules="[{ required:true, message: '请选择时间' }]"
        />
        <van-popup
          v-model:show="showDatetimePickerPlan"
          position="bottom"
          round
          style="max-height: 50vh;"
        >
          <van-date-picker
            v-if="!dateOrTimePlan"
            v-model="currentDatePlan"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onDateConfirmPlan"
            @cancel="cancelDatePickerPlan"
          >
            <template #confirm><van-button type="primary" @click="onDateConfirmPlan">下一步</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelDatePickerPlan">取消</van-button></template>
          </van-date-picker>
          <van-time-picker
            v-if="dateOrTimePlan"
            v-model="currentTimePlan"
            title="选择时间"
            :columns-type="['hour', 'minute', 'second']"
            @confirm="onConfirmDatetimePlan"
            @cancel="cancelTimePickerPlan"
          >
            <template #confirm><van-button type="primary" @click="onConfirmDatetimePlan">确定</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelTimePickerPlan">取消</van-button></template>
          </van-time-picker>
        </van-popup>

        <!-- 特种作业人员：readonly+移除@click，阻止人员选择 -->
        <van-field
          v-if="form.specialPerson"
          readonly
          border
          v-model="form.specialPerson"
          label="特种作业人员"
          :colon="true"
          placeholder="请选择特种作业人员"
          label-width="100"
          required
        />
        <OrganizationalWithLeafUser
          ref="PopupDepartmentSpecialPerson"
          @receive-from-child="getDepartmentSpecialPerson"
          :main-key="specialPersonKey"
          :dept-code="deptCode"
        />

        <!-- 特种作业人员证件：readonly（纯展示标签） -->
        <div v-if="form.specialPerson" v-for="(item,index) in form.specialCard.split(',')" :key="index">
        <van-field
          :colon="true"
          readonly
          :label="`特种作业人员证件${index+1}`"
          label-width="125"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" :f-id="item" />
          </div>
      </span>

      <!-- 第二部分：危险源与安全措施（复选框无readonly，保留disabled） -->
      <span>
        <van-field
          :colon="true"
          readonly
          label="选择危险源及风险"
          label-width="200"
        ></van-field>
        <!-- 说明：复选框无HTML原生readonly属性，只能用disabled（否则可勾选） -->
        <van-checkbox-group v-model="checkboxDangerPoint" shape="square" disabled>
          <van-checkbox v-for="(item,index) in dangerPoints" :name="item" :key="index"
                        style="margin-bottom: 11px;margin-left: 10px;">
            {{ item }}
          </van-checkbox>
        </van-checkbox-group>
        <!-- 其他危险源输入：readonly（限制输入） -->
        <van-field
          v-if="checkboxDangerPoint.includes('其他：')"
          @blur="iconsDangerPoint"
          :colon="false"
          label="   "
          v-model="dangerPoint"
          label-width="10"
          readonly
          style="border-bottom: 1px solid black;margin-left: 40px;margin-right: 20px;"
        ></van-field>

        <van-field
          :colon="true"
          readonly
          label="安全措施"
        ></van-field>
        <!-- 单选框同理，无readonly，保留disabled -->
        <van-checkbox-group v-model="checkboxSafeMeasure" shape="square" disabled>
          <van-checkbox v-for="(item,index) in safeMeasures" :name="item" :key="index"
                        style="margin-bottom: 11px;margin-left: 10px;">
            {{ item }}
          </van-checkbox>
        </van-checkbox-group>
        <!-- 其他安全措施输入：readonly -->
        <van-field
          v-if="checkboxSafeMeasure.includes('其他：')"
          :colon="false"
          v-model="safeMeasure"
          @blur="iconsSafeMeasure"
          label="   "
          label-width="10"
          readonly
          style="border-bottom: 1px solid black;margin-left: 40px;margin-right: 20px;"
        ></van-field>
      </span>

      <!-- 第三部分：签名区域（替换为查看组件，无输入） -->
      <span>
        <van-field
          :colon="true"
          readonly
          label="风险告知人签字"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.leaderSignatureStart" :f-id="form.leaderSignatureStart+'fxgzrqzs'" />
      </span>

      <span> 
        <van-field
          :colon="true"
          readonly
          label="其他作业人员签字"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.otherSignatureStart" :f-id="form.otherSignatureStart+'qtzyrqms'" />
      </span>

      <!-- 第四部分：管理单位相关（单选框用disabled，时间选择用readonly+移除事件） -->
      <span>
        <van-field
          :colon="true"
          readonly
          label="是否需要管理单位签字"
          label-width="200"
        ></van-field>
        <!-- 单选框无readonly，保留disabled -->
        <van-radio-group v-model="form.isManagerSignature" direction="horizontal" disabled>
          <van-radio style="margin-bottom: 11px;margin-left: 20px;" name="是">是</van-radio>
          <van-radio style="margin-bottom: 11px;margin-left: 20px;" name="否">否</van-radio>
        </van-radio-group>

        <!-- 管理单位许可时间：readonly+移除@click -->
        <van-field
          v-if="form.isManagerSignature==='是'"
          v-model="form.ownerTime"
          is-link
          readonly
          name="datetime"
          label="管理单位许可时间"
          :colon="true"
          placeholder="点击选择日期和时间"
          label-width="130"
          required
          :rules="[{ required:true, message: '请选择时间' }]"
        />
        <van-popup
          v-model:show="showDatetimePickerOwner"
          position="bottom"
          round
          style="max-height: 50vh;"
        >
          <van-date-picker
            v-if="!dateOrTimeOwner"
            v-model="currentDateOwner"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onDateConfirmOwner"
            @cancel="cancelDatePickerOwner"
          >
            <template #confirm><van-button type="primary" @click="onDateConfirmOwner">下一步</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelDatePickerOwner">取消</van-button></template>
          </van-date-picker>
          <van-time-picker
            v-if="dateOrTimeOwner"
            v-model="currentTimeOwner"
            title="选择时间"
            :columns-type="['hour', 'minute', 'second']"
            @confirm="onConfirmDatetimeOwner"
            @cancel="cancelTimePickerOwner"
          >
            <template #confirm><van-button type="primary" @click="onConfirmDatetimeOwner">确定</van-button></template>
            <template #cancel><van-button type="danger" @click="cancelTimePickerOwner">取消</van-button></template>
          </van-time-picker>
        </van-popup>

        <van-field
          v-if="form.isManagerSignature==='是'"
          :colon="true"
          readonly
          label="管理单位确认签字"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.isManagerSignature==='是' && form.otherSignatureStart" :f-id="form.ownerSignatureStart+'qtzyrqms'" />

        <van-field
          :colon="true"
          readonly
          label="是否穿戴好劳保护品（拍照）"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" :f-id="form.protectClothing+'protectClothin'" />
      </span>

      <!-- 第五部分：特种防护设备（单选框disabled，类型选择readonly+移除事件） -->
      <span>
        <van-field
          :colon="true"
          readonly
          label="是否需要携带安全防护器具"
          label-width="200"
        ></van-field>
        <van-radio-group v-model="form.isNeedSpecialEq" direction="horizontal" disabled>
          <van-radio style="margin-bottom: 11px;margin-left: 20px;" name="是">是</van-radio>
          <van-radio style="margin-bottom: 11px;margin-left: 20px;" name="否">否</van-radio>
        </van-radio-group>

        <!-- 特种防护器具类型：readonly+移除@click -->
        <van-field
          label-width="125"
          v-if="form.isNeedSpecialEq==='是'"
          is-link
          :colon="true"
          readonly
          v-model="form.specialType"
          required
          label="安全防护器具类型"
          placeholder="选择安全防护器具类型"
          :rules="[{ required: true, message: '请选择安全防护器具类型' }]"
        />
        <van-popup v-if="form.isNeedSpecialEq==='是'" v-model:show="showSpecialTypePicker" round position="bottom">
          <van-picker :columns="specialTypes" @cancel="showSpecialTypePicker = false" @confirm="onConfirmSpecialType" />
        </van-popup>

        <van-field
          v-if="form.isNeedSpecialEq==='是'"
          :colon="true"
          readonly
          label="安全防护器具穿戴情况（拍照）"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.isNeedSpecialEq==='是'" :f-id="form.specialPhoto+'specialPhoto'" />

        <van-field
          :colon="true"
          readonly
          label="作业开始照片（拍照）"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" :f-id="form.startPhoto+'startPhoto'" />
      </span>

      <!-- 第六部分：签退与遗留问题（签名查看，输入框readonly） -->
      <span>
        <van-field
          :colon="true"
          readonly
          label="作业人员签退"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.otherSignature" :f-id="form.otherSignature+'ldseend'" />
      </span>

      <span v-if="false">
        <van-field
          :colon="true"
          readonly
          label="管理方签字"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.ownerSignatureEnd" :f-id="form.ownerSignatureEnd+'glfqze'" />
      </span>

      <span>
        <!-- 遗留问题：readonly -->
        <van-field
          border
          readonly
          v-model="form.otherQuestion"
          label="遗留问题"
          :colon="true"
          placeholder="请输入遗留问题"
          type="textarea"
          auto-size
          required
        />
      </span>

      <span>
        <van-field
          :colon="true"
          readonly
          label="作业负责人签名"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.leaderSignatureEnd" :f-id="form.leaderSignatureEnd+'zyfzrqme'" />
        <van-field
          :colon="true"
          readonly
          label="作业结束照片（拍照）"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" :f-id="form.endPhoto" />
      </span>

      <!-- 第七部分：安全员与项目经理签名（纯展示） -->
      <span v-if="form.workId">
        <van-field
          :colon="true"
          readonly
          label="项目安全员签名"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.safePersonSignature" :f-id="form.safePersonSignature" />
      </span>

      <span v-if="form.workId">
        <van-field
          :colon="true"
          readonly
          label="项目经理签名"
          label-width="200"
        ></van-field>
        <AttachmentS3Image :plus-icon="false" :readonly="true" v-if="form.managerSignature" :f-id="form.managerSignature" />
      </span>
      <div style="height: 10px;"></div>
    </van-form>
  </div>
</template>

<script setup>
// 脚本部分完全不变（仅调整模板控件属性，逻辑无需修改）
import { getUUID } from '@/axios/crypto.js';
import { ref, reactive, onMounted, getCurrentInstance, nextTick, toRaw } from 'vue';
import { closeToast, Dialog, showDialog, showFailToast, showLoadingToast, showSuccessToast, showToast } from 'vant';
import AttachmentS3Image from '@/components/AttachmentS3ImageSY.vue';
import AttachmentS3 from '@/components/AttachmentS3.vue';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
import OrganizationalWithLeafUser from '@/components/OrganizationalWithLeafUserSpecialWork.vue';
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import HandwrittenSignatureLook from '@/components/HandwrittenSignatureLook.vue';

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};

const deptCode = ref('');
const dangerPoints = ref([]);
const safeMeasures = ref([]);
onMounted(() => {
  
  deptCode.value = JSON.parse(localStorage.getItem('dept'))[0].deptCode;
  getProjectNames();

  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth();
  minDate.value = new Date(currentYear - 20, 0, 1);
  maxDate.value = new Date(currentYear + 2, currentMonth, 28);

  resetDatetimeStart();
  resetDatetimePlan();
  console.log('路由传值', proxy.$route.query);
  nextTick(() => {
    if (proxy.$route.query.id) {
      form.value = proxy.$route.query;
      var url = '/sgsafe/ProjectWork/queryById';
      var param = { id: form.value.id };
      proxy.$axios.get(url, param).then(response => {
        if (response.data.code === 0) {
          form.value = response.data.data;
          console.log('数据', response.data.data);
          dangerPoints.value = form.value.dangerPoint.split(',');
          safeMeasures.value = form.value.safeMeasure.split(',');
          checkboxDangerPoint.value = form.value.dangerPoint ? form.value.dangerPoint.split(',') : [];
          checkboxSafeMeasure.value = form.value.safeMeasure ? form.value.safeMeasure.split(',') : [];
        } else {
          showToast({ message: '数据加载失败！' + response.data.msg });
        }
      });
    }
  });

});

const getTimeFormatter = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const formRef = ref(null);
const qvxiao = () => {
  showToast({ type: 'fail', message: '操作取消！' });
  onClickLeft();
};

import { workflowSubmit, workflowCancel } from '@/tools/workflow.js';

const flowId = ref('ProjectSingnatureQun');
const jsons = ref([]);
const baocun = () => {
  if (form.value.id !== '') {
    form.value.dangerPoint = checkboxDangerPoint.value.toString();
    form.value.safeMeasure = checkboxSafeMeasure.value.toString();
  }
  if (form.value.stepNumber === 10) form.value.overTask = '是';

  var url = 'sgsafe/ProjectWork/save';
  var param = { json: JSON.stringify(form.value) };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showSuccessToast('保存成功！');
      form.value = response.data.data;
      form.value.stepNumber++;
      if (form.value.stepNumber === 11 || form.value.stepNumber === 7) onClickLeft();
      if (form.value.stepNumber === 4) {
        jsons.value = { singnatrueQunPerson: form.value.chaoSongPerson };
        const processedData = {};
        for (const key in jsons.value) {
          if (jsons.value.hasOwnProperty(key)) {
            const replacedValue = jsons.value[key].replace(/,/g, ';');
            const parts = replacedValue.split(';');
            processedData[key] = parts.map(part => `U_${part.trim()}`).join(';');
          }
        }
        const b = { singnatrueQunPerson: processedData.singnatrueQunPerson, id: form.value.id };
        sessionStorage.setItem('variables', JSON.stringify(toRaw(b)));

        workflowSubmit(
          flowId.value,
          '风险告知人抄送',
          '初始化提交',
          sessionStorage.getItem('variables'),
          form.workId2,
          form.trackId2
        ).then((result) => {
          if (result.status === 'success') {
            var url = 'sgsafe/ProjectWork/saveProcessInfo2';
            var process = { id: form.value.id, workId: result.workId, trackId: result.trackId };
            var param = { json: JSON.stringify(process) };
            proxy.$axios.post(url, param).then(response => {
              if (response.data.code === 0) {
                form.value = response.data.data;
                showToast({ type: 'success', message: '' });
                sendMessage(form.value.chaoSongPerson, '风险告知人抄送', 'projectManage/todo_detail/index2?id=' + form.value.id);
              }
            });
          } else {
            showToast({ type: 'error', message: '提交审批失败，' + result.msg });
          }
        }).catch((error) => {
          showToast({ type: 'error', message: '提交过程出错：' + (error.message || '未知错误') });
        });
      }
    } else {
      showFailToast('操作失败！');
    }
  });
};

const sendMessage = (id, userId, content, routing) => {
  var url = 'sgsafe/ProjectWork/sendMessageProjectWork2';
  var param = { params: JSON.stringify({ id, userId, content, routing }) };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) showSuccessToast('发送成功');
  });
};

const guid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};

const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId')
});

const projectNames = ref([]);
const showProjectNamePicker = ref(false);
const onConfirmProjectName = ({ selectedOptions }) => {
  showProjectNamePicker.value = false;
  form.value.projectId = selectedOptions[0].value;
  form.value.projectName = selectedOptions[0].text;
  form.value.projectLeader = selectedOptions[0].projectLeader;
  form.value.projectLeaderCode = selectedOptions[0].projectLeaderCode;
  form.value.projectSafePerson = selectedOptions[0].projectSafePerson;
  form.value.projectSafePersonCode = selectedOptions[0].projectSafePersonCode;
};
const getProjectNames = () => {
  return new Promise((resolve) => {
    var url = '/sgsafe/Project/queryProjectNames';
    var param = {};
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code === 0) {
        let a = response.data.data;
        a.forEach(e => {
          projectNames.value.push({
            value: e.id,
            text: e.projectName,
            projectLeader: e.projectLeader,
            projectLeaderCode: e.projectLeaderCode,
            projectSafePerson: e.projectSafePerson,
            projectSafePersonCode: e.projectSafePersonCode
          });
        });
      } else {
        showToast({ type: 'fail', message: '项目列表加载失败' + response.data.msg });
      }
      resolve();
    });
  });
};

const form = ref({
  id: '',
  projectName: '',
  projectId: '',
  projectLeader: '',
  projectLeaderCode: '',
  workName: '',
  workDesc: '',
  timeStart: '',
  planEnd: '',
  realEnd: '',
  specialPerson: '',
  specialPersonCode: '',
  specialCard: '',
  dangerPoint: '',
  safeMeasure: '',
  ownerTime: '',
  ownerSignatureStart: '',
  protectClothing: '',
  specialType: '',
  specialPhoto: '',
  startPhoto: '',
  endPhoto: '',
  otherSignatureEnd: '',
  ownerSignatureEnd: '',
  leaderSignatureEnd: '',
  otherQuestion: '',
  projectSafePerson: '',
  projectSafePersonCode: '',
  isManagerSignature: '否',
  isNeedSpecialEq: '否'
});

const minDate = ref();
const maxDate = ref();

const showDatetimePickerStart = ref(false);
const currentDateStart = ref();
const currentTimeStart = ref();
const dateOrTimeStart = ref(false);
const onDateConfirmStart = () => {
  dateOrTimeStart.value = true;
};
const resetDatetimeStart = () => {
  dateOrTimeStart.value = false;
  if (form.value.timeStart) {
    const dt = new Date(form.value.timeStart);
    currentDateStart.value = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
    currentTimeStart.value = [
      String(dt.getHours()).padStart(2, '0'),
      String(dt.getMinutes()).padStart(2, '0'),
      String(dt.getSeconds()).padStart(2, '0')
    ];
  } else {
    const now = new Date();
    currentDateStart.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
    currentTimeStart.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};
const onConfirmDatetimeStart = () => {
  const year = currentDateStart.value[0];
  const month = currentDateStart.value[1].toString().padStart(2, '0');
  const day = currentDateStart.value[2].toString().padStart(2, '0');
  const hours = currentTimeStart.value[0].toString().padStart(2, '0');
  const minutes = currentTimeStart.value[1].toString().padStart(2, '0');
  const seconds = currentTimeStart.value[2].toString().padStart(2, '0');
  form.value.timeStart = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePickerStart.value = false;
  dateOrTimeStart.value = false;
};
const cancelDatePickerStart = () => {
  showDatetimePickerStart.value = false;
  resetDatetimeStart();
};
const cancelTimePickerStart = () => {
  resetDatetimeStart();
};

const showDatetimePickerPlan = ref(false);
const currentDatePlan = ref();
const currentTimePlan = ref();
const dateOrTimePlan = ref(false);
const onDateConfirmPlan = () => {
  dateOrTimePlan.value = true;
};
const resetDatetimePlan = () => {
  dateOrTimePlan.value = false;
  if (form.value.planEnd) {
    const dt = new Date(form.value.planEnd);
    currentDatePlan.value = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
    currentTimePlan.value = [
      String(dt.getHours()).padStart(2, '0'),
      String(dt.getMinutes()).padStart(2, '0'),
      String(dt.getSeconds()).padStart(2, '0')
    ];
  } else {
    const now = new Date();
    currentDatePlan.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
    currentTimePlan.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};
const onConfirmDatetimePlan = () => {
  const year = currentDatePlan.value[0];
  const month = currentDatePlan.value[1].toString().padStart(2, '0');
  const day = currentDatePlan.value[2].toString().padStart(2, '0');
  const hours = currentTimePlan.value[0].toString().padStart(2, '0');
  const minutes = currentTimePlan.value[1].toString().padStart(2, '0');
  const seconds = currentTimePlan.value[2].toString().padStart(2, '0');
  form.value.planEnd = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePickerPlan.value = false;
  dateOrTimePlan.value = false;
};
const cancelDatePickerPlan = () => {
  showDatetimePickerPlan.value = false;
  resetDatetimePlan();
};
const cancelTimePickerPlan = () => {
  resetDatetimePlan();
};

const specialPersonKey = guid();
const PopupDepartmentSpecialPerson = ref();
const handleDepartmentSpecialPerson = () => {
  PopupDepartmentSpecialPerson.value.open();
};
const codeAndDescSpecialPerson = ref([]);
const getDepartmentSpecialPerson = (items) => {
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDescSpecialPerson.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.specialPersonCode = codeList.join(',');
  var url = '/sgsafe/Project/querySpecialCardFileByUserCode';
  var param = { userCode: form.value.specialPersonCode };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) form.value.specialCard = response.data.data.cardFile;
    else showToast({ message: '证件加载失败！' + response.data.message });
  });
  form.value.specialPerson = descList.join(',');
};

const checkboxDangerPoint = ref([]);
const checkboxSafeMeasure = ref([]);
const ownerSignFlag = ref('false');

const showDatetimePickerOwner = ref(false);
const currentDateOwner = ref();
const currentTimeOwner = ref();
const dateOrTimeOwner = ref(false);
const onDateConfirmOwner = () => {
  dateOrTimeOwner.value = true;
};
const resetDatetimeOwner = () => {
  dateOrTimeOwner.value = false;
  if (form.value.ownerTime) {
    const dt = new Date(form.value.ownerTime);
    currentDateOwner.value = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
    currentTimeOwner.value = [
      String(dt.getHours()).padStart(2, '0'),
      String(dt.getMinutes()).padStart(2, '0'),
      String(dt.getSeconds()).padStart(2, '0')
    ];
  } else {
    const now = new Date();
    currentDateOwner.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
    currentTimeOwner.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};
const onConfirmDatetimeOwner = () => {
  const year = currentDateOwner.value[0];
  const month = currentDateOwner.value[1].toString().padStart(2, '0');
  const day = currentDateOwner.value[2].toString().padStart(2, '0');
  const hours = currentTimeOwner.value[0].toString().padStart(2, '0');
  const minutes = currentTimeOwner.value[1].toString().padStart(2, '0');
  const seconds = currentTimeOwner.value[2].toString().padStart(2, '0');
  form.value.ownerTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePickerOwner.value = false;
  dateOrTimeOwner.value = false;
};
const cancelDatePickerOwner = () => {
  showDatetimePickerOwner.value = false;
  resetDatetimeOwner();
};
const cancelTimePickerOwner = () => {
  resetDatetimeOwner();
};

const specialToolFlag = ref('false');
const specialTypes = ref([
  { value: '头部护具类', text: '头部护具类' },
  { value: '呼吸护具类', text: '呼吸护具类' },
  { value: '眼（面）护具类', text: '眼（面）护具类' },
  { value: '防护服类', text: '防护服类' },
  { value: '防护鞋类', text: '防护鞋类' },
  { value: '防坠落护具类', text: '防坠落护具类' }
]);
const showSpecialTypePicker = ref(false);
const onConfirmSpecialType = ({ selectedOptions }) => {
  showSpecialTypePicker.value = false;
  form.value.specialType = selectedOptions[0].text;
};

const nextStepFlag = ref(1);
const sendMessageSignature = () => {
  var url = '/sgsafe/ProjectWork/sendMessageSignature';
  var param = { params: form.value.id };
  if (form.value) {
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code === 0) showSuccessToast('成功抄送');
      else showFailToast('操作失败' + response.data.msg);
    });
  }
};

const safeMeasure = ref(null);
const dangerPoint = ref(null);
const iconsSafeMeasure = () => {
  if (safeMeasure.value) checkboxSafeMeasure.value.push(safeMeasure.value);
};
const iconsDangerPoint = () => {
  if (dangerPoint.value) checkboxDangerPoint.value.push(dangerPoint.value);
};

const onDateConfirmPlanPre = () => {
  form.value.stepNumber--;
};
const onClickSignatureFxgzrFlag = ref('false');
const onClickSignatureFxgzr = () => {
  onClickSignatureFxgzrFlag.value = 'true';
};
const onClickSignatureQtzyrFlag = ref('false');
const onClickSignatureQtzyr = () => {
  onClickSignatureQtzyrFlag.value = 'true';
};
const onClickSignatureGldwqrFlag = ref('false');
const onClickSignatureGldwqr = () => {
  onClickSignatureGldwqrFlag.value = 'true';
};
const onClickSignatureZyryqtFlag = ref('false');
const onClickSignatureZyryqt = () => {
  onClickSignatureZyryqtFlag.value = 'true';
};
const onClickSignatureGldwqtFlag = ref('false');
const onClickSignatureGldwqt = () => {
  onClickSignatureGldwqtFlag.value = 'true';
};
const onClickSignatureZyfzrqtFlag = ref('false');
const onClickSignatureZyfzrqt = () => {
  onClickSignatureZyfzrqtFlag.value = 'true';
};
const resetFlagFlase = () => {
  onClickSignatureFxgzrFlag.value = 'false';
  onClickSignatureQtzyrFlag.value = 'false';
  onClickSignatureGldwqrFlag.value = 'false';
  onClickSignatureZyryqtFlag.value = 'false';
  onClickSignatureGldwqtFlag.value = 'false';
};
</script>

<style scoped>
.h5-container {
  width: 100%;
  box-sizing: border-box;
  height: 100vh;
  background-color: white;
  padding: 10px;
  padding-bottom: 20px;
}

.radio-group {
  display: flex;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  margin: 10px 0;
  gap: 10px;
}

.radio-item {
  padding: 8px 12px;
  border: 1px solid #222;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.radio-item.active {
  background-color: #4285f4;
  color: white;
  border-color: #4285f4;
}
</style>