<template>
  <div>
    <el-radio-group v-model="tabPosition" style="margin: 5px">
      <el-radio-button label="first">选择岗位</el-radio-button>
      <el-radio-button label="second">选择SOP</el-radio-button>
      <el-radio-button label="third">作业详情</el-radio-button>
    </el-radio-group>
    <div
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
      "
      v-show="tabPosition == 'first'"
    >
      <!-- 缩放容器 -->
      <div
        ref="mapContainer"
        :style="{
          transform: `scale(${scaleFactor})`,
          transformOrigin: 'top left',
          width: '1250px',
          height: '700px',
          position: 'relative',
        }"
      >
        <img
          :style="{width:jobconfig.width+'px',height:jobconfig.height+'px'}"
          :src="jobconfig.imageUrl"
          alt=""
        />
        <div v-for="(item, index) in jobconfigPoint.records" :key="item.id">
          <!-- 绿色盒子 -->
          <div
            class="deptGreen"
            :style="{left:item.x+'px',top:item.y+'px'}"
            @click="handelChange('second', item.entityId, item.entityName)"
          >
            {{ item.entityName }}
          </div>

          <!--          // 使图标位于岗位上方-->
          <div
            v-for="(ticket, i) in (TicketListPage[item.entityId] && TicketListPage[item.entityId].slice(0, 3)) || []"
            :key="'btn-' + i"
            @click="handleTicketDialogVisible(item.entityId, item.entityName)"
            :style="{
    width: '28px',
    height: '28px',
    background: 'rgb(4, 134, 241)',
    textAlign: 'center',
    lineHeight: '28px',
    fontSize: '20px',
    color: 'white',
    borderRadius: '5px',
    position: 'absolute',
    top: (item.y - 70) + 'px',
    left: (item.x - ((TicketListPage[item.entityId] ? Math.min(TicketListPage[item.entityId].length, 3) * 35 : 0) - 60) / 2 + i * 40) + 'px', // 动态计算宽度
    cursor: 'pointer'
  }"
          >
            {{ (i === 2 && TicketListPage[item.entityId] && TicketListPage[item.entityId].length > 3) ? '3+' : (i + 1) }}
          </div>

          <img
            v-for="(ticket, index) in (TicketListPage[item.entityId] && TicketListPage[item.entityId].slice(0, 3)) || []"
            :key="ticket.ticketId"
            :style="{
    width: '35px',
    height: '35px',
    position: 'absolute',
    cursor: 'pointer',
    top: (item.y - 40) + 'px',
    left: (item.x - ((TicketListPage[item.entityId] ? Math.min(TicketListPage[item.entityId].length, 3) * 35 : 0) - 53) / 2 + index * 40) + 'px' // 动态计算宽度
  }"
            :src="index === 2 && (TicketListPage[item.entityId] && TicketListPage[item.entityId].length > 3) ? imageMap[5] : imageMap[ticket.ticketType]"
            alt=""
            @click="index === 2 && (TicketListPage[item.entityId] && TicketListPage[item.entityId].length > 3) ? handleTicketDialogVisible(item.entityId, item.entityName) : handleTicketClick(ticket)"
          />
<!--          <div-->
<!--            v-for="(ticket, i) in (TicketListPage[item.entityId] && TicketListPage[item.entityId].slice(0, 3)) || []"-->
<!--            :key="'btn-' + i"-->
<!--            @click="handleTicketDialogVisible(item.entityId, item.entityName)"-->
<!--            :style="{-->
<!--      width: '28px',-->
<!--      height: '28px',-->
<!--      background: 'rgb(4, 134, 241)',-->
<!--      textAlign: 'center',-->
<!--      lineHeight: '28px',-->
<!--      fontSize: '20px',-->
<!--      color: 'white',-->
<!--      borderRadius: '5px',-->
<!--      position: 'absolute',-->
<!--      top: (item.y - 70) + 'px',-->
<!--      left: (item.x - ((TicketListPage[item.entityId] ? 3 * 35 : 0) - 53) / 2 + i * 40) + 'px',-->
<!--      cursor: 'pointer'-->
<!--    }"-->
<!--          >-->
<!--            {{ i + 1 }}-->
<!--          </div>-->
<!--          &lt;!&ndash; 显示作业票图标，最多 3 个图标 &ndash;&gt;-->
<!--          <img-->
<!--            v-for="(ticket, index) in (TicketListPage[item.entityId] && TicketListPage[item.entityId].slice(0, 3)) || []"-->
<!--            :key="ticket.ticketId"-->
<!--            :style="{-->
<!--              width: '35px',-->
<!--              height: '35px',-->
<!--              position: 'absolute',-->
<!--              cursor: 'pointer',-->
<!--              top: (item.y - 40) + 'px',  // 让图标浮在岗位的上方-->
<!--              left: (-->
<!--                item.x - -->
<!--                ((TicketListPage[item.entityId] ? TicketListPage[item.entityId].length * 35 : 0) - 53) / 2 +  // 计算总宽度并居中，减去单个图标宽度，确保居中-->
<!--                index * 40  // 处理图标间隔-->
<!--              ) + 'px'-->
<!--            }"-->
<!--            :src="index === 2 && (TicketListPage[item.entityId] && TicketListPage[item.entityId].length > 3) ? imageMap[5] : imageMap[ticket.ticketType]"-->
<!--            alt=""-->
<!--            @click="index === 2 && (TicketListPage[item.entityId] && TicketListPage[item.entityId].length > 3) ? handleTicketDialogVisible(item.entityId, item.entityName) : handleTicketClick(ticket)"-->

