<template>
  <div class="h5-container">
    <van-nav-bar title="风险告知详情" left-text="返回" left-arrow @click-left="onClickLeft"
    >
      <template #left>
        <svg t="1749540528155" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
             p-id="4132" width="6vw" height="6vh">
          <path
            d="M801.630938 934.023203m-36.203868 36.203867l0 0q-36.203867 36.203867-72.407734 0l-434.446406-434.446406q-36.203867-36.203867 0-72.407734l0 0q36.203867-36.203867 72.407734 0l434.446406 434.446406q36.203867 36.203867 0 72.407734Z"
            fill="#000000" p-id="4133"></path>
          <path
            d="M729.223203-8.030938m36.203867 36.203868l0 0q36.203867 36.203867 0 72.407734l-434.446406 434.446406q-36.203867 36.203867-72.407734 0l0 0q-36.203867-36.203867 0-72.407734l434.446406-434.446406q36.203867-36.203867 72.407734 0Z"
            fill="#000000" p-id="4134"></path>
        </svg>
      </template>
    </van-nav-bar>
    <!-- <van-nav-bar title="请假申请审批" left-arrow @click-left="onClickLeft" /> -->

    <van-tabs v-model:active="activeTab" @change="handleTabsClick" sticky>
      <van-tab title="业务详情">
        <van-form @submit="baocun" ref="formRef">
          <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"
          :rules="[{ required:true, message: '请选择时间' }]"
          required
        />
        <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"
          :rules="[{ required:true, message: '请选择时间' }]"
          required
        />
        <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
          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（纯展示标签） -->
        <van-field
          :colon="true"
          readonly
          label="特种作业人员证件"
          label-width="120"
        ></van-field>
        <AttachmentS3Image :readonly="true" :f-id="form.specialCard" />
      </span>

          <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 :readonly="true" v-if="form.leaderSignatureStart" :f-id="form.leaderSignatureStart+'fxgzrqzs'" />
      </span>
          
        </van-form>
        <div style="background-color: white;">
          <van-button v-if="false" block round type="primary" native-type="submit" style="margin-bottom: 5px;">
            保存
          </van-button>

        </div>
        <van-list
          :finished="isFinished"
          finished-text="没有更多了"
          style="background-color: white;"
        >
          <h3 style="background-color: white;margin-top: 10px;">审批历史</h3>
          <div v-for="item in tableData" :key="item.id" class="card">
            <van-cell
              :label="`操作时间: ${item.actiontime}, 审批意见: ${item.comments},节点名称: ${item.nodename},用户名：${item.username},备注：${item.memo}`"
            >
              <template #title>
                <span style="margin-left: 4px;color: #007aff;">{{ item.actionname }}</span>
              </template>
              <template #label>
                <div class="label-content">
                  <div>操作时间：{{ item.actiontime }}</div>
                  <div>审批意见：{{ item.comments }}</div>
                  <div>节点名称：{{ item.nodename }}</div>
                  <div>用户名：{{ item.username }}</div>
                  <div>备注：{{ item.memo }}</div>
                </div>
              </template>
            </van-cell>
          </div>
          <div style="background-color: white;padding: 10px;height: 70px;"></div>
        </van-list>

        <div :style="cardBodyStyle" v-if="type === '1' || type === '3'" style="background-color: white;">
          <h3 v-if="type === '1' || type === '3'" style="background-color: white;">审批意见</h3>
          <van-field
            v-model="comment"
            type="textarea"
            placeholder="请输入审批意见"
            rows="4"
            required
          />
        </div>
        <div :style="cardBodyStyle" v-if="type !== '0' && flowInfo.flowButtons !== ''" style="background-color: white;">
          <van-button block
                      v-for="item in flowInfo.flowButtons"
                      :key="item.buttonId"
                      :type="buttonType(item.buttonId)"
                      v-show="shouldShowButton(item.buttonId)"
                      @click="handleClick(item)"
                      style="margin-bottom: 5px;"
          >
            {{ buttonName(item.buttonId) }}
          </van-button>
          <van-button block type="danger" @click="qvxiao">
            取消
          </van-button>
        </div>
      </van-tab>
      <van-tab title="流程图" name="image">
        <iframe :src="urlFrame" width="1800px" height="600px" ref="iframe"></iframe>
      </van-tab>
    </van-tabs>
  </div>


  <van-dialog
    v-model:show="showDialog"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleJumpRejectStart"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>

  <van-dialog
    v-model:show="showDialog2"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleGetBack"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>

  <van-dialog
    v-model:show="showDialog3"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleStop"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>

  <van-dialog
    v-model:show="showDialog4"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleReaded"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>

  <van-dialog
    v-model:show="showDialog5"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleReject"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>

  <van-dialog
    v-model:show="showDialog7"
    title="提示"
    show-cancel-button
    :confirm-button-text="confirmButtonText"
    :cancel-button-text="cancelButtonText"
    @confirm="handleConfirmSubmitQueDing"
    @cancel="handleCancel"
  >
    <div>确定要执行该操作吗？</div>
  </van-dialog>
