<template>
  <div class="h5-container">
    <van-nav-bar title="项目作业管理" @click-left="onClickLeft">
    </van-nav-bar>
    <van-button v-if="form.stepNumber!==1" type="primary" @click="onDateConfirmPlanPre">上一步</van-button>
    <van-form @submit="baocun" ref="formRef">
      <span v-if="form.stepNumber===1">
        <van-field is-link :colon="true" readonly v-model="form.projectName" required label="项目名称"
                   placeholder="选择项目名称"
                   @click="showProjectNamePicker = true" :rules="[{ required: true, message: '请选择项目名称' }]" />
      <van-popup v-model:show="showProjectNamePicker" round position="bottom">
        <van-picker :columns="projectNames" @cancel="showProjectNamePicker = false" @confirm="onConfirmProjectName" />
      </van-popup>
        <template v-if="form.stepNumber===1"></template>
      <van-field
        border
        v-model="form.workName"
        label="作业名称"
        :colon="true"
        placeholder="请输入作业名称"
        required
        :rules="[{ required: true, message: '请输入作业名称' }]"
      />

      <van-field
        border
        v-model="form.workDesc"
        label="作业内容"
        :colon="true"
        placeholder="请输入作业内容"
        required
        :rules="[{ required: true, message: '请输入作业内容' }]"
        type="textarea"
        auto-size
      />
      <van-field
        border
        v-model="form.workArea"
        label="作业区域"
        :colon="true"
        placeholder="请输入作业区域"
        required
        :rules="[{ required: true, message: '请输入作业区域' }]"
      />

      <van-field
        v-model="form.timeStart"
        is-link
        readonly
        name="datetime"
        label="作业开始时间"
        :colon="true"
        placeholder="点击选择日期和时间"
        @click="showDatetimePickerStart = true"
        required
        label-width="100"
        :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 class="text-only-next-btn" @click="onDateConfirmStart">下一步</van-button>
          </template>
          <template #cancel>
            <van-button class="text-only-next-btn" @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 class="text-only-next-btn" @click="onConfirmDatetimeStart">确定</van-button>
          </template>
          <template #cancel>
            <van-button class="text-only-next-btn" @click="cancelTimePickerStart">取消</van-button>
          </template>
        </van-time-picker>
      </van-popup>

      <van-field
        v-model="form.planEnd"
        is-link
        readonly
        name="datetime"
        label="计划结束时间"
        :colon="true"
        placeholder="点击选择日期和时间"
        @click="showDatetimePickerPlan = true"
        required
        label-width="100"
        :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 class="text-only-next-btn" @click="onDateConfirmPlan">下一步</van-button>
          </template>
          <template #cancel>
            <van-button class="text-only-next-btn" @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 class="text-only-next-btn" @click="onConfirmDatetimePlan">确定</van-button>
          </template>
          <template #cancel>
            <van-button class="text-only-next-btn" @click="cancelTimePickerPlan">取消</van-button>
          </template>
        </van-time-picker>
      </van-popup>
      

      <van-field
        readonly
        border
        v-model="form.specialPerson"
        label="特种作业人员"
        :colon="true"
        placeholder="请选择特种作业人员"
        label-width="100"
        @click="handleDepartmentSpecialPerson"
      />
      <OrganizationalWithLeafUser ref="PopupDepartmentSpecialPerson" @receive-from-child="getDepartmentSpecialPerson"
                                  :main-key="specialPersonKey" :dept-code="deptCode" />
        
        <van-field v-if="isShowTypeAndProject" is-link :colon="true" readonly v-model="workTypeOne" required
                   label="作业类别"
                   placeholder="选择作业类别"
                   @click="showProjectNamePickerWorkType = true" />
      <van-popup v-if="isShowTypeAndProject" v-model:show="showProjectNamePickerWorkType" round position="bottom">
        <van-picker :columns="workTypeSelect" @cancel="showProjectNamePickerWorkType = false"
                    @confirm="onConfirmProjectNameWorkType" />
      </van-popup>
        
        <van-field v-if="isShowTypeAndProject2" is-link :colon="true" readonly v-model="workProjectOne" required
                   label="操作项目"
                   placeholder="选择操作项目"
                   @click="showProjectNamePickerWorkProject = true" />
      <van-popup v-if="isShowTypeAndProject2" v-model:show="showProjectNamePickerWorkProject" round position="bottom">
        <van-picker :columns="workProjectSelect" @cancel="showProjectNamePickerWorkProject = false"
                    @confirm="onConfirmProjectNameWorkProject" />
      </van-popup>

        <div v-for="(item,index) in cardArray" :key="index">
          <van-field
            :colon="true"
            readonly
            :label="`特种作业人员证件${index+1}`"
            label-width="125"
          ></van-field>
          <AttachmentS3Image ref="popupSpecialCard" :f-id="item" />
        </div>
      </span>

      <span v-if="form.stepNumber===2">
        <van-field
          :colon="true"
          readonly
          label="选择危险源及风险"
          label-width="200"
        ></van-field>
      <van-checkbox-group v-model="checkboxDangerPoint" shape="square">
        <van-checkbox v-for="(item,index) in dangerPoints" :name="item" style="margin-bottom: 11px;margin-left: 10px;">
          {{ item }}
        </van-checkbox>
        
      </van-checkbox-group>
        <van-field v-if="checkboxDangerPoint.includes('其他：')"
                   @blur="iconsDangerPoint"
                   :colon="false"
                   label="   "
                   v-model="dangerPoint"
                   label-width="10"
                   style="border-bottom: 1px solid black;margin-left: 40px;margin-right: 20px;"
        ></van-field>
        
      <van-field
        :colon="true"
        readonly
        label="安全措施"
      ></van-field>
      <van-checkbox-group v-model="checkboxSafeMeasure" shape="square">
        <van-checkbox v-for="(item,index) in safeMeasures" :name="item" style="margin-bottom: 11px;margin-left: 10px;">
          {{ item }}
        </van-checkbox>
        
      </van-checkbox-group>
        <van-field v-if="checkboxSafeMeasure.includes('其他：')"
                   :colon="false"
                   v-model="safeMeasure"
                   @blur="iconsSafeMeasure"
                   label="   "
                   label-width="10"
                   style="border-bottom: 1px solid black;margin-left: 40px;margin-right: 20px;"
        ></van-field>
      </span>

      <span v-if="form.stepNumber===3">