<!--          />-->


        </div>

      </div>
    </div>

    <div
      style="
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        position: relative;
      "
      v-show="tabPosition == 'second'"
    >
      <h3 style="margin-left: 20px">{{ this.marsSopTitle }} SOP</h3>
      <span style="margin-left: 20px">选择 工艺/设备</span>
      <!--      :data="marsSopPage"-->
      <el-table
        style="width: 50%; margin: 20px"
        :header-cell-style="{ background: '#004d8c', color: '#FFFFFF' }"
        :data="technologyList"
        highlight-current-row
        @current-change="handleSelectionChange"
      >
        <!--        <el-table-column type="selection" width="55" align="center"/>-->
        <!--        <el-table-column-->
        <!--          label="sop名称"-->
        <!--          align="center"-->
        <!--          prop="sopName"-->
        <!--        ></el-table-column>-->
        <el-table-column
          label="设备/工艺名称"
          align="center"
          prop="machineryName"
        ></el-table-column>
        <!--        <el-table-column-->
        <!--          label="所属岗位"-->
        <!--          align="center"-->
        <!--          prop="workstationName"-->
        <!--        ></el-table-column>-->
      </el-table>
      <h2 style="margin-left: 20px">sop类型</h2>
      <el-radio-group
        v-model="selectedOption"
        size="small"
        style="display: flex; flex-direction: column; align-items: flex-start"
        @change="handleSopchange"
      >
        <!-- v-for="(option, index) in filteredSopTypes"-->
        <el-radio
          v-for="item in sopTypeOption"
          :key="item.value"
          :label="item.label"
          border
          style="margin: 10px"
        >
          {{ item.label }}
        </el-radio>
      </el-radio-group>
      <el-button
        type="primary"
        style="margin-left: 140px"
        @click="handelChange('third')"
      >开始执行
      </el-button>
    </div>
    <div
      style="position: relative; display: flex"
      v-show="tabPosition == 'third'"
    >
      <div
        class="left"
        style="width: 35%; display: flex; flex-direction: column"
      >
        <div class="left-top">
          <el-card class="box-card" style="margin: 10px" v-loading="loading">
            <div slot="header" class="clearfix">
              <span>工艺/设备 工艺图</span>
            </div>
            <img style="margin-left: 25%;width: 200px;height: 230px" :src="this.machineryImg" alt=""/>
          </el-card>
        </div>
        <div class="left-bottom">
          <el-card class="box-card" style="height: 102%; margin: 10px" v-loading="loading">
            <div slot="header" class="clearfix">
              <span>锁定站信息</span>
              <i
                class="el-icon-search"
                style="
                  float: right;
                  padding: 3px 0;
                  cursor: pointer;
                  color: #189eff;
                "
                @click="goLockDetail"
              ></i>
            </div>
            <el-row>
              <MapData
                :machineryId="this.machineryId"
              ></MapData>
              <!--              <el-col :span="9">-->
              <!--                <el-table-->
              <!--                  :data="selectPointList"-->
              <!--                  :show-header="false"-->
              <!--                  height="200"-->
              <!--                  @row-click="handleChangeTable"-->
              <!--                  v-if="tableVisible"-->
              <!--                >-->
              <!--                  <el-table-column prop="pointName" label=""></el-table-column>-->
              <!--                  <el-table-column prop="remark" label=""></el-table-column>-->
              <!--                </el-table>-->
              <!--                <span-->
              <!--                  v-if="!tableVisible"-->
              <!--                  style="color: #53a3ef; cursor: pointer"-->
              <!--                  @click="handleChangeTable"-->
              <!--                >锁定站</span-->
              <!--                >-->
              <!--                <img-->
              <!--                  src="@/assets/images/MapImage.png"-->
              <!--                  style="width: 200px; height: 130px; margin-top: 10px"-->
              <!--                />-->
              <!--              </el-col>-->
              <!--              <el-col :span="8">-->

              <!--              </el-col>-->
            </el-row>
          </el-card>
        </div>
      </div>
      <div class="right" style="flex: 1">
        <el-card class="box-card" style="margin: 10px; height: 800px;">
