<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: 100%; height: 100%"
          src="@/assets/images/marsBg.png"
          alt=""
        />
        <img
          v-for="(ticket, index) in TicketListPage"
          :key="ticket.ticketId"
          :style="{
            width: '35px',
            height: '35px',
            position: 'absolute',
            cursor: 'pointer',
            // 图标垂直居中
            top: `${deptXLGCenter.top - 53}px`,
            // 图标水平居中，动态计算偏移
            left: `${
              deptXLGCenter.left -
              (TicketListPage.length * 35 + (TicketListPage.length - 1) * 5) /
                2 +
              index * 40
            }px`,
          }"
          :src="require(`@/assets/images/${imageMap[ticket.ticketType]}.png`)"
          alt=""
          @click="handleTicketClick(ticket)"
        />

        <!-- deptCCO 区域的图标 -->
        <img
          v-for="(ticket, index) in COCOTicketListPage"
          :key="ticket.ticketId"
          :style="{
            width: '35px',
            height: '35px',
            position: 'absolute',
            cursor: 'pointer',
            // 图标垂直居中
            top: `${deptCCOCenter.top - 53}px`,
            // 图标水平居中，动态计算偏移
            left: `${
              deptCCOCenter.left -
              (COCOTicketListPage.length * 35 +
                (COCOTicketListPage.length - 1) * 5) /
                2 +
              index * 40
            }px`,
          }"
          :src="require(`@/assets/images/${imageMap[ticket.ticketType]}.png`)"
          alt=""
          @click="handleTicketClick(ticket)"
        />
        <div class="deptXLG" @click="handelChange('second', 8, 'R&R')">R&R</div>
        <div class="deptCCO" @click="handelChange('second', 7, 'CCO')">CCO</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">
            <div slot="header" class="clearfix">
              <span>工艺/设备 工艺图</span>
            </div>
            <img style="margin-left: 25%" :src="this.machineryImg" alt=""/>
          </el-card>
        </div>
        <div class="left-bottom">
          <el-card class="box-card" style="height: 100%; margin: 10px">
            <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>
              <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/sopbgimg.png"
                  style="width: 200px; height: 130px; margin-top: 10px"
                />
              </el-col>
              <el-col :span="8">
                <MapData
                  style="width: 300px; height: 320px; margin-left: 18%"
                  :machineryId="this.machineryId"
                ></MapData>
              </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>
          <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
                            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
                            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-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="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="锁定站信息"
      height="500px"
      width="1200px"
      append-to-body
    >
      <!--      这里为了没有地图数据而设置的-->
      <!--      <el-row>-->
      <!--        <el-col :span="8">-->
      <!--          <div style="padding: 10px">-->
      <!--            <el-table :data="selectPointList" :show-header="false" style="width: 200px;height: 175px;margin-left: 15%">-->
      <!--              <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="8">-->
      <!--          <LockDetail-->
      <!--            style=" margin-left: 5%"-->
      <!--            :machineryId="this.machineryId"-->
      <!--          ></LockDetail>-->
      <!--        </el-col>-->
      <!--        <el-col :span="8">-->
      <!--          <div style="padding: 10px"></div>-->
      <!--        </el-col>-->
      <!--      </el-row>-->

      <el-row>
        <el-col :span="8">
          <LockDetail
            style="width: 300px; height: 520px; margin-left: 5%"
            :machineryId="this.machineryId"
          ></LockDetail>
          <el-table
            :data="selectPointList"
            :show-header="false"
            style="width: 200px; height: 175px; margin-left: 15%"
          >
            <el-table-column prop="pointName" label=""></el-table-column>
            <el-table-column prop="remark" label=""></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <img
            src="@/assets/images/sopbgimg.png"
            style="width: 100%; height: 100%"
          />
        </el-col>
      </el-row>
    </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
} 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 { getLotoInfo, getLotoMapInfo } from '@/api/mes/lotoStation/lotoStation'
import LockDetail from '@/views/mes/job/jobm/LockDetail.vue'

export default {
  name: 'NewSop',
  components: { Template, MapData, LockDetail },
  dicts: ['sop_type', 'ticket_status', 'ticket_user_type'],
  data() {
    return {
      imageMap: {
        0: 'ticketType0', //维修
        1: 'ticketType1', //Pm
        2: 'ticketType2', //开收班
        3: 'ticketType3', //清洁
        4: 'ticketType4' //换产
      },
      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: [], //隔离点选中的表格渲染
      COCOTicketListPage: [], //CCO岗位的作业票
      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
      }
    }
  },
  computed: {
    // filteredSopTypes() {
    //   const sopTypesInMarsSopPage = this.marsSopPage.map(
    //     (item) => item.sopType
    //   )
    //   return this.dict.type.sop_type.filter((option) =>
    //     sopTypesInMarsSopPage.includes(option.value)
    //   )
    // },
    isStepFourExecuted() {
      const stepFour = this.EightStepForm.find((step) => step.stepIndex == '4')
      return stepFour && stepFour.stepStatus === '1'
    },
    deptXLGCenter() {
      return {
        left: this.deptXLGPosition.left + this.deptXLGPosition.width / 2,
        top: this.deptXLGPosition.top + this.deptXLGPosition.height / 2
      }
    },
    deptCCOCenter() {
      return {
        left: this.deptCCOPosition.left + this.deptCCOPosition.width / 2,
        top: this.deptCCOPosition.top + this.deptCCOPosition.height / 2
      }
    }
  },
  watch: {
    tabPosition: function(val, oldVal) {
      if (val == 'first') {
        this.sopTypeOption = []
        this.technologyList=[]
        this.sopId = null
        this.getList()
      }
    },
    'dialogForm.locker': function(val) {
      if (val) {
        this.handlelockerChage(val)
        console.log('我制定了')
      }
    }
  },

  mounted() {
    this.getList()

  },
  methods: {
    // 锁定站信息部分表格收缩
    handleChangeTable() {
      this.tableVisible = !this.tableVisible
    },
    // 锁定站进入详细页面
    goLockDetail() {
      // this.$router.push({
      //   name:'LockDetail',params: { machineryId: this.machineryId }
      // },)
      this.LockDetailvisible = true
    },
    // 内部人员搜索
    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.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

        getLotoMapInfo(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, '查看-正在进行中作业票列表')

        this.TicketListPage = res.data.filter(
          (item) => item.workstationId == '8'
        )

        this.COCOTicketListPage = res.data.filter(
          (item) => item.workstationId == '7'
        )
      })
      // 这里注释掉是为了 初始化跳转数据为空
      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
      })
    },
    // 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

              getLotoMapInfo(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
        })
      }
    }
  }
}
</script>


<style scoped lang="scss">
.deptXLG {
  position: absolute;
  width: 65px;
  height: 25px;
  left: 500px;
  top: 260px;
  background: #70b26f;
  line-height: 25px;
  text-align: center;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}

.deptCCO {
  position: absolute;
  width: 65px;
  height: 25px;
  left: 670px;
  top: 480px;
  background: #70b26f;
  line-height: 25px;
  text-align: center;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}

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