<!--        在这里签完字抄送？到这一步再抄送-->
        <van-field
          :colon="true"
          readonly
          label="风险告知人签字"
          label-width="200"
        ></van-field>
      </span>
      <!--      <van-button v-if="nextStepFlag===3" type="primary" @click="onClickSignatureFxgzr">点击签名</van-button>-->
      <!--      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="onClickSignatureFxgzrFlag==='true'" :f-id="form.leaderSignatureStart+'fxgzrqzs'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="form.stepNumber===3"
                            :f-id="form.leaderSignatureStart+'fxgzrqzs'"></HandwrittenSignature>
      <!--      <HandwrittenSignatureLook ref="childRef1"  v-if="nextStepFlag===3" :f-id="form.leaderSignatureStart+'fxgzrqms'" :update-flag="bhFlag" :qm-flags="false"></HandwrittenSignatureLook>-->
      <span v-if="form.stepNumber===4"> 
         <van-field
           :colon="true"
           readonly
           label="其他作业人员签字"
           label-width="200"
         ></van-field>
      </span>
      <!--      <van-button v-if="nextStepFlag===4" type="primary" @click="onClickSignatureQtzyr">点击签名</van-button>-->
      <!--      <HandwrittenSignature v-if="onClickSignatureQtzyrFlag==='true'" :f-id="form.otherSignatureStart+'qtzyrqms'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="form.stepNumber===4"
                            :f-id="form.otherSignatureStart+'qtzyrqms'"></HandwrittenSignature>
      <!--      <HandwrittenSignatureLook  v-if="nextStepFlag===4" :f-id="form.otherSignatureStart+'qtzyrqms'" :qm-flags="false"></HandwrittenSignatureLook>-->
      <span v-if="form.stepNumber===5">
  <van-field
    :colon="true"
    readonly
    label="是否需要管理单位签字"
    label-width="200"
  ></van-field>
      <van-radio-group v-model="form.isManagerSignature" direction="horizontal">
        <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>

      <van-field
        v-if="form.isManagerSignature==='是'"
        v-model="form.ownerTime"
        is-link
        readonly
        name="datetime"
        label="管理单位许可时间"
        :colon="true"
        placeholder="点击选择日期和时间"
        label-width="130"
        @click="showDatetimePickerOwner = true"
        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
              @click="onDateConfirmOwner"
              class="text-only-next-btn"
            >
    下一步
  </van-button>
          </template>
          <template #cancel>
            <van-button class="text-only-next-btn" @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>
        <!--        <van-button v-if="nextStepFlag===5 && ownerSignFlag==='true'" type="primary" @click="onClickSignatureGldwqr">点击签名</van-button>-->
        <!--      <HandwrittenSignature v-if="onClickSignatureGldwqrFlag==='true'" :f-id="form.ownerSignatureStart+'qtzyrqms'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="form.isManagerSignature==='是'"
                            :f-id="form.ownerSignatureStart+'qtzyrqms'"
                            @resetQMFlag="resetFlagFlase"></HandwrittenSignature>
        <!--<HandwrittenSignatureLook  v-if="nextStepFlag===5" :f-id="form.ownerSignatureStart+'qtzyrqms'" :qm-flags="false"></HandwrittenSignatureLook>-->
      <van-field
        :colon="true"
        readonly
        label="是否穿戴好劳保护品（拍照）"
        label-width="200"
      ></van-field>
      <AttachmentS3Image :f-id="form.protectClothing+'protectClothin'" />