<!--          <div slot="header" class="clearfix">-->
<!--            <span>八大步骤</span>-->
<!--          </div>-->
          <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="八大步骤" name="eightSteps">
          <div
            style="
              width: 100%;
              height: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <div style="width: 700px; height: 600px">
              <div style="width: 100%; height: 100px">
                <div>
                  <!--                  :show-header="false"-->
                  <el-table :data="EightStepForm" style="margin-top: 60px">
                    <el-table-column label="步骤" prop="stepIndex">
                      <template slot-scope="scope">
                        <span>第{{ scope.row.stepIndex }}步</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="步骤" prop="number">
                      <template slot-scope="scope">
                        <span v-if="scope.row.lockNum !== null">
                          <!--                          <img src="@/assets/images/lockImg.png" alt="" style="width: 12px;height:13px;margin-top: 5px;">-->
                          <i class="el-icon-lock">{{ scope.row.lockNum }}</i>
                        </span>
                        <span v-if="scope.row.userNum !== null">
                          <i class="el-icon-user">{{ scope.row.userNum }}</i>
                        </span>
                        <span v-if="scope.row.conflictJobNum !== null">
                          <i class="el-icon-s-claim">{{
                              scope.row.conflictJobNum
                            }}</i>
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="stepStatus">
                      <template slot-scope="scope">
                        <!-- 判断逻辑 -->
                        <span
                          v-if="
                            scope.row.stepIndex == '3' &&
                            (scope.row.stepStatus !== '1' ||
                              !isStepFourExecuted)
                          "
                        >
                          <el-button
                            disabled
                            type="primary"
                            plain
                            size="small"
                            @click="addInside(scope.row)"
                          >
                            分配
                          </el-button>
                        </span>
                        <span
                          v-if="
                            scope.row.stepIndex == '3' &&
                            scope.row.stepStatus === '1' &&
                            isStepFourExecuted
                          "
                        >
                          <span
                            style="
                              display: inline-block;
                              width: 8px;
                              height: 8px;
                              margin: 1%;
                              border-radius: 50%;
                              background: #6aabfb;
                            "
                          ></span>
                          <span>已执行</span>
                        </span>

                        <!-- 其他步骤 -->
                        <span
                          v-if="
                            scope.row.stepIndex != '3' &&
                            scope.row.stepStatus !== '1'
                          "
                        >
                          <el-button
                            disabled
                            type="primary"
                            plain
                            size="small"
                            @click="addInside(scope.row)"
                          >
                            执行
                          </el-button>
                        </span>
                        <span
                          v-if="
                            scope.row.stepIndex != '3' &&
                            scope.row.stepStatus === '1'
                          "
                        >
                          <span
                            style="
                              display: inline-block;
                              width: 8px;
                              height: 8px;
                              margin: 1%;
                              border-radius: 50%;
                              background: #6aabfb;
                            "
                          ></span>
                          <span>已执行</span>
                        </span>
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="内容"
                      prop="stepContent"
                      width="300"
                    ></el-table-column>
                    <el-table-column label="详情" prop="">
                      <template slot-scope="scope">
                        <span
                          v-if="
                            scope.row.stepIndex == '5' ||
                            scope.row.stepIndex == '1' ||
                            scope.row.stepIndex == '8'
                          "
                        >
                          <el-button
                            type="text"
                            size="small"
                            @click="checkDetail(scope.row)"
                          >查看</el-button
                          >
                        </span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </div>
            </el-tab-pane>
            <el-tab-pane label="作业日志" name="jobLogs">
              <div class="joblogBox">
              <div class="joblogCon">
                  <!--顶部日志内容-->
                <div class="joblogTop">
                  <p v-for="(item, index) in filteredJoblogList" :key="index">
                    <span v-html="renderLogContent(item.operationContent)"></span>
                  </p>
                </div>
                  <!-- 底部过滤条件-->
                <div class="bottomCheck">
                  <el-checkbox
                    :indeterminate="isIndeterminate"
                    :checked="checkAlljoblog"
                    @change="handleCheckAllChange"
                    style="margin:3px 25px;font-size: 16px"

                  >
                    全部
                  </el-checkbox>

                  <!-- 多选项 -->
                  <el-checkbox-group
                    v-model="checkedJoblogs"
                    @change="handleCheckedJoblogsChange"
                    class="big-checkbox"
                  >
                    <el-checkbox
                      v-for="item in jobLogtypes"
                      :label="item.value"
                      :key="item.value"
                      class="big-checkbox"
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <el-button style="float: right" type="primary" @click="finshJobticket"
          >结束作业
          </el-button>
          <el-button
            style="float: right; margin-right: 10px"
            type="danger"
            @click="cancelJobticket"
          >取消作业
          </el-button>
        </el-card>
      </div>
    </div>
    <!-- 作业日志检索内容中未选中类型的新消息-->
    <el-dialog
      :visible.sync="JoblogdialogVisible"
      title="新日志提醒"
      width="50%"
      :close-on-click-modal="true"
    >
      <div class="joblogTop1">
        <p>
          <span v-html="renderLogContent(dialogLog.operationContent)"></span>
        </p>
      </div>
    </el-dialog>
    <!-- 添加或修改外部人员对话框 -->
    <el-dialog :visible.sync="open" width="1400px" append-to-body>
      <div slot="title" class="dialog-title">
        <i></i>
        <span class="title">添加人员</span>
      </div>
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :rules="rules"
        label-width="70px"
      >
        <el-row>
          <el-form-item label="上锁人" prop="locker">
            <el-select
              v-model="dialogForm.locker"
              placeholder="上锁人"
              clearable
              style="width: 230px"
              @change="handlelockerChage"
              @clear="handlelockerClear"
            >
              <el-option
                v-for="dict in this.listLockerOption"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-row>

        <el-row style="display: flex; justify-content: space-between">
          <el-col :span="7">
            <h3>选中人员列表</h3>
            <el-table :data="AllUserTable" stripe height="400">
              <!--              <el-table-column type="selection" width="55" align="center"/>-->
              <!--            <el-table-column prop="userId" label="外部人员Id">-->
              <!--            </el-table-column>-->
              <el-table-column prop="userName" label="姓名">
                <template slot-scope="scope">
                  <span style="color: #2a87ff">{{ scope.row.userName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="userType" label="来源">
                <template slot-scope="scope">
                  <span style="color: #2a87ff">{{
                      scope.row.userType == '0' ? '内部' : '外部'
                    }}</span>
                </template>
              </el-table-column>
              <!--              <el-table-column label="操作" width="80">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-button-->
              <!--                    v-no-more-click-->
              <!--                    @click.native.prevent="-->
              <!--                      deleteRow(scope.$index, AllUserTable)-->
              <!--                    "-->
              <!--                    type="text"-->
              <!--                    size="small"-->
              <!--                  >-->
              <!--                    移除-->
              <!--                  </el-button>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-col>
          <!--         内部共锁人-->
          <el-col :span="7">
            <h3>内部共锁人列表</h3>
            <el-table
              :data="insideTableData"
              stripe
              ref="insideTable"
              height="400"
              @selection-change="InSelectionChange"
              :header-cell-style="{
                'background-color': '#afccfd',
                color: 'white',
              }"
            >
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column
                prop="userId"
                label="内部人员Id"
              ></el-table-column>
              <el-table-column prop="nickName" label="姓名">
                <template slot-scope="scope">
                  <span style="color: #2a87ff">{{ scope.row.nickName }}</span>
                </template>
              </el-table-column>
              <!-- 添加搜索条件的列 -->
              <el-table-column label="搜索">
                <template slot="header">
                  <el-input
                    placeholder="搜索姓名"
                    v-model="insideSearchQuery"
                    size="small"
                    @input="filterInsideTable"
                    style="width: 90px"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-col :span="7">
            <h3>外部共锁人列表</h3>
            <el-table
              :data="outsideTableData"
              stripe
              ref="outsideTable"
              height="400"
              @selection-change="OutSelectionChange"
              :header-cell-style="{
                'background-color': '#fc3d49',
                color: 'white',
              }"
            >
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column
                prop="userId"
                label="外部人员Id"
              ></el-table-column>
              <el-table-column prop="nickName" label="姓名">
                <template slot-scope="scope">
                  <span style="color: #2a87ff">{{ scope.row.nickName }}</span>
                </template>
              </el-table-column>
              <!-- 添加搜索条件的列 -->
              <el-table-column label="搜索">
                <template slot="header">
                  <el-input
                    placeholder="搜索姓名"
                    v-model="outsideSearchQuery"
                    size="small"
                    @input="filterOutsideTable"
                    style="width: 90px"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="confirmAddUser"
        >确认
        </el-button>
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    第五步查看作业详情弹窗-->
    <el-dialog :visible.sync="FiveDetailvisible" width="1000px" append-to-body>
      <el-row>
        <el-card class="box-cardStatus">
          <div slot="header" class="clearfix">
            <span style="font-weight: bolder">作业状态</span>
          </div>
          <el-table
            :data="jobTicket"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column label="作业编号" prop="ticketId">
            </el-table-column>
            <el-table-column label="作业名称" prop="ticketName">
            </el-table-column>
            <el-table-column label="状态" align="center" prop="ticketStatus">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.ticket_status"
                  :value="scope.row.ticketStatus"
                />
              </template>
            </el-table-column>
            <el-table-column label="上锁钥匙" prop="lockKeyName">
            </el-table-column>
            <el-table-column label="解锁钥匙" prop="colockKeyName">
            </el-table-column>
          </el-table>
        </el-card>
      </el-row>
      <el-row>
        <el-col :span="7" style="height: 400px">
          <el-card class="box-card1">
            <div slot="header" class="clearfix">
              <span style="font-weight: bolder">人员状态</span>
            </div>
            <el-table :data="lockUserList">
              <el-table-column label="上锁人" prop="userName"></el-table-column>
              <el-table-column label="状态" align="center" prop="jobStatus">
                <template slot-scope="scope">
                  <div
                    class="box"
                    style="
                      width: 30px;
                      height: 30px;
                      border: 1px solid black;
                      background-color: white;
                      margin: 0 auto;
                    "
                  >
                    <span
                      v-if="
                        scope.row.jobStatus == 0 ||
                        scope.row.jobStatus == 1 ||
                        scope.row.jobStatus == 2 ||
                        scope.row.jobStatus == 3
                      "
                    ></span>
                    <!-- 显示错号 -->
                    <span
                      v-else-if="scope.row.jobStatus == 4"
                      style="font-size: 20px; line-height: 30px"
                    >🔒</span
                    >
                    <!-- 显示对号 -->
                    <span
                      v-else-if="scope.row.jobStatus == 5"
                      style="font-size: 20px; line-height: 30px"
                    >✓</span
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <el-card class="box-cardgsr">
            <el-table :data="colockUserList">
              <el-table-column label="共锁人" prop="userName"></el-table-column>
              <el-table-column label="状态" align="center" prop="jobStatus">
                <template slot-scope="scope">
                  <div
                    class="box"
                    style="
                      width: 30px;
                      height: 30px;
                      border: 1px solid black;
                      background-color: white;
                      margin: 0 auto;
                    "
                  >
                    <span
                      v-if="
                        scope.row.jobStatus == 0 ||
                        scope.row.jobStatus == 1 ||
                        scope.row.jobStatus == 2 ||
                        scope.row.jobStatus == 3
                      "
                    ></span>
                    <!-- 显示错号 -->
                    <span
                      v-else-if="scope.row.jobStatus == 4"
                      style="font-size: 20px; line-height: 30px"
                    >🔒</span
                    >
                    <!-- 显示对号 -->
                    <span
                      v-else-if="scope.row.jobStatus == 5"
                      style="font-size: 20px; line-height: 30px"
                    >✓</span
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card2">
            <div slot="header" class="clearfix">
              <span style="font-weight: bolder">隔离点状态</span>
            </div>
            <el-table :data="ticketPointsList">
              <el-table-column label="隔离点" prop="pointName" width="80">
              </el-table-column>
              <el-table-column label="状态" align="center" prop="pointStatus">
                <template slot-scope="scope">
                  <div
                    class="box"
                    style="
                      width: 30px;
                      height: 30px;
                      border: 1px solid black;
                      background-color: white;
                      margin: 0 auto;
                    "
                  >
                    <span v-if="scope.row.pointStatus == 0" style=""></span>
                    <!-- 显示错号 -->
                    <span
                      v-else-if="scope.row.pointStatus == 1"
                      style="font-size: 20px; line-height: 30px"
                    >🔒</span
                    >
                    <!-- 显示对号 -->
                    <span
                      v-else-if="scope.row.pointStatus == 2"
                      style="font-size: 20px; line-height: 30px"
                    >✓</span
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="挂锁名称" prop="lockName">
              </el-table-column>
              <el-table-column
                label="锁具机构"
                prop="locksetName"
              ></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!--    第八步查看影响作业票-->
    <el-dialog
      :visible.sync="EightDetailvisible"
      title="受影响作业票"
      width="650px"
      append-to-body
    >
      <el-table :data="AffectedTickets">
        <el-table-column label="作业票编号" prop="ticketId"></el-table-column>
        <el-table-column label="作业票名称" prop="ticketName" width="220">
        </el-table-column>

        <el-table-column label="作业票状态" prop="ticketStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.ticket_status"
              :value="scope.row.ticketStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="作业票类型" prop="ticketType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sop_type"
              :value="scope.row.ticketType"
            />
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!--    锁定站放大按钮呈现diaolog-->
    <el-dialog
      :visible.sync="LockDetailvisible"
      title="锁定站信息"
      width="1200px"
      append-to-body
      class="elDialog"
    >
      <!--      这里为了没有地图数据而设置的-->
      <el-row>
        <el-col :span="6">
          <div>
            <el-table :data="selectPointList" :show-header="false" style="width: 200px;height: 175px;">
              <el-table-column
                prop="pointName"
                label=""
              ></el-table-column>
              <el-table-column
                prop="remark"
                label=""
              ></el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col :span="18">
          <LockDetail
            :machineryId="this.machineryId"
          ></LockDetail>
        </el-col>
      </el-row>
    </el-dialog>
    <!--    地图数字打开正在执行作业票页面-->
    <el-dialog
      :visible.sync="ticketVisible"
      :title="`${currentWorkstationName} 进行中的作业`"
      width="700px"
      append-to-body
      class="elDialog"
    >
      <el-table :data="TicketListPage[currentWorkstationId] || []">
        <el-table-column label="岗位" prop="workstationId" width="70">
          <template slot-scope="scope">
            {{ currentWorkstationName }}
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="ticketName" width="50">
          <template slot-scope="scope" style="width: 50px">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="图标" prop="ticketType" width="100">
          <template slot-scope="scope">
            <img :src="imageMap[scope.row.ticketType]" style="width:30px;height:30px"/>
          </template>
        </el-table-column>
        <el-table-column label="作业票名称" prop="ticketName"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button type="text" @click="handleTicketClick(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { listMarsDept } from '@/api/system/marsdept'