</template>

<script setup>

import {
  ref,
  toRaw,
  reactive,
  onMounted,
  onActivated,
  onBeforeMount,
  getCurrentInstance,
  nextTick,
  defineAsyncComponent
} from 'vue';
import {
  useWorkflowStore
} from '@/stores/workflow';
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import AttachmentS3 from '@/components/AttachmentS3.vue';
import AttachmentS3Image from '@/components/AttachmentS3Image.vue';
import OrganizationalWithLeafUser from '@/components/OrganizationalWithLeafUser.vue';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';


const workflow = useWorkflowStore();

const onClickLeft = () => {
  history.back();
};
const {
  proxy
} = getCurrentInstance();
import {
  useRoute
} from 'vue-router';
import { showToast } from 'vant';

const route = useRoute();
const flowId = ref('');
const workId = ref('');
const trackId = ref('');
const subjectionId = ref('');
const type = ref('');
let out = route.query;
const subjectionIdtem = ref('');

const queryOneById = async () => {
  var url = 'sgsafe/ProjectWork/queryOneById';
  var params = {
    params: out.id
  };
  console.log('id-------------------------', out.id);
  const response = await proxy.$axios.get(url, params);
  console.log('response', response.data);
  if (response.data.code === 0) {
    // await querySubjectionIdByWorkId();
    let temp = JSON.parse(localStorage.getItem('post'))[0].id;
    let dataS = '';
    dataS = response.data.data;
    console.log('222', dataS);
    // console.log('formssssssssssssss', form.value.status);
    // if (response.data.data.status === '2' || response.data.data.status === '3') {
    //   temp = '';
    //   console.log('我执行了判断！！！！！！！！！！！！！！');
    // }
    sessionStorage.setItem('workflowQuery', JSON.stringify({
      flowId: 'ProjectSingnatureQun',
      workId: dataS.workId2,
      trackId: dataS.trackId2,
      subjectionId: temp,
      type: '1',
      date: new Date().getTime()
    }));
    console.log('获取之后', JSON.parse(sessionStorage.getItem('workflowQuery')));
  } else {
    showToast({
      type: 'fail',
      message: response.data.msg
    });
  }
};