</span>

      <span v-if="form.stepNumber===6">
  <van-field
    :colon="true"
    readonly
    label="是否需要携带安全防护器具"
    label-width="200"
  ></van-field>
      <van-radio-group v-model="form.isNeedSpecialEq" direction="horizontal">
        <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>

      <van-field label-width="125" v-if="form.isNeedSpecialEq==='是'" is-link :colon="true" readonly
                 v-model="form.specialType" required label="安全防护器具类型" placeholder="选择安全防护器具类型"
                 @click="showSpecialTypePicker = true"
                 :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 v-if="form.isNeedSpecialEq==='是'" :f-id="form.specialPhoto+'specialPhoto'" />

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

      <span v-if="form.stepNumber===7">
        <van-field
          :colon="true"
          readonly
          label="作业人员签退"
          label-width="200"
        ></van-field>
        <!--        <van-button v-if="nextStepFlag===7" type="primary" @click="onClickSignatureZyryqt">点击签名</van-button>-->
        <!--      <HandwrittenSignature v-if="onClickSignatureZyryqtFlag==='true'" :f-id="form.otherSignatureEnd+'ldseend'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="form.stepNumber===7 && form.otherSignature"
                            :f-id="form.otherSignature+'ldseend'"
                            @resetQMFlag="resetFlagFlase"></HandwrittenSignature>
        <!--<HandwrittenSignatureLook  v-if="nextStepFlag===7" :f-id="form.otherSignatureEnd+'ldseend'" :qm-flags="false"></HandwrittenSignatureLook>-->
      </span>

      <span v-if="form.stepNumber===8">
        <van-field
          :colon="true"
          readonly
          label="管理方签字"
          label-width="200"
        ></van-field>
        <!--        <van-button v-if="nextStepFlag===8" type="primary" @click="onClickSignatureGldwqt">点击签名</van-button>-->
        <!--      <HandwrittenSignature v-if="onClickSignatureGldwqtFlag==='true'" :f-id="form.ownerSignatureEnd+'glfqze'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height:50vh" v-if="form.stepNumber===8"
                            :f-id="form.ownerSignatureEnd+'glfqze'"
                            @resetQMFlag="resetFlagFlase"></HandwrittenSignature>
        <!--<HandwrittenSignatureLook  v-if="nextStepFlag===8" :f-id="form.ownerSignatureEnd+'glfqze'" :qm-flags="false"></HandwrittenSignatureLook>-->
        
      </span>


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

      <span v-if="form.stepNumber===10">
        <van-field
          :colon="true"
          readonly
          label="作业负责人签名"
          label-width="200"
        ></van-field>
        <!--        <van-button v-if="nextStepFlag===10" type="primary" @click="onClickSignatureZyfzrqt">点击签名</van-button>-->
        <!--      <HandwrittenSignature v-if="onClickSignatureZyfzrqtFlag==='true'" :f-id="form.leaderSignatureEnd+'zyfzrqme'" @resetQMFlag="resetFlagFlase"></HandwrittenSignature>-->
      <HandwrittenSignature style="width: 100%;height: 50vh" v-if="form.stepNumber===10"
                            :f-id="form.leaderSignatureEnd+'zyfzrqme'"
                            @resetQMFlag="resetFlagFlase"></HandwrittenSignature>
        <!--<HandwrittenSignatureLook  v-if="nextStepFlag===10" :f-id="form.leaderSignatureEnd+'zyfzrqme'" :qm-flags="false"></HandwrittenSignatureLook>-->
        
      </span>

      <span v-if="form.workId">
        <van-field
          :colon="true"
          readonly
          label="项目安全员签名"
          label-width="200"
        ></van-field>
      </span>

      <span v-if="form.workId">
        <van-field
          :colon="true"
          readonly
          label="项目经理签名"
          label-width="200"
        ></van-field>
      </span>


      <van-button v-if="false" block round type="warning" @click.stop="temporaryStorageSubmit"
                  style="margin-bottom: 5px;">
        暂存
      </van-button>
      <van-button v-if="form.stepNumber===10" block round type="primary" native-type="submit"
                  style="margin-bottom: 5px;">
        完成
      </van-button>
      <van-button v-else-if="form.stepNumber===6" block round type="primary" native-type="submit"
                  style="margin-bottom: 5px;">
        开始作业
      </van-button>
      <van-button v-else block round type="primary" native-type="submit" style="margin-bottom: 5px;">
        下一步
      </van-button>
      <van-button block round plain type="default" @click="qvxiao">
        取消
      </van-button>
      <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 { wxReady, requestSignature } from '@/router/initWxSdk.js';