import { getTechnologyInfo, listTechnology } from '@/api/system/machinery'
import Template from '@/views/print/printtemplate/list.vue'
import { getIsMarsSopPage } from '@/api/mes/sop/sopindex'
import {
  addJobTicket,
  addJobUsers,
  getJobTicketInfo,
  getStepEight,
  getStepInfo,
  getWorkstationTicketList,
  listJobTicket,
  selectSopTypeByMachineryId,
  updateJobStep,
  updateJobToCancel,
  updateJobToFinish,
  getIsTicketOperLogPage
} from '@/api/mes/job/job'
import MapData from '@/views/mes/job/jobm/Mapdata.vue'
import { getUserList } from '@/api/mes/workCard'
import { getJobPlayTicketInfo } from '@/api/mes/jobplay/jobplay'
import { selectIsLotoStationById, selectLotoMapById } from '@/api/mes/lotoStation/lotoStation'
import LockDetail from '@/views/mes/job/jobm/LockDetail.vue'
import { selectIsMapById } from '@/api/system/mapconfig'
import { getIsMapPointPage } from '@/api/system/mappoint'
import { getIsSystemAttributeByKey } from '@/api/system/configuration'
import { getDicts } from '@/api/system/dict/data'
import {connectWebsocket} from "@/utils/websocket";
import { nextTick } from 'vue';
const joblogsOptions = [];
export default {
  name: 'NewSop',
  components: { Template, MapData, LockDetail },
  dicts: ['sop_type', 'ticket_status', 'ticket_user_type'],
  data() {
    return {
      ticketVisible: false,//正在进行作业票的弹窗标记
      currentWorkstationId: null,//当前点击的岗位Id
      currentWorkstationName: null,//当前点击的岗位的名称
      jobconfig: null,//接口传递地图与宽高数据
      jobconfigPoint: null,//接口传递的岗位位置信息
      imageMap: {
        0: 'ticketType0', //维修
        1: 'ticketType1', //Pm
        2: 'ticketType2', //开收班
        3: 'ticketType3', //清洁
        4: 'ticketType4',  //换产
        5: 'ticketType5'//更多
      },
      tabPosition: 'first',
      selectedOption: '',
      selectedRow: null, //设备工艺 单选表格
      marsSopPage: [], //岗位对应sop列表--现在准备存放设备工艺 而不是选设备工艺的sop
      technologyList: [], //设备工艺表格数据
      marsSopTitle: '', //岗位后 对应展示sop
      marsDeptList: [],
      listLockerOption: [], //上锁人下拉数据
      form: null, //存储选中的设备工艺sop列表数据
      machineryImg: null, //第三步作业执行渲染设备工艺图片
      machineryId: null, //第三步作业执行渲染电柜的数据
      EightStepForm: null, //八大步骤详细内容
      ticketId: null, //新增之后 编辑需要使用的id
      open: false, //添加人员
      openColocker: false, //添加内外部人员
      outsideTableData: [], //外部人员表格
      insideTableData: [], //内部人员表格
      insideTableDataOrign: [], //内部原始数据
      outsideTableDataOrign: [], //外部原始数据
      selectedInsideRows: [], // 存储选中的内部人员的 userId
      selectedOutsideRows: [], // 存储选中的外部人员的 userId
      insideSearchQuery: '', // 内部搜索条件
      outsideSearchQuery: '', // 外部搜索条件
      AllUserTable: [], //所有选中人员列表
      dialogForm: {
        nickName: '',
        username: ''
      },
      // 弹出层标题
      title: '',
      // 弹框中显示的form表单内容
      newticketUserDTOList: [], //为了上锁人单独传递数据
      FiveDetailvisible: false, //第五步详情弹窗
      ticketPointsList: [], //第五步详情的隔离点信息
      colockUserList: [], //第五步详情的共锁人信息
      lockUserList: [], //第五步详情的上锁人信息
      jobTicket: [], //第五步详情的作业票信息
      TicketListPage: [], //作业票列表page接口传递的数据 底图循环渲染图标 RR岗位作业票
      selectPointList: [], //隔离点选中的表格渲染
      scaleFactor: 1, // 缩放比例，初始值为1
      EightDetailvisible: false, //第八步受影响作业票
      AffectedTickets: [], //第八步查看详情信息表格
      sopTypeOption: [],
      sopId: null,
      workstationId: null, //岗位Id
      rules: {
        locker: [
          { required: true, message: '上锁人不能为空', trigger: 'change' }
        ]
      },
      tableVisible: true, //表格显示
      LockDetailvisible: false, //锁定站详情'
      deptXLGPosition: {
        left: 500,
        top: 260,
        width: 65,
        height: 25
      },
      deptCCOPosition: {
        left: 670,
        top: 480,
        width: 65,
        height: 25
      },
      loading: false,
      LoadStatus: '',//给LockDetail加弹窗加载
      activeName: 'eightSteps', // 默认展示“八大步骤”
      joblogList:[],//原始作业日志数据列表
      filteredJoblogList: [], // 过滤后日志
    //   作业日志底部查询
      isIndeterminate: false,
      checkedJoblogs: [],
      jobLogtypes: [],
      joblogsOptions: [], // 只存所有 dictValue，用于全选逻辑,
      checkAlljoblog: true,
      JoblogdialogVisible: false,
      dialogLog: '',
    }
  },
  computed: {
    isStepFourExecuted() {
      const stepFour = this.EightStepForm.find((step) => step.stepIndex == '4')
      return stepFour && stepFour.stepStatus === '1'
    },
  },
  watch: {
    tabPosition: function(val, oldVal) {
      if (val == 'first') {
        this.sopTypeOption = []
        this.technologyList = []
        this.sopId = null
        this.getList()
      }
      if (val == 'third') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 3000)
      }
    },
    'dialogForm.locker': function(val) {
      if (val) {
        this.handlelockerChage(val)
        console.log('我制定了')
      }
    },
    "ticketId": function(val) {
      if(val){
        console.log(this.ticketId,val,'JIANRT')
        this.initWebSocket()

      }
    }
  },

  mounted() {
    this.getList()
  },




  methods: {

    // 正在进行中作业票点击数字打开弹窗
    handleTicketDialogVisible(entityId, entityName) {
      this.ticketVisible = true
      this.currentWorkstationId = entityId
      this.currentWorkstationName = entityName
    },

    // 锁定站信息部分表格收缩
    // handleChangeTable() {
    //   this.tableVisible = !this.tableVisible
    // },
    // 锁定站进入详细页面
    goLockDetail() {
      // this.$router.push({
      //   name:'LockDetail',params: { machineryId: this.machineryId }
      // },)
      this.LockDetailvisible = true
      this.LoadStatus = this.$loading({
        target: '.elDialog .el-dialog '
      })
      setTimeout(() => {
        this.LoadStatus.close()
      }, 3000)

    },
    // 内部人员搜索
    filterInsideTable() {
      const query = this.insideSearchQuery.trim().toLowerCase()
      const filteredData = this.insideTableDataOrign.filter((item) =>
        item.nickName.toLowerCase().includes(query)
      )
      this.insideTableData = filteredData

      // 如果输入框为空或null，回显选中状态
      if (!this.insideSearchQuery) {
        // 筛选完毕后，勾选 AllUserTable 中有的用户
        this.insideTableData.forEach((user) => {
          const matchingUser = this.AllUserTable.find(
            (u) => u.userId == user.userId
          )

          console.log('Matching User:', matchingUser) // 输出匹配结果
          if (matchingUser) {
            this.$nextTick(() => {
              console.log(`Selecting user: ${user.nickName}`)
              this.$refs.insideTable.toggleRowSelection(user, true)
            })
          } else {
            this.$nextTick(() => {
              console.log(`Deselecting user: ${user.nickName}`)
              this.$refs.insideTable.toggleRowSelection(user, false)
            })
          }
        })
      }
    },

    // 外部人员搜索
    filterOutsideTable() {
      const query = this.outsideSearchQuery.trim().toLowerCase()
      const filteredData = this.outsideTableDataOrign.filter((item) =>
        item.nickName.toLowerCase().includes(query)
      )
      this.outsideTableData = filteredData

      // 如果输入框为空或null，回显选中状态
      if (!this.outsideSearchQuery) {
        // 筛选完毕后，勾选 AllUserTable 中有的用户
        this.outsideTableData.forEach((user) => {
          const matchingUser = this.AllUserTable.find(
            (u) => u.userId == user.userId
          )

          console.log('Matching User:', matchingUser) // 输出匹配结果
          if (matchingUser) {
            this.$nextTick(() => {
              console.log(`Selecting user: ${user.nickName}`)
              this.$refs.outsideTable.toggleRowSelection(user, true)
            })
          } else {
            this.$nextTick(() => {
              console.log(`Deselecting user: ${user.nickName}`)
              this.$refs.outsideTable.toggleRowSelection(user, false)
            })
          }
        })
      }
    },
    handleTicketClick(data) {
      console.log(data, '查看作业票详情')
      this.ticketVisible = false
      this.ticketId = data.ticketId
      this.tabPosition = 'third'
      this.workstationId = data.workstationId

      getStepInfo(this.ticketId).then((res) => {
        this.EightStepForm = res.data
        console.log(res, '作业票-详细信息')
      })
      this.machineryId = data.machineryId
      // 获取设备工艺图
      getTechnologyInfo(data.machineryId).then((res) => {
        this.machineryImg = res.data.machineryImg
        // 获取电柜选中隔离点
        const lotoId = res.data.lotoId
        const selectPointsIds = res.data.pointIdList

        selectLotoMapById(lotoId).then((response) => {
          console.log(response, '电柜信息--NewMarsJob')
          this.selectPointList = response.data.filter((item) =>
            selectPointsIds.includes(item.pointId)
          )
          console.log(this.selectPointList, '拿到的选中隔离点数据')
        })
      })
    },
    getList() {
      const data = {
        pages: 1,
        size: -1
      }
      getWorkstationTicketList(data).then((res) => {
        console.log(res, '查看-正在进行中作业票列表')
        let ticketsByWorkstation = {}

        res.data.forEach((ticket) => {
          if (!ticketsByWorkstation[ticket.workstationId]) {
            ticketsByWorkstation[ticket.workstationId] = []
          }
          ticketsByWorkstation[ticket.workstationId].push(ticket)
        })

        this.TicketListPage = ticketsByWorkstation

      })
      const sysAttrKey1 = 'icon.permit.maintenance'//维修
      const sysAttrKey2 = 'icon.permit.pm'//Pm
      const sysAttrKey3 = 'icon.permit.shift'//开收班
      const sysAttrKey4 = 'icon.permit.clean'//清洁
      const sysAttrKey5 = 'icon.permit.changeover'//换产
      const sysAttrKey6 = 'icon.permit.more'//更多
      Promise.all([
        getIsSystemAttributeByKey(sysAttrKey1),
        getIsSystemAttributeByKey(sysAttrKey2),
        getIsSystemAttributeByKey(sysAttrKey3),
        getIsSystemAttributeByKey(sysAttrKey4),
        getIsSystemAttributeByKey(sysAttrKey5),
        getIsSystemAttributeByKey(sysAttrKey6)
      ]).then((responses) => {
        this.imageMap[0] = responses[0].data.sysAttrValue // 维修
        this.imageMap[1] = responses[1].data.sysAttrValue // Pm
        this.imageMap[2] = responses[2].data.sysAttrValue // 开收班
        this.imageMap[3] = responses[3].data.sysAttrValue // 清洁
        this.imageMap[4] = responses[4].data.sysAttrValue // 换产
        this.imageMap[5] = responses[5].data.sysAttrValue//更多
        console.log(this.imageMap, 'imageMap')
      })
      // 这里注释掉是为了 初始化跳转数据为空
      const data1 = {
        pages: 1,
        size: -1,
        machineryType: '工艺'
      }
      // listTechnology(data1).then((res) => {
      //   console.log(res, 'technologyList')
      //   this.technologyList = res.data.records
      // })
      listMarsDept(data).then((res) => {
        console.log(res, 'marsDeptList')
        this.marsDeptList = res.data.records
      })
      // 获取基础数据里配置的作业票地图获取mapId
      const sysAttrKey = 'sys.map.permit'
      getIsSystemAttributeByKey(sysAttrKey).then((response) => {
        const sysAttrValue = response.data.sysAttrValue
        // 这里获取全局配置地图参数里的作业票地图
        selectIsMapById(sysAttrValue).then((res) => {
          console.log(res, '作业票地图 图片数据')
          this.jobconfig = res.data
        })
      })

      const dataMap = {
        pages: 1,
        size: -1,
        mapId: 1
      }
      getIsMapPointPage(dataMap).then((res) => {
        console.log(res, '作业票地图岗位位置信息接口')
        this.jobconfigPoint = res.data
      })
    },
    // sop类型 el-radio
    handleSopchange(data) {
      const sopType = this.sopTypeOption.find((item) => item.label == data)
      const data1 = {
        pages: 1,
        size: -1,
        machineryId: this.machineryId,
        sopType: sopType.value
      }
      getIsMarsSopPage(data1).then((res) => {
        console.log(res, 'SopPage')
        this.sopId = res.data.records[0].sopId
      })
    },

    // 作业票切换
    handelChange(val, workstationId, workstationName) {
      console.log(val)

      this.marsSopTitle = workstationName
      this.workstationId = workstationId
      if (workstationId) {
        const data = {
          pages: 1,
          size: -1,
          workstationId: workstationId,
          machineryType: '工艺'
        }
        listTechnology(data).then((res) => {
          console.log(res, '设备工艺---列表')
          this.technologyList = res.data.records
        })
        // getIsMarsSopPage(data).then((res) => {
        //   console.log(res, 'SopPage')
        //   this.marsSopPage = res.data.records
        // })
      }
      if (!this.sopId && val == 'third') {
        this.$message.error('请先选择对应设备工艺或sop类型')
        return
      }
      this.tabPosition = val
      if (val == 'third') {
        this.selectedOption = ''
        this.sopTypeOption = []
        console.log(this.sopId, 'this.sopId')
        if (this.sopId) {
          const data = {
            sopId: this.sopId
          }
          addJobTicket(data).then((res) => {
            console.log(res, '作业票新增')
            this.$message.success('作业开始执行')
            this.ticketId = res.data
            getStepInfo(this.ticketId).then((res) => {
              this.EightStepForm = res.data
              console.log(res, '作业票-详细信息')
            })
            // 获取设备工艺图
            getTechnologyInfo(this.machineryId).then((res) => {
              this.machineryImg = res.data.machineryImg
              // 获取电柜选中隔离点
              const lotoId = res.data.lotoId
              const selectPointsIds = res.data.pointIdList

              selectLotoMapById(lotoId).then((response) => {
                console.log(response, '电柜信息--NewMarsJob')
                this.selectPointList = response.data.filter((item) =>
                  selectPointsIds.includes(item.pointId)
                )
                console.log(this.selectPointList, '拿到的选中隔离点数据')
              })
            })
          })
        }
      }
    },

    // 单选选中数据
    handleSelectionChange(selection) {
      console.log(selection, 'mars设备工艺表格多选拿到的数据')

      this.form = selection
      this.machineryId = selection.machineryId
      getTechnologyInfo(selection.machineryId).then((res) => {
        this.machineryImg = res.data.machineryImg
      })
      selectSopTypeByMachineryId(selection.machineryId).then((res) => {
        console.log(res, 'SopTypeByMachineryId')
        this.sopTypeOption = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      })
    },
    // 添加内部人员
    addInside(row) {
      if (row.stepIndex == '3') {
        this.dialogForm.locker = ''
        this.AllUserTable = []
        this.newticketUserDTOList = []

        const roleId = this.dict.type.ticket_user_type.find(
          (item) => item.label == 'jtlocker'
        ) //利用字典值来记录上锁人 共锁人 方便如果修改了值 直接系统更改
        const query1 = {
          pageSize: 10000,
          pageNum: 1,
          workstationId: this.workstationId,
          roleId: roleId.value,
          unitId: 9
        }
        // 上锁人赋值  上锁人 共锁人都要遵循 属于当前工艺 当前作业负责人或者执行人的角色属性
        getUserList(query1).then((res) => {
          // 上锁人下拉数据
          this.listLockerOption = res.rows.map((item) => ({
            label: item.nickName,
            value: item.userId
          }))
        })
        const roleIdColocker = this.dict.type.ticket_user_type.find(
          (item) => item.label == 'jtcolocker'
        ) //利用字典值来记录上锁人 共锁人 方便如果修改了值 直接系统更改
        const query = {
          pageSize: 10000,
          pageNum: 1,
          workstationId: this.workstationId,
          roleId: roleIdColocker.value
        }
        // 共锁人赋值
        getUserList(query).then((res) => {
          // 内部共锁人
          this.insideTableData = res.rows.filter((item) => item.unitId == 9)
          // 外部共锁人
          this.outsideTableData = res.rows.filter((item) => item.unitId != '9')

          // 获取已分配人员数据
          getJobTicketInfo(this.ticketId).then((res) => {
            const assignedUsers = res.data.jobTicketUserList || []
            console.log(assignedUsers, '已分配人员')

            this.dialogForm.locker = assignedUsers
              .filter((item) => item.userRole == 'jtlocker')
              .map((item) => item.userName)

            const newUser = res.data.jobTicketUserList.filter(
              (item) => item.userRole == 'jtlocker'
            )
            this.newticketUserDTOList = [
              ...this.newticketUserDTOList,
              ...newUser
            ]
            // 更新内部和外部用户的选中状态
            this.$nextTick(() => {
              // 手动选中内部人员
              this.insideTableData.forEach((user) => {
                const isAssigned = assignedUsers.some(
                  (assigned) =>
                    assigned.userId == user.userId &&
                    assigned.userType == '0' &&
                    assigned.userRole !== 'jtlocker'
                )
                if (isAssigned) {
                  this.$refs.insideTable.toggleRowSelection(user, true)
                }
              })

              // 手动选中外部人员
              this.outsideTableData.forEach((user) => {
                const isAssigned = assignedUsers.some(
                  (assigned) =>
                    assigned.userId == user.userId &&
                    assigned.userType == '1' &&
                    assigned.userRole !== 'jtlocker'
                )
                if (isAssigned) {
                  this.$refs.outsideTable.toggleRowSelection(user, true)
                }
              })
              this.insideTableDataOrign = [...this.insideTableData]
              this.outsideTableDataOrign = [...this.outsideTableData]

              this.open = true
            })
          })
        })
      } else {
        const data = {
          stepId: row.stepId,
          stepStatus: '1'
        }
        updateJobStep(data).then((res) => {
          this.$message.success('执行成功')
          getStepInfo(this.ticketId).then((res) => {
            this.EightStepForm = res.data
            console.log(res, '作业票-详细信息')
          })
        })
      }
    },

    // 上锁人下拉选择change事件
    handlelockerChage(val) {
      console.log(val, '上锁人chage')
      if (val) {
        // 操作选中角色发生变化
        this.newticketUserDTOList = []
        this.$set(this.dialogForm, this.dialogForm.locker, val)
      } else {
        this.$set(this.dialogForm, this.dialogForm.locker, val)
      }
      this.$forceUpdate()
      const user = this.listLockerOption.find((item) => item.value == val)

      if (user && this.dialogForm.locker !== '') {
        const existingUser = this.listLockerOption.find(
          (u) => u.userName === user.label
        )
        if (!existingUser) {
          this.newticketUserDTOList.push({
            userName: user.label,
            userId: user.value,
            userType: 0,
            userRole: 'jtlocker'
          })

          console.log(this.newticketUserDTOList, '用户')
        } else {
          // console.log('用户已存在', user.label)
        }
      }
    },
    handlelockerClear() {
      this.newticketUserDTOList = []
      console.log(this.newticketUserDTOList, '清除后的用户')
    },
    InSelectionChange(selection) {
      // 移除未选中的内部用户
      this.AllUserTable = this.AllUserTable.filter(
        (user) =>
          user.userType !== 0 ||
          selection.some((item) => item.userId === user.userId)
      )

      // 添加新的内部用户
      selection.forEach((item) => {
        if (
          !this.AllUserTable.some(
            (user) => user.userId === item.userId && user.userType === 0
          )
        ) {
          this.AllUserTable.push({
            userName: item.nickName,
            userId: item.userId,
            userType: 0,
            userRole: 'jtcolocker'
          })
        }
      })

      console.log(this.AllUserTable, '内部人员')
    },

    OutSelectionChange(selection) {
      // 移除未选中的外部用户
      this.AllUserTable = this.AllUserTable.filter(
        (user) =>
          user.userType !== 1 ||
          selection.some((item) => item.userId === user.userId)
      )

      // 添加新的外部用户
      selection.forEach((item) => {
        if (
          !this.AllUserTable.some(
            (user) => user.userId === item.userId && user.userType === 1
          )
        ) {
          this.AllUserTable.push({
            userName: item.nickName,
            userId: item.userId,
            userType: 1,
            userRole: 'jtcolocker'
          })
        }
      })

      console.log(this.AllUserTable, '外部人员')
    },
    confirmAddUser() {
      const data = {
        ticketId: this.ticketId,
        ticketUserDTOList: [...this.AllUserTable, ...this.newticketUserDTOList]
      }
      console.log(data, '添加人员')
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          addJobUsers(data).then((res) => {
            console.log(res, '添加人员')
            if (res.data) {
              this.$message.success('分配人员成功')
              this.open = false
              this.AllUserTable = []
              this.dialogForm.locker = ''
              getStepInfo(this.ticketId).then((res) => {
                this.EightStepForm = res.data
                console.log(res, '作业票-详细信息')
              })
            }
          })
        }
      })
    },
    // 人员列表删除
    deleteRow(index, rows) {
      console.log(index, rows, '删除的行')
      const deletedItem = rows[index] // 获取要删除的项
      rows.splice(index, 1) // 从显示的列表中删除

      const formIndex = this.dialogForm.ticketUserDTOList.findIndex(
        (item) => item.userName == deletedItem.userName
      )
      if (formIndex !== -1) {
        this.dialogForm.ticketUserDTOList.splice(formIndex, 1) // 从 form.ticketUserDTOList 中删除
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.FiveDetailvisible = false
      this.EightDetailvisible = false
    },
    // 作业票结束
    finshJobticket() {
      const data = {
        ticketId: this.ticketId
      }
      updateJobToFinish(data).then((res) => {
        console.log(res, '结束作业票')
        if (res.data) {
          this.$message.success('作业票结束')
          this.tabPosition = 'first'
          this.getList()
        }
      })
    },
    // 作业票取消
    cancelJobticket() {
      const data = {
        ticketId: this.ticketId
      }
      updateJobToCancel(data).then((res) => {
        console.log(res, '取消作业票')
        if (res.data) {
          this.$message.success('作业票取消')
          this.tabPosition = 'first'
          this.getList()
        }
      })
    },
    //   查看详情八大步骤
    checkDetail(row) {
      if (row.stepIndex == '5') {
        this.FiveDetailvisible = true
        let ticketId = this.ticketId
        getJobPlayTicketInfo(ticketId).then((res) => {
          console.log(res, '作业执行详细信息')
          this.jobTicket = [res.data.jobTicket].map((item) => ({
            ...item,
            lockKeyName: res.data.lockKeyName,
            colockKeyName: res.data.colockKeyName
          }))
          this.lockUserList = res.data.lockUserList
          this.colockUserList = res.data.colockUserList
          this.ticketPointsList = res.data.ticketPointsList
        })
      } else if (row.stepIndex == '8') {
        let ticketId = this.ticketId
        this.EightDetailvisible = true
        getStepEight(ticketId).then((res) => {
          console.log(res, '第八步查看作业票数据')
          this.AffectedTickets = res.data
        })
      } else if (row.stepIndex == '1') {
        this.$router.push({
          path: '/mes/dv/technology/technologyDetail/CraftDetail',
          query: { machineryId: this.machineryId }
        })
      }
    },
  //   作业日志连接socket获取数据
    initWebSocket(){
      const code= this.ticketId;
      const address='sys.websocket.address'
      getIsSystemAttributeByKey(address).then((res) => {
        // console.log(res, 'websocket地址');
        this.websocketAddress = res.data.sysAttrValue
        const isLocalDev = window.location.hostname === 'localhost'

        const baseAddress = isLocalDev
          ? 'ws://192.168.0.10:9190'
          : this.websocketAddress;
        connectWebsocket(
          `${baseAddress}/websocket/jobTicketLog/${code}`,
          { w: 'S' },
          async (res) => {
            console.log(res, 'websocket接收服务器的作业日志数据');
            if (res !== 'heartbeat') {
              // 判断是否需要弹窗显示
              await this.onNewSocketLog(res);  // 👈传入最新的 WebSocket 消息
              await this.getJoblogs(); // 抽出专用接口函数
            }
          },
          (err) => {
            console.log('断开重连');
          }
        );
      }).catch(err => {
        console.error('获取WebSocket地址失败:', err);
      });
    },


  //   查询作业日志接口获取
    async getJoblogs() {
      const joblogdata = {
        ticketId: this.ticketId,
        current: 1,
        size: -1,
      };
      const res = await getIsTicketOperLogPage(joblogdata);
      // console.log('接口返回日志：', res.data.records);
      this.joblogList = res.data.records;
      // ✨强制刷新筛选后的列表
      this.filterJoblogs();
    },


    //   作业日志tab点击事件
    async handleTabClick(tab) {
      if (tab.name === 'jobLogs') {
        await this.getJoblogs()
      }

      const dictRes = await getDicts('job_log_type');
      const dicts = dictRes.data.map(item => ({
        label: item.dictLabel,
        value: String(item.dictValue), // 确保是字符串类型
      }));

      this.jobLogtypes = dicts;
      this.joblogsOptions = dicts.map(item => item.value);
      this.checkedJoblogs = [...this.joblogsOptions]; // 初始化全选
      console.log(this.checkAlljoblog,'选中状态');
      this.checkAlljoblog = true;
      console.log(this.checkAlljoblog,'是否选中');
      this.isIndeterminate = false;
      this.filterJoblogs();
    },

    // 作业日志页面数据展示样式分割
    renderLogContent(content) {
      if (!content) return ''
      // 第一步：先处理 <url>[label] 为 <img> + label
      content = content.replace(/<([^>]+)>\[([^\]]+)\]/g, (match, url, label) => {
        return `<img src="${url}" style="height: 25px; vertical-align: middle;"> <span style="color:#007BFF;margin: 0 3px">${label}</span>`
      })
      // 第二步：处理剩下的 [label]，转成蓝色字体
      content = content.replace(/\[([^\]]+)\]/g, '<span style="color:#007BFF;margin: 0 5px">$1</span>')
      return content
    },

    //   作业日志底部筛选功能
    handleCheckedJoblogsChange(val) {
      const checkedCount = val.length;
      this.checkAlljoblog = checkedCount === this.joblogsOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.joblogsOptions.length;

      this.filterJoblogs();
    },
    handleCheckAllChange(val) {
      this.checkedJoblogs = val ? [...this.joblogsOptions] : [];
      this.isIndeterminate = false;
      this.filterJoblogs();
    },

    // 实际日志筛选逻辑
    filterJoblogs() {
      if (this.checkedJoblogs.includes('ALL')) {
        this.filteredJoblogList = this.joblogList;
      } else {
        this.filteredJoblogList = this.joblogList.filter(log =>
          this.checkedJoblogs.includes(String(log.operationType))
        );
      }
    },

  //   作业日志弹框
  parseLogString(logStr) {
    const obj = {};
    const match = logStr.match(/^[^(]+?\((.*)\)$/);
    if (!match) return obj;
    const keyValuePairs = match[1].split(/,\s*(?=\w+=)/); // 处理 "key=value" 中的逗号
    keyValuePairs.forEach(pair => {
      const [key, value] = pair.split('=');
      if (value === 'null') {
        obj[key] = null;
      } else if (!isNaN(value)) {
        obj[key] = Number(value);
      } else {
        obj[key] = value;
      }
  });

  return obj;
},

// 判断某条日志是否在当前筛选之外（即是否未被选中）
    async onNewSocketLog(rawLogStr) {
      // 1. 将字符串解析为对象
      const newLog = this.parseLogString(rawLogStr);

      // 2. 获取当前勾选的类型（都转成字符串）
      const selectedTypes = this.checkedJoblogs.map(String);
      const newLogType = String(newLog.operationType);
      // console.log('新日志类型:', newLogType, '勾选类型:', selectedTypes);
      // 3. 判断是否未被选中 → 弹窗
      if (!selectedTypes.includes(newLogType)) {
        this.dialogLog = newLog;
        this.JoblogdialogVisible = true;
        // console.log('弹框内容:', newLog);
      } else {
        this.JoblogdialogVisible = false;
        // console.log('该类型已勾选，不弹框');
      }
    }

  }
}
</script>