//-1
const showDialog = ref(false);
// 显示对话框
const showConfirmDialog = () => {
  showDialog.value = true;
};
// 取消按钮点击事件
const handleCancel = () => {
  showToast({
    message: '已取消！'
  });
  showDialog.value = false;
  showDialog2.value = false;
  showDialog3.value = false;
  showDialog4.value = false;
  showDialog5.value = false;
  showDialog6.value = false;
  showDialog7.value = false;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleJumpReject = () => {
  showConfirmDialog();
};
//-2
const showDialog2 = ref(false);
// 显示对话框
const showConfirmDialog2 = () => {
  showDialog2.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleGet = () => {
  showConfirmDialog2();
};
//-3
const showDialog3 = ref(false);
// 显示对话框
const showConfirmDialog3 = () => {
  showDialog3.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handle = () => {
  showConfirmDialog3();
};
//-4
const showDialog4 = ref(false);
// 显示对话框
const showConfirmDialog4 = () => {
  showDialog4.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleR = () => {
  showConfirmDialog4();
};
//-5
const showDialog5 = ref(false);
// 显示对话框
const showConfirmDialog5 = () => {
  showDialog5.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleRe = () => {
  showConfirmDialog5();
};
//-6
const showDialog6 = ref(false);
// 显示对话框
const showConfirmDialog6 = () => {
  showDialog6.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleConfirmS = () => {
  showConfirmDialog6();
};
//-7
const showDialog7 = ref(false);
// 显示对话框
const showConfirmDialog7 = () => {
  showDialog7.value = true;
};
// 示例：调用 showConfirmDialog() 来触发对话框显示
const handleConfirmSubmit = (nodeName) => {
  variables.value = oldVariables.value;
  if (sessionStorage.getItem('variables') !== null
    && sessionStorage.getItem('variables') !== undefined
    && sessionStorage.getItem('variables') !== '') {
    const newVariables = JSON.parse(sessionStorage.getItem('variables'));

    variables.value = { ...oldVariables.value, ...newVariables };
  }
  console.log('variables.value', variables.value);
  showConfirmDialog7();
};


const confirmButtonText = ref('确认');
const cancelButtonText = ref('取消');

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  console.log(val);
  let repeat = false;

  for (let i = 0; i < val.length; i++) {
    console.log(val[i].user.id);
    repeat = false;
    for (let j = 0; j < multipleSelection.value.length; j++) {
      if (multipleSelection.value[j].user.id === val[i].user.id) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      multipleSelection.value.push(val[i]);
    }
  }

  for (let i = 0; i < val.length; i++) {
    repeat = false;
    for (let j = 0; j < tableDataUser.value.length; j++) {
      if (tableDataUser.value[j].user.id === val[i].user.id) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      tableDataUser.value.push(val[i]);
    }
  }

};

const buttonName = (buttonId) => {
  switch (buttonId) {
    case 'submit':
      return '阅知';
    case 'readed':
      return '阅知';
    case 'reject':
      return '退回';
    case 'jumpreject':
      return 'warning';
    case 'jumprejectstart':
      return '驳回';
    case 'stop':
      return '终止';
    case 'move':
      return '转办';
    case 'getback':
      return '拿回';
    default:
      return 'default'; // 或者返回null/undefined，但Element UI的el-button有默认样式
  }
};

// 一个用于根据name返回button type的函数
const buttonType = (buttonId) => {
  switch (buttonId) {
    case 'submit':
      return 'success';
    case 'readed':
      return 'success';
    case 'reject':
      return 'default';
    case 'jumpreject':
      return 'warning';
    case 'jumprejectstart':
      return 'warning';
    case 'stop':
      return 'danger';
    case 'move':
      return 'primary';
    case 'getback':
      return 'primary';
    default:
      return 'default'; // 或者返回null/undefined，但Element UI的el-button有默认样式
  }
};
const shouldShowButton = (buttonId) => {
  return buttonId === 'submit'
    || buttonId === 'reject'
    // || buttonId === 'jumpreject'
    || buttonId === 'jumprejectstart'
    || buttonId === 'stop'
    || buttonId === 'getback'
    || buttonId === 'readed'
    || buttonId === 'move';
};

import style from '@/tools/style';

const cardBodyStyle = ref(style.card);

const dialogVisibleUser = ref(false);
const dialogVisibleNode = ref(false);
const radioNode = ref('');
const radioNodeValue = ref('');

const radioNodes = ref([]);
const radioNodeSelect = ref([]);

const openDialog = () => {
};

const defaultProps = ref({
  children: 'children',
  label: 'deptName'
});

const expandedKeys = ref([]);
const dataTree = ref([]);
const selectedDept = ref({
  id: '',
  deptCode: ''
});

const onRadioChange = (data) => {
  console.log(data);
  radioNodeValue.value = data;

};

const handleNodeClick = (data) => {
  selectedDept.value = data;
  getTableDataUserDept();
};

const getDataDeptTree = () => {
  if (deptIds.value === '') {
    var url = 'framework/SysDepartment/queryTree';
    var param = {};
    proxy.$axios.get(url, param).then(response => {
      dataTree.value = response.data.data;
      if (dataTree.value.length === 1) {
        for (var node of dataTree.value) {
          expandedKeys.value.push(node.id);
        }
        console.log(dataTree.value);
      }
    });
  } else {
    var url = 'framework/SysDepartment/queryByIds';
    var param = {
      ids: deptIds.value
    };
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        // var children = []
        // children.push(response.data.data)
        dataTree.value = [{
          id: '10010',
          deptCode: 'root',
          deptName: '部门',
          children: response.data.data
        }];
        for (var node of dataTree.value) {
          expandedKeys.value.push(node.id);
        }
      }
    });
  }
};

const defaultPropsPost = ref({
  children: 'children',
  label: 'postName'
});

const expandedKeysPost = ref([]);
const dataPost = ref([]);
const selectedPost = ref({
  id: '',
  postCode: ''
});

const getDataPost = () => {
  var url = 'framework/SysPost/queryByIds';
  var param = {
    page: 1,
    rows: 40,
    ids: postIds.value
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {

      dataPost.value = [{
        id: '10086',
        postCode: 'root',
        postName: '岗位',
        children: response.data.data
      }];
      for (var node of dataPost.value) {
        expandedKeysPost.value.push(node.id);
      }
    }
  });
};

const handleNodeClickPost = (data) => {
  selectedPost.value = data;
  getTableDataUserPost();
};

const getTableDataUserPost = () => {
  var url = 'framework/SysUserPost/queryByPostId';
  var param = {
    postId: selectedPost.value.id
  };
  proxy.$axios.get(url, param).then(response => {
    tableDataUserDept.value = response.data.data;
  });
};


const tableDataUserDept = ref([]);

const getTableDataUserDept = () => {
  var url = 'framework/SysUserDept/queryByDeptId';
  var param = {
    deptId: selectedDept.value.id
  };
  proxy.$axios.get(url, param).then(response => {
    tableDataUserDept.value = response.data.data;
  });
};

const tableDataUser = ref([]);

const handleDeleteUserData = (row) => {

  for (let i = 0; i < multipleSelection.value.length; i++) {
    if (multipleSelection.value[i].id === row.id) {
      multipleSelection.value.splice(i, 1);
    }
  }

  for (let i = 0; i < tableDataUser.value.length; i++) {
    if (tableDataUser.value[i].id === row.id) {
      tableDataUser.value.splice(i, 1);
    }
  }
};


const handleSave = () => {
  handleConfirmSubmit(nextNodeName.value);
  dialogVisibleUser.value = false;
};

const handleCancelSave = () => {
  dialogVisibleUser.value = false;
};

const handleSaveNode = () => {
  // handleConfirmSubmit()
  radioNodeSelect.value = [];
  console.log(radioNodeValue.value);
  for (let i = 0; i < radioNodes.value.length; i++) {
    if (radioNodes.value[i].nodeId === radioNodeValue.value) {
      radioNodes.value[i].isSelect = 'true';
      radioNodeSelect.value.push(radioNodes.value[i]);
    }
  }

  nextNodeList.value = radioNodeSelect.value;
  console.log(nextNodeList.value);
  handlePreSubmit();
  dialogVisibleNode.value = false;
};

const handleCancelSaveNode = () => {
  dialogVisibleNode.value = false;
};

const checkboxDangerPoint = ref([])
const checkboxSafeMeasure = ref([])
const queryByWorkId = async () => {
  var url = 'sgsafe/ProjectWork/queryByWorkId2';
  var param = {
    workId: workId.value
  };
  console.log('查询参数', param);
  const response = await proxy.$axios.get(url, param);
  if (response.data.code == '0') {
    console.log('查询成功nihao', response.data);
    console.log('你好', response.data.data);
    form.value = response.data.data;
    console.log('form', form.value)
    checkboxDangerPoint.value = response.data.data.dangerPoint.split(',');
    checkboxSafeMeasure.value = response.data.data.safeMeasure.split(',');
  } else {
    showToast({
      message: '操作失败！' + response.data.msg
    });
  }
};

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


  const workflowQuery = JSON.parse(sessionStorage.getItem('workflowQuery'));
  console.log('onMountedworkflowQuery啊', workflowQuery);
  flowId.value = workflowQuery.flowId;
  workId.value = workflowQuery.workId;
  trackId.value = workflowQuery.trackId;
  subjectionId.value = workflowQuery.subjectionId;
  type.value = workflowQuery.type;
  if (type.value === undefined || type.value === null) {
    type.value = '0';
  }

  console.log('你还好吗subjectid', workflowQuery.subjectionId);

  await queryByWorkId();

  await openWorkflow();

  await getTableData();

  // await querySubjectionIdByWorkId();
});