const { proxy } = getCurrentInstance();

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

const deptCode = ref('');
const dangerPoints = ref([]);
const safeMeasures = ref([]);
onMounted(async () => {
  //遍历危险源
  let dangerPointsString = '电源→触电；煤气→中毒、窒息；高温→灼烫；粉尘→其他伤害（尘肺）；高空坠物、交叉作业→物体打击；高处作业、登高作业→高处坠落；设备运转、动作→机械伤害；吊装作业→起重伤害；油污、光线昏暗→其他伤害（摔伤）；噪音→其他伤害（听力受损）；交通→车辆伤害；重物搬运→其他伤害（砸伤、扭伤）；其他：';
  let safeMeasuresString = '安全措施：严格执行停电挂牌制度作业前先断电、经验电确认没电之后再作业；人员全部撤离并还牌之后、方可送电；两人及以上进入现场、必须佩戴煤气报警仪、按照煤气区域作业操作规程进行作业、站在上风口、掌握逆风而逃原则、监护到位、煤气浓度高于160ppm时应立即撤离；带好防尘口罩；防护栏杆牢固、合理站位、系好安全带、安全带悬挂点要正确选择、高挂抵用；观察来往车辆、避让车辆、严谨跨越栏杆；遵守停送电挂牌及现场作业“八不干”、上下工序交叉作业时要停止作业、确保安全条件下进行作业、监护到位；携带应急灯或者头灯、合理放置警示灯、增加临时照明设施；合理站位、可靠切断能量源、防止设备误动作、设备动作必须由操作工执行、设备动作时禁止靠近、坑洞区域临边作业、合理站位、拉安全绳、较滑区域铺填防滑物品；落差2米以上使用安全带；戴好耳塞；注意作业中的行车及其起重设备禁止在行车及起重设备落物费减半景区与停留和行走；其他：';
  dangerPoints.value = dangerPointsString.split('；');
  safeMeasures.value = safeMeasuresString.split('；');
  //图片
  // form.value.specialCard = getUUID();
  form.value.protectClothing = getUUID();
  form.value.specialPhoto = getUUID();
  form.value.startPhoto = getUUID();
  form.value.endPhoto = getUUID();
  //签名
  form.value.leaderSignatureStart = getUUID();
  form.value.otherSignatureStart = getUUID();
  form.value.ownerSignatureStart = getUUID();
  form.value.leaderSignatureEnd = getUUID();
  form.value.otherSignature = getUUID();
  form.value.ownerSignatureEnd = getUUID();

  deptCode.value = JSON.parse(localStorage.getItem('dept'))[0].deptCode;
  //执行查询所有项目的方法
  await getProjectNames();
  /**初始化时间**/
    // 更智能的日期范围设置
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth();

  // 设置更合理的动态范围
  minDate.value = new Date(currentYear - 20, 0, 1); // 20年前
  maxDate.value = new Date(currentYear + 2, currentMonth, 28); // 2年后，日期固定为28号避免2月问题

  form.value.timeStart = getTimeFormatter(new Date());
  form.value.planEnd = getTimeFormatter(new Date());
  form.value.ownerTime = getTimeFormatter(new Date());

  // 添加日期时间选择器初始化
  resetDatetimeStart();
  resetDatetimePlan();

});