<style scoped lang="scss">
.deptGreen {
  position: absolute;
  min-width: 65px;
  height: 25px;
  background: #70b26f;
  line-height: 25px;
  text-align: center;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  padding: 0 10px;
}

.box-cardStatus {
  width: 850px;
  margin: 15px;
}

.box-card1 {
  width: 250px;
  margin: 15px;
}

.box-cardgsr {
  width: 250px;
  height: auto;
  margin: 15px;
}

.box-card2 {
  width: 560px;
  margin: 15px;
}

.status-container {
  width: 100%;
  height: 100%;
  background: pink;
  display: flex;
}

.box {
  width: 30px;
  height: 30px;
  border: 1px solid #e7e5e5;
  background-color: rgb(209, 77, 77);
}

.error-icon {
  color: red;
  font-weight: bold;
}

.success-icon {
  color: green;
  font-weight: bold;
}

//滚动条的宽度
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  background-color: #e4e4e4;
  border-radius: 6px;
}

//滚动条的滑块
::-webkit-scrollbar-thumb {
  background-color: #a1a3a9;
  border-radius: 6px;
}

div[ref="mapContainer"] {
  transition: transform 0.2s ease;
}

.left-bottom {
  height: 460px;
  // background: blue;
}
//作业日志
.joblogBox {
  width: 100%;
  height: 80%;
  margin: 0 auto 20px;
  box-sizing: border-box;
  //background: pink;
  .joblogCon{
    width: 98%;
    height: 80%;
    margin: auto;
    //background: greenyellow;
    .joblogTop{
      width: 100%;
      height: 600px;
      margin: auto;
      overflow-y: auto;
      //background: cadetblue;
      p{
        font-size: 16px;
        line-height: 20px;
      }
    }
    .bottomCheck{
      width:100%;
      height: 50px;
      line-height: 50px;
      font-size: 23px;
      display: flex;
      margin: auto;
      //background: forestgreen;

      .big-checkbox {
        font-size: 23px; /* 字体大小 */
      }

      /* 调整实际复选框的大小 */
      //.big-checkbox >>> .el-checkbox__inner {
      //  width: 25px;
      //  height: 25px;
      //}
      .big-checkbox ::v-deep(.el-checkbox__inner) {
        width: 25px;
        height: 25px;
      }

      .big-checkbox >>> .el-checkbox__label {
        font-size: 23px;
        padding-left: 8px;
      }
    }


}
}
</style>