onActivated(() => {
  debugger
  const workflowQuery = JSON.parse(sessionStorage.getItem('workflowQuery'));
  console.log('onActivated', workflowQuery);
  flowId.value = workflowQuery.flowId;
  workId.value = workflowQuery.workId;
  trackId.value = workflowQuery.trackId;
  subjectionId.value = workflowQuery.subjectionId;
  type.value = workflowQuery.type;
  if (type.value === undefined || type.value === null) {
    type.value = '0';
  }
  openWorkflow();
  // getBusinessPage()

});

// const loginName = ref(localStorage.getItem('userName'))
const handleTabsClick = (tab, event, item) => {
  // if (activeTab.value == 'process') {
  //   getHistory();
  // } else if (activeTab.value == 'image') {
  //   urlFrame.value =
  //     `${import.meta.env.VITE_WORKFLOW_ADDR}` + '/horizon-workflow-boot/workflow/module/designer/index.html?workid=' + workId
  //       .value + '&showtype=2&dataid=' + workId.value;
  // }
  if (activeTab.value == 'image') {
    urlFrame.value =
      `${import.meta.env.VITE_WORKFLOW_ADDR}` + '/horizon-workflow-boot/workflow/module/designer/index.html?workid=' + workId
        .value + '&showtype=2&dataid=' + workId.value;
  }
};

const activeName = ref('business');
/*const flowId = ref('');
const workId = ref('');
const trackId = ref('');
const subjectionId = ref('');
const type = ref('');*/

const nextNodeList = ref([]);

const urlFrame = ref('');

const currentComponent = ref('');
const tableDataHistory = ref([]);