const getTimeFormatter = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需加 1
  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}`;
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};


const formRef = ref(null);
const qvxiao = () => {

  showToast({
    type: 'fail',
    message: '操作取消！'
  });
  onClickLeft();
};

//提交审批流程
import { workflowSubmit, workflowCancel } from '@/tools/workflow.js';
import HandwrittenSignature from '@/components/HandwrittenSignature4.vue';
import HandwrittenSignatureLook from '@/components/HandwrittenSignatureLook.vue';

const flowId = ref('');
const jsons = ref([]);
flowId.value = 'ProjectSingnatureQun';
const baocun = () => {
  console.log('Flag保存的参数', onClickSignatureFxgzrFlag.value);
  console.log('Nihao ', form.value.stepNumber, form.value.stepNumber === 10);

  if (form.value.stepNumber === 1) {
    form.value.specialCard = cardArray.value.join(',');
    form.value.updateModel = '0';
  }
  if (form.value.stepNumber === 6) {
    form.value.workStatus = '作业中';
    form.value.realStart = new Date();
  } else if (form.value.stepNumber === 10) {
    form.value.workStatus = '作业结束';
  } else {
    form.value.workStatus = '作业起草';
  }
  if (form.value.id !== '') {
    form.value.dangerPoint = checkboxDangerPoint.value.toString();
    form.value.safeMeasure = checkboxSafeMeasure.value.toString();
    if (form.value.dangerPoint === '' || form.value.safeMeasure === '') {
      showToast({
        type: 'fail',
        message: '请选择危险点与安全措施！'
      });
      return;
    }
  }

  console.log('保存的参数', form.value);
  // 原有保存逻辑保持不变
  var url = 'sgsafe/ProjectWork/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      console.log('保存成功后呢', form.value);
      showToast({
        type: 'success',
        message: '保存成功！'
      });
      form.value = response.data.data;
      localStorage.setItem('chaosongPerson', JSON.stringify(form.value.chaoSongPerson))
      form.value.stepNumber++;
      if (form.value.stepNumber === 11 || form.value.stepNumber === 7) {
        // nextStepFlag.value = 0;
        onClickLeft();
      }
      if (form.value.stepNumber === 4) {

        jsons.value = {
          singnatrueQunPerson: form.value.chaoSongPerson
        };

        // 处理函数
        function processValue(value) {
          // 将逗号替换为分号
          const replacedValue = value.replace(/,/g, ';');
          // 分割值
          const parts = replacedValue.split(';');
          // 每个部分前加上 U_
          const processedParts = parts.map(part => `U_${part.trim()}`);
          // 重新组合
          return processedParts.join(';');
        }

        // 处理整个对象
        const processedData = {};
        for (const key in jsons.value) {
          if (jsons.value.hasOwnProperty(key)) {
            processedData[key] = processValue(jsons.value[key]);
          }
        }

        console.log('对象新', toRaw(processedData));

        let b = {
          singnatrueQunPerson: processedData.singnatrueQunPerson,
          id: form.value.id
        };

        const aaa = JSON.stringify(toRaw(b));
        sessionStorage.setItem('variables', aaa);
        console.log('aaa', aaa);

        flowId.value = 'ProjectSingnatureQun';
        if (form.value.workId2 !== '') {
          return;
        } else {
          // 不弹出提示框，直接执行提交逻辑
          workflowSubmit(
            flowId.value,
            form.value.projectName + '项目' + form.value.workName + '作业已开始，请关注',
            '初始化提交',
            sessionStorage.getItem('variables'),
            form.value.workId2,
            form.value.trackId2
          ).then((result) => {
            if (result.status === 'success') {
              // 将结果返回的workId和trackId保存
              var url = 'sgsafe/ProjectWork/saveProcessInfo2';
              var process = {
                'id': form.value.id,
                'workId': result.workId,
                'trackId': result.trackId
              };
              proxy.$axios.post('sgsafe/ProjectWork/queryCodeByUserId', {params:JSON.parse(localStorage.getItem('chaosongPerson'))}).then(response => {
                if (response.data.code === 0) {
                  var param = {
                    json: JSON.stringify(process)
                  };
                  proxy.$axios.post(url, param).then(response2 => {
                    if (response.data.code === 0) {
                      form.value = response2.data.data;
                      ++form.value.stepNumber
                      console.log('保存成功',response.data.data);
                      sendMessage(form.value.workName + '作业已开始，请关注',response.data.data, form.value.projectName + '项目', 'projectManage/todo_detail/index2?id=' + form.value.id);
                    }
                  });
                }
              });
            } else {
              showToast({
                type: 'error',
                message: '提交审批失败，' + result.msg
              });
            }
          }).catch((error) => {
            // 捕获workflowSubmit执行过程中的错误（如接口调用失败等）
            showToast({
              type: 'error',
              message: '提交过程出错：' + (error.message || '未知错误')
            });
          });

        }
      }


    } else {
      showToast({
        type: 'fail',
        message: '操作失败！'
      });
    }
  });
};
const temporaryStorageSubmit = () => {

  // 原有保存逻辑保持不变
  var url = 'sgsafe/ProjectWork/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      console.log('保存成功后呢', form.value);
      showToast({
        type: 'success',
        message: '保存成功！'
      });
      form.value = response.data.data;
      onClickLeft();

    } else {
      showToast({
        type: 'fail',
        message: '操作失败！'
      });
    }
  });
};
const sendMessage = (title,userCodes, content, routing) => {
  console.log('发送消息给', userCodes);
  var url = 'sgsafe/ProjectWork/sendMessageProjectWork';
  var param = {
    params: JSON.stringify({
      title,
      userCodes,
      content,
      routing
    })
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '发送成功'
      });
    }
  });
};

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;
  console.log('选择内容', selectedOptions);
  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;
  console.log('选择的内容', form.value);
};
const getProjectNames = () => {
  var url = '/sgsafe/Project/queryProjectNames';
  var param = {
    deptCode: deptCode.value
  };
  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
      });
    }
  });
};

/**表单*/
const form = ref({
  id: '',
  projectName: '',
  projectId: '',
  projectLeader: '',
  projectLeaderCode: '',
  workName: '',
  workDesc: '',
  timeStart: '',
  planEnd: '',
  specialPerson: '',
  specialPersonCode: '',
  specialCard: '',

  dangerPoint: '',
  safeMeasure: '',
  ownerTime: '',
  ownerSignatureStart: '',
  protectClothin: '',
  specialType: '',
  specialPhoto: '',

  startPhoto: '',
  endPhoto: '',
  otherSignature: '',
  ownerSignatureEnd: '',
  leaderSignatureEnd: '',
  otherQuestion: '',

  projectSafePerson: '',
  projectSafePersonCode: '',

  stepNumber: 1,
  isManagerSignature: '否',
  isNeedSpecialEq: '否',
  overTask: '否'
});

//最大最小日期
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();
  // 重置为当前时间或从表单获取时间
  if (form.value.timeStart) {
    const dt = new Date(form.value.timeStart);
    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();
    currentTimeStart.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};

//计划结束时间
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();
  // 重置为当前时间或从表单获取时间
  if (form.value.planEnd) {
    const dt = new Date(form.value.planEnd);
    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();
    currentTimePlan.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};

//是否显示作业类别和操作项目
const isShowTypeAndProject = ref(false);
const isShowTypeAndProject2 = ref(false);
//作业类别
const workTypeSelect = ref([]);
const workType = ref([]);
const workTypeOne = ref('');
const showProjectNamePickerWorkType = ref(false);
const onConfirmProjectNameWorkType = ({ selectedOptions }) => {
  workTypeOne.value = selectedOptions[0].value;
  workType.value = workType.value.filter(item =>
    item.jobCategory === selectedOptions[0].value
  );
  if (workType.value.length > 1) {
    workType.value.forEach(e => {
      workProjectSelect.value.push({
        text: e.actionItems,
        value: e.actionItems
      });
    });
    isShowTypeAndProject2.value = true;
  } else {
    cardArray.value.push(workType.value[0].cardFile);
    form.value.specialCard = workType.value[0].cardFile;
  }
  console.log('作业类别', selectedOptions[0].value, workType.value);
  showProjectNamePickerWorkType.value = false;
};

//操作项目
const workProjectSelect = ref([]);
const workProject = ref(null);
const workProjectOne = ref('');
const showProjectNamePickerWorkProject = ref(false);
const onConfirmProjectNameWorkProject = ({ selectedOptions }) => {
  workProjectOne.value = selectedOptions[0].value;
  workType.value = workType.value.filter(item =>
    item.actionItems === selectedOptions[0].value
  );
  cardArray.value.push(workType.value[0].cardFile);
  form.value.specialCard = workType.value[0].cardFile;
  console.log('操作项目', selectedOptions[0].value, workType.value);
  showProjectNamePickerWorkProject.value = false;
};

//特种工作人员
const cardArray = ref([]);
const personArray = ref([]);
const personCodeArray = ref([]);
const specialPersonKey = guid();
const PopupDepartmentSpecialPerson = ref();
const handleDepartmentSpecialPerson = () => {
  isShowTypeAndProject.value = false;
  isShowTypeAndProject2.value = false;
  PopupDepartmentSpecialPerson.value.open();
};

const codeAndDescSpecialPerson = ref([]);
const getDepartmentSpecialPerson = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  codeAndDescSpecialPerson.value.push(items.userCode + '-' + items.userDesc);
  codeList.push(items.userCode);
  descList.push(items.userDesc);
  personArray.value.push(items.userDesc);
  personCodeArray.value.push(items.userCode);
  form.value.specialPersonCode = personCodeArray.value.join(',');
  form.value.specialPerson = personArray.value.join(',');
  console.log('form德职啊', form.value.specialPersonCode, codeList, descList);
  var url = '/sgsafe/CardSpecialWork/queryInfoByUserCode';
  var param = {
    json: JSON.stringify({
      userCode: personCodeArray.value[personCodeArray.value.length - 1]
    })
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code === 0) {
      console.log('链接数据', response.data.data);
      workType.value = response.data.data;
      if (response.data.data.length > 1) {
        response.data.data.forEach(e => {
          workTypeSelect.value.push({
            text: e.jobCategory,
            value: e.jobCategory
          });
        });
        isShowTypeAndProject.value = true;
      } else {
        cardArray.value.push(response.data.data[0].cardFile);
        form.value.specialCard = response.data.data[0].cardFile;
      }
    } else {
      showToast({
        message: '操作失败！' + response.data.message
      });
    }

  });

};

//复选
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}`;
  form.value.ownerTime = `${year}-${month}-${day} ${hours}:${minutes}`;
  showDatetimePickerOwner.value = false;
  dateOrTimeOwner.value = false;
};
// 日期选择器取消
const cancelDatePickerOwner = () => {
  showDatetimePickerOwner.value = false;
  resetDatetimeOwner();
};