const getHistory = async () => {

  var url = 'workflow/process/history';
  var param = {
    workId: workId
  };
  const response = await proxy.$axios.post(url, param);

  if (response.data.code == '0') {
    tableDataHistory.value = response.data.data.records;
  } else {
    showToast({
      type: 'error',
      message: '操作失败！' + response.data.msg
    });
  }
};

const getBusinessPage = () => {
  var url = 'framework/BusinessProcess/queryBusinessPageByFlowId';
  var param = {
    flowId: flowId.value
  };
  console.log('flowId:::' + JSON.stringify(flowId.value));
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      console.log('getBusinessPage:::' + JSON.stringify(response.data.data));

      const modules = import.meta.glob('../**/*.vue');
      currentComponent.value = defineAsyncComponent(modules[`..${response.data.data.pathWeb}.vue`]);

    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const flowInfo = ref({});
const oldVariables = ref({});
const nextNodeName = ref('');

const postIds = ref('');

const deptIds = ref('');


const openWorkflow = async () => {
  var url = 'workflow/task/open';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value
  };
  const response = await proxy.$axios.post(url, param);
  if (response.data.code == '0') {
    console.log('openworkflDD按钮', response.data);
    flowInfo.value = response.data.data;
    oldVariables.value = flowInfo.value['flowVars'];
  } else {
  }
  workflow.setWorkId(workId.value);
  console.log('workflow.workId设置仓库的workId', workflow.workId);
  getBusinessPage();
};

const comment = ref('');

const itemtemp = ref([]);
const handleClick = async (item) => {
  itemtemp.value = item;
  await baocun();


};

const variables = ref({});
const handlePreSubmit = () => {
  variables.value = oldVariables.value;
  if (sessionStorage.getItem('variables') !== null
    && sessionStorage.getItem('variables') !== undefined
    && sessionStorage.getItem('variables') !== '') {
    const newVariables = JSON.parse(sessionStorage.getItem('variables'));
    variables.value = { ...oldVariables.value, ...newVariables };
  }
  if (comment.value === undefined || comment.value === '') {
    showToast({
      type: 'error',
      message: '请填写审批意见'
    });
    return;
  }
  var url = 'workflow/task/submit';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value,
    comment: comment.value,
    variables: JSON.stringify(variables.value),
    nextNodes: JSON.stringify(nextNodeList.value)
  };
  console.log('valibles', JSON.stringify(variables.value));
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      console.log(response.data.data);
      var status = response.data.data.status;
      // 选人
      if (status === 4) {
        var nextNodes = response.data.data.nextNodes;
        // 后续就只有一个节点，不需要选择节点
        if (nextNodes && nextNodes.length === 1) {
          if ((nextNodes[0].authors.Author && nextNodes[0].authors.Author.initAuthor)
            || (nextNodes[0].authors.Author && nextNodes[0].authors.Author.selectAuthor === undefined)) {

            var positions = undefined;
            var depts = undefined;
            var others = undefined;
            if (nextNodes[0].authors.Author.initAuthor) {
              positions = nextNodes[0].authors.Author.initAuthor.positions;
              depts = nextNodes[0].authors.Author.initAuthor.depts;
              others = nextNodes[0].authors.Author.initAuthor.others;
              // 岗位
              if (positions) {
                postIds.value = '';
                for (let i = 0; i < positions.length; i++) {
                  postIds.value += positions[i].id + ',';
                }
                console.log('positions:' + postIds.value);
                getDataPost();
              }

              // 部门
              if (depts) {
                deptIds.value = '';
                for (let i = 0; i < depts.length; i++) {
                  deptIds.value += depts[i].id + ',';
                }
                console.log('depts:' + deptIds.value);
                getDataDeptTree();
              }
            }

            if (nextNodes[0].authors.Author.initAuthor === undefined
              && nextNodes[0].authors.Author.selectAuthor === undefined) {
              getDataPost();
              getDataDeptTree();
            }

            // 打开弹出框
            dialogVisibleUser.value = true;
            nextNodeList.value = nextNodes;
            nextNodeName.value = nextNodes[0].nodeName;
          }
          // 不选人
          else {
            handleConfirmSubmit(nextNodes[0].nodeName);
          }
        }
        // 后续多个节点，需要选择节点、给多节点赋值用户
        else if (nextNodes && nextNodes.length > 1) {
          console.log('后续多个节点，需要选择节点、给多节点赋值用户');
        }
        // 没有后续节点
        else {
          console.log('没有后续节点');
        }
      }
      // 选节点
      else if (status === 2) {
        radioNodes.value = response.data.data.nextNodes;
        console.log(radioNodes.value);
        if (radioNodes.value.length > 0) {
          radioNode.value = radioNodes.value[0].nodeName;
          console.log(radioNode.value);
        }
        dialogVisibleNode.value = true;
      }
      // 执行成功
      else if (status === 0) {
        var nextNodes = response.data.data.nextNodes;
        handleConfirmSubmit(nextNodes[0].nodeName);
      }
    } else {
      showToast({
        type: 'error',
        message: '操作失败'
      });
    }
  });
};

const handleConfirmSubmitQueDing = () => {
  var url = 'workflow/task/confirmSubmit';

  if (tableDataUser.value.length > 0) {
    var selectAuthor = '';
    var selectAuthorName = '';
    for (let i = 0; i < tableDataUser.value.length; i++) {
      selectAuthor = selectAuthor + tableDataUser.value[i].user.id + ';';
      selectAuthorName = selectAuthorName + tableDataUser.value[i].user.userDesc + ';';
    }
    var author = {
      'authorId': 'Author',
      'authorName': '主办',
      'selectType': 'radio',
      'isFree': 'true',
      'isUser': 'false',
      'isDefUser': 'false',
      'isSelect': 'true',
      'selectAuthor': selectAuthor,
      'selectAuthorName': selectAuthorName,
      'required': null,
      'initAuthor': null
    };
    nextNodeList.value[0].authors.Author = author;
  }

  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value,
    comment: comment.value,
    variables: JSON.stringify(variables.value),
    nextNodes: JSON.stringify(nextNodeList.value)
  };

  console.log('param' + JSON.stringify(param));

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      console.log(response.data);
      showToast({
        type: 'success',
        message: '操作成功，流程已通过'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败' + response.data.msg
      });
    }
  });
};

const handleReject = () => {
  var url = 'workflow/task/reject';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value,
    comment: comment.value
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '操作成功，流程已退回'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败' + response.data.msg
      });
    }
  });
};

const handleReaded = () => {
  var url = 'workflow/task/read';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '操作成功，流程已读'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败，请联系开发人员'
      });
    }
  });
};

const handleStop = () => {
  var url = 'workflow/task/stop';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '操作成功，流程已终止'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败，请联系开发人员'
      });
    }
  });
};

const handleGetBack = () => {
  var url = 'workflow/task/getBack';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '操作成功，流程已拿回'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败，流程已审批，不允许拿回'
      });
    }
  });
};

const handleJumpRejectStart = () => {
  var url = 'workflow/task/jumpRejectStart';
  var param = {
    workId: workId.value,
    trackId: trackId.value,
    subjectionId: subjectionId.value,
    comment: comment.value
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '操作成功，流程已退回到提交人！'
      });
      handleTodo();
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const handleTodo = () => {
  if (type.value === '2') {
    proxy.$router.push({
      path: '/workflow/haddone',
      query: {}
    });
  } else if (type.value === '3') {
    proxy.$router.push({
      path: '/schedule'
    });
  } else {
    proxy.$router.push({
      // path: '/workflow/todo',
      path: '/projectManage/todo',
      query: {}
    });
  }
};


/**历史任务详情**/
const tableData = ref([]);
const date = ref(null);
const query = ref({
  hdType: ''
});
const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);

const getTableData = async () => {
  const url = 'workflow/process/history';
  const param = {
    workId: workId.value
  };
  const response = await proxy.$axios.get(url, param);
  if (response.data.code === 0) {

    tableData.value = response.data.data.records;

    tableData.value.forEach(item => {
      switch (item.status) {
        case '0':
          item.status = '隐患登记';
          break;
        case '1':
          item.status = '隐患分析确认';
          break;
        case '2':
          item.status = '隐患整改';
          break;
        case '3':
          item.status = '隐患验收';
          break;
        case '4':
          item.status = '隐患销号';
          break;
        case '5':
          item.status = '结束';
          break;
        case '-1':
          item.status = '待提交';
          break;
      }
    });
  } else {
    showToast({
      type: 'error',
      message: '操作失败！' + response.data.msg
    });
  }
};

const onLoad = () => {
  if (!isFinished.value) {
    currentPage.value += 1;
    getTableData();
  }
};

//表单
/**表单*/
const form = ref({
  discovererOtherDesc: '',
  hdPicId: '',
  hdId: '',
  hdType: '',
  discoveryTime: '',
  hdSubtype: '',
  discoverer: '',
  discovererOther: '',
  hdDescription: '',
  hdLevel: '',
  bz: '',
  hdLocation: '',
  picBefore: '',

  equipmentId: '',
  hdmanageLevel: '',
  handlingProcesses: '',
  companyId: '',
  repairLeader: '',
  repairOther: '',
  repairSuggest: '',
  repairDdl: '',
  repairDept: '',
  acceptLeader: '',
  acceptOther: '',
  picAfter: '',
  picTemp: '',
  repairDescription: '',
  discovererDept: '',
  discovererDeptCode: '',
  hdLocationCode: '',
  hdLocationName: '',

  status: '',


  hdSelect: '正常登记',
  id: ''
});