// 时间选择器取消
const cancelTimePickerOwner = () => {
  resetDatetimeOwner();
  // 重置为当前时间或从表单获取时间
  if (form.value.ownerTime) {
    const dt = new Date(form.value.ownerTime);
    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();
    currentTimeOwner.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};

//控制是否需要携带特种防护器具
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;
  console.log('选择内容', selectedOptions);
  form.value.specialType = selectedOptions[0].text;
  console.log('选择的内容', form.value);
};

//用来控制下一步显示
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) {
        showToast({
          type: 'success',
          message: '成功抄送'
        });
      } else {
        showToast({
          type: 'fail',
          message: '操作失败' + 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 bhFlag = ref(0);

function resetFlagFlase() {
  bhFlag.value++;
  // 直接通过ref变量访问子组件方法（无需this）
  if (childRef1.value) { // 先判断子组件是否已挂载
    childRef1.value.getTableData();
  }
  console.log('bhFlag', bhFlag.value);
  onClickSignatureFxgzrFlag.value = 'false';
  onClickSignatureQtzyrFlag.value = 'false';
  onClickSignatureGldwqrFlag.value = 'false';
  onClickSignatureZyryqtFlag.value = 'false';
  onClickSignatureGldwqtFlag.value = 'false';
}

//子组件
const childRef1 = ref(null);
const popupSpecialCard = ref(null);

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

/* 穿透scoped样式，覆盖Vant按钮默认样式 */
::v-deep .text-only-next-btn {
  /* 核心：清除背景和边框 */
  background-color: transparent !important;
  border: none !important;
  /* 文本样式：匹配常见主题色，可根据需求修改color值 */
  color: #409EFF !important;
  font-size: 14px;
  /* 调整内边距：避免默认按钮的左右留白过大 */
  padding: 8px 0;
  /* 清除默认圆角（可选，若不需要圆角） */
  border-radius: 0 !important;
}

/* hover状态：轻微浅背景，提升交互感知（可选，可删除） */
::v-deep .text-only-next-btn:hover {
  background-color: rgba(64, 158, 255, 0.05) !important;
}

/* 点击活跃状态：无额外背景，避免点击时出现底色 */
::v-deep .text-only-next-btn:active {
  background-color: transparent !important;
}
</style>