//发现时间
const showDatetimePicker = ref(false);
const currentDate = ref([2024, 8, 1]);
const currentTime = ref([12, 0, 0]);
const minDate = new Date(2000, 0, 1);
const maxDate = new Date(2050, 11, 31);

const onDateConfirm = () => {
  // 日期选择确认后的处理
};

const onTimeConfirm = () => {
  // 时间选择确认后的处理
};

const onConfirmDatetime = () => {
  const year = currentDate.value[0];
  const month = currentDate.value[1].toString().padStart(2, '0');
  const day = currentDate.value[2].toString().padStart(2, '0');
  const hours = currentTime.value[0].toString().padStart(2, '0');
  const minutes = currentTime.value[1].toString().padStart(2, '0');
  const seconds = currentTime.value[2].toString().padStart(2, '0');

  form.value.discoveryTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePicker.value = false;
};

//整改期限
const showDatetimePicker2 = ref(false);
const currentDate2 = ref([2024, 8, 1]);
const currentTime2 = ref([12, 0, 0]);
const minDate2 = new Date(2000, 0, 1);
const maxDate2 = new Date(2050, 11, 31);
const dateOrTime2 = ref(false);
const onDateConfirm2 = () => {
  // 日期选择确认后的处理
  console.log('选择内容', dateOrTime2.value);
  dateOrTime2.value = true;
};

const onTimeConfirm2 = () => {
  // 时间选择确认后的处理
};

const onConfirmDatetime2 = () => {
  const year = currentDate2.value[0];
  const month = currentDate2.value[1].toString().padStart(2, '0');
  const day = currentDate2.value[2].toString().padStart(2, '0');
  const hours = currentTime2.value[0].toString().padStart(2, '0');
  const minutes = currentTime2.value[1].toString().padStart(2, '0');
  const seconds = currentTime2.value[2].toString().padStart(2, '0');

  form.value.repairDdl = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePicker2.value = false;
  dateOrTime2.value = false;
};


const showPicker2 = ref(false);

const onConfirmYhdj = ({ selectedOptions }) => {
  showPicker2.value = false;
  form.value.hdLevel = selectedOptions[0].value;
  console.log('选择的内容', form.value);
};

const yhdjs = ref([{ text: '一般隐患', value: '一般隐患' },
  { text: '重大隐患', value: '重大隐患' }]
);

const formRef = ref(null);
const qvxiao = () => {
  showToast({
    type: 'fail',
    message: '操作取消！'
  });
  onClickLeft();
};
const baocun = () => {
  var url = 'sgsafe/ProjectWork/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      showToast({
        type: 'success',
        message: '操作成功！'
      });
       orJsons();
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};
const repairLL = ref('');
const repairOO = ref('');
const acceptLL = ref('');
const acceptOO = ref('');
const hdCancel = ref('');
const jsons = ref('');
const countJSQ = ref(0);
const orJsons = async () => {
  console.log('forms打印一下', form.value);
  hdCancel.value = await qq('sdaf', form.value.projectLeaderCode);
  console.log('hdCancel打印一下', hdCancel.value);
};
const qq = async (a, val) => {
  countJSQ.value += 1;
  let aa = '';
  var url = 'sgsafe/Hiddendanger/qqId';
  var param = {
    params: val
  };
  console.log('参数打印一下', param);
  await proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {

      aa = response.data.data;
      console.log('返回值', aa);
      jsons.value = {
        projectLeader: aa
      };
      // console.log('niadsiofjmowe',jsons.value)

      // 处理函数
      function processValue(value) {
        // 将逗号替换为分号
        console.log('value', 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)) {
          console.log('key', jsons.value);
          processedData[key] = processValue(jsons.value[key]);
        }
      }

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

      const b = {
        projectLeader: processedData.projectLeader,
        id: form.value.id
      };

      const aaa = JSON.stringify(toRaw(b));
      // workflow.setAcceptAndRepair(aaa)
      sessionStorage.setItem('variables', aaa);
      console.log('aaa', sessionStorage.getItem('variables'));
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
  let item = itemtemp.value;
  console.log(item['buttonId']);
  console.log(item['buttonName']);
  if (item['buttonId'] === 'submit') {
    handlePreSubmit();
    countJSQ.value = 0;
  } else if (item['buttonId'] === 'reject') {
    handleRe();
    countJSQ.value = 0;
  } else if (item['buttonId'] === 'jumprejectstart') {
    handleJumpReject();
    countJSQ.value = 0;
  } else if (item['buttonId'] === 'getback') {
    handleGet();
    countJSQ.value = 0;
  } else if (item['buttonId'] === 'stop') {
    handle();
    countJSQ.value = 0;
  } else if (item['buttonId'] === 'readed') {
    handleR();
    countJSQ.value = 0;
  }

  return aa;
};

const handleChangeHdSelect = (value) => {
  form.value.hdSelect = value;
  if (value === '正常登记') {
    isStandardFlow.value = true;
  } else if (value === '即查即改') {
    isStandardFlow.value = false;
  }
  getYHID();
};

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

  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};
/* 发现人 */
const leaderKey = guid();
const PopupDepartmentLeaderNameRef = ref();
const handleDepartmentLeaderName = () => {
  PopupDepartmentLeaderNameRef.value.open();
};

const codeAndDesc = ref([]);
const getDepartmentLeaderName = (item) => {
  form.value.discoverer = item.user.userCode;
  form.value.discovererDesc = item.user.userDesc;
  form.value.discovererDeptCode = item.dept.deptCode;
  form.value.discovererDept = item.dept.deptName;
};

/* 其他发现人 */
const leaderKey2 = guid();
const PopupDepartmentLeaderNameRef2 = ref();
const handleDepartmentLeaderName2 = () => {
  PopupDepartmentLeaderNameRef2.value.open();
};

const codeAndDesc2 = ref([]);
const getDepartmentLeaderName2 = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDesc2.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.discovererOther = codeList.join(',');
  form.value.discovererOtherDesc = descList.join(',');
};

//定义一个变量切换即查即改还是标准流程
const isStandardFlow = ref(false);

//当是即查即改时得到隐患编号并赋值
const getYHID = () => {
  //直接请求后端返回一个隐患编号
  console.log('getYHID');
  if (form.value.hdSelect === '即查即改') {
    var url = 'sgsafe/Hiddendanger/getYhbhTemp';
    var param = {};
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        form.value.hdId = response.data.data;
      } else {
        showToast({
          type: 'error',
          message: '操作失败！' + response.data.msg
        });
      }
    });
  } else {
    form.value.hdId = '';
  }
};

/* 整改人 */
const leaderKeyzgr = guid();
const PopupDepartmentLeaderNameRefzgr = ref();
const handleDepartmentLeaderNamezgr = () => {
  PopupDepartmentLeaderNameRefzgr.value.open();
};

const codeAndDesczgr = ref([]);
const getDepartmentLeaderNamezgr = (item) => {
  form.value.repairLeader = item.user.userCode;
  form.value.repairLeaderDesc = item.user.userDesc;
  form.value.repairDept = item.dept.deptName;
};

/* 其他整改人 */
const leaderKey2qtzgr = guid();
const PopupDepartmentLeaderNameRef2qtzgr = ref();
const handleDepartmentLeaderName2qtzgr = () => {
  PopupDepartmentLeaderNameRef2qtzgr.value.open();
};

const codeAndDesc2qtzgr = ref([]);
const getDepartmentLeaderName2qtzgr = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDesc2qtzgr.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.repairOther = codeList.join(',');
  form.value.repairOtherDesc = descList.join(',');
};

/* 验收人 */
const leaderKeyysr = guid();
const PopupDepartmentLeaderNameRefysr = ref();
const handleDepartmentLeaderNameysr = () => {
  PopupDepartmentLeaderNameRefysr.value.open();
};

const codeAndDescysr = ref([]);
const getDepartmentLeaderNameysr = (item) => {
  form.value.acceptLeader = item.user.userCode;
  form.value.acceptLeaderDesc = item.user.userDesc;
};

/* 其他验收人 */
const leaderKey2qtysr = guid();
const PopupDepartmentLeaderNameRef2qtysr = ref();
const handleDepartmentLeaderName2qtysr = () => {
  PopupDepartmentLeaderNameRef2qtysr.value.open();
};

const codeAndDesc2qtysr = ref([]);
const getDepartmentLeaderName2qtysr = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDesc2qtysr.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.acceptOther = codeList.join(',');
  form.value.acceptOtherDesc = descList.join(',');
};

/* 组织树选择 */
const showBottom = ref(false);
const handleTableDataUserDeptUpdate = async (nodeData) => {
  form.value.repairDept = nodeData.deptName;
  // form.value.repairDept = nodeData.deptCode + '-' + nodeData.deptName
  showBottom.value = false;
};
const showPickerHandle = () => {
  showBottom.value = true;
};

</script>

<style scoped>
/*自定义单选样式*/


.h5-container {
  width: 100%;
  box-sizing: border-box;
  height: 100vh;
  background-color: white;
  padding: 10px;
}

.card {
  margin: 10px;
  border-radius: 8px;
  background-color: #fff;
}

.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

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