<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="作业编号" prop="ticketId">
        <el-input
          v-model="queryParams.ticketId"
          placeholder="请输入作业编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作业名称" prop="ticketName">
        <el-input
          v-model="queryParams.ticketName"
          placeholder="请输入作业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="作业区域" prop="workareaId">-->
<!--        <treeselect-->
<!--          style="width: 318px"-->
<!--          v-model="queryParams.workareaId"-->
<!--          :options="deptOptions"-->
<!--          :normalizer="normalizer"-->
<!--          placeholder="选择作业区域"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button
          v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-no-more-click
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="jobList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="70" align="center" />
      <el-table-column
        label="作业编号"
        align="center"
        prop="ticketId"
        width="200"
      >
      </el-table-column>
      <el-table-column
        label="作业名称"
        align="center"
        prop="ticketName"
        width="200"
      />
<!--      <el-table-column-->
<!--        label="作业区域"-->
<!--        align="center"-->
<!--        prop="workareaName"-->
<!--        width="200"-->
<!--      />-->
      <!-- 上锁状态 -->
      <el-table-column label="上锁状态" align="center" width="230">
        <template slot-scope="scope">
          <div
            class="status-container"
            style="width: 100%; height: 100%; display: flex; tetx-align: center"
          >
            <!-- 渲染 lockNum 框子 -->
            <div
              v-for="(item, index) in scope.row.lockNum"
              :key="'lock-' + index"
              class="box"
              style="
                width: 30px;
                height: 30px;
                border: 1px solid black;
                background-color: #fff;
                margin: 0 auto;
              "
            >
              <!-- <span v-if="index < scope.row.lockNum"></span> -->
              <!-- 显示错号 -->
              <span
                v-if="index < scope.row.lockedNum"
                style="font-size: 20px; line-height: 26px"
                >🔒</span
              >
              <!-- 显示对号 -->
              <b
                v-else-if="index < scope.row.removeLockNum"
                style="font-size: 20px; line-height: 30px"
                >✓</b
              >
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 共锁状态 -->
      <el-table-column label="共锁状态" align="center" width="500">
        <template slot-scope="scope">
          <div
            class="status-container"
            style="
              width: 100%;
              display: flex;
              flex-wrap: wrap;
              gap: 4px;
              justify-content: flex-start;
              text-align: center;
              box-sizing: border-box;
              margin: 0 auto;
            "
          >
            <!-- 动态渲染框内容 -->
            <div
              v-for="(item, index) in generateStatus(scope.row)"
              :key="'status-' + index"
              class="box"
              style="
                width: 30px;
                height: 30px;
                border: 1px solid black;
                background-color: #fff;
                margin: 0 2px;
                box-sizing: border-box;
              "
            >
              <b
                v-if="item === 'check'"
                style="font-size: 20px; line-height: 30px"
                >✓</b
              >
              <span
                v-else-if="item === 'lock'"
                style="font-size: 20px; line-height: 26px"
                >🔒</span
              >
              <!-- 空框子无需内容 -->
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLook(scope.row)"
            v-hasPermi="['mes:job:jobplay:view']"
            >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listJobPlayTicket,
  getJobPlayTicketInfo,
} from "@/api/mes/jobplay/jobplay";

import { genCode } from "@/api/system/autocode/rule";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listWorkarea } from "@/api/mes/wa/workarea";
import { connectWebsocket, closeWebsocket, sendMsg } from "@/utils/websocket";
export default {
  name: "Team",
  components: { Treeselect },
  dicts: ["ticket_type", "ticket_status"],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      intervalId: null,
      // 车间数据
      workshopList: [],
      // 作业区域数据
      workareaList: [],
      // 部门树选项
      deptOptions: [],
      // 查询参数
      createTime: "",
      queryParams: {
        current: 1,
        size: 10,
        ticketCode: null,
        ticketName: null,
        ticketStatus: null,
        workshopId: null,
        workareaId: null,
        ticketType: null,
        startTime: "",
        endTime: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },

      // 表单参数
      form: {},
      //
      isFetching: false, // 标志位，控制接口请求是否已经执行过
    };
  },
  created() {
    this.getList();
    // this.getWorkareaList();
    this.initWebSocket()
  },

// 页面销毁就停止webStocket
  beforeDestroy() {
    this.destory()
  },

  methods: {
    initWebSocket(){
      const timestep= Date.now();
      connectWebsocket(`ws://192.168.1.127:9090/websocket/jobTicket/${timestep}`,{w:'S',},(res)=>{
          console.log(res,'websocket接收服务器的数据-index');
          const resMsg=res
          if(resMsg=='refresh'){
            this.handleRefresh();
          }
        },
        (err)=>{
          console.log('断开重连',);
        })
    },
    handleRefresh() {
      if (this.isFetching) {
        console.log('接口请求正在进行中，忽略本次 refresh 消息');
        return;
      }
      this.isFetching = true; // 设置标志位为 true，表示接口请求正在进行中
      listJobPlayTicket(this.queryParams).then((response) => {
        console.log(response, "response--作业票列表");
        this.jobList = response.data.records;
        this.total = response.data.total;
      }).catch((error) => {
        console.error('获取作业票列表失败', error);
      }).finally(() => {
        this.isFetching = false; // 重置标志位为 false，允许下次 refresh 消息执行接口请求

      });
    },
    destory(){
      closeWebsocket();//断开链接
    },
    // 发消息
    sendMsg(){
      sendMsg('aaa');
    },

    generateStatus(row) {
      // 从数据中获取值
      const colockNum = row.colockNum || 0; // 总框数
      const colockedNum = row.colockedNum || 0; // 锁数量
      const removeColockNum = row.removeColockNum || 0; // 对号数量

      // 创建状态数组
      const statusArray = [];

      // 添加对号
      for (let i = 0; i < removeColockNum; i++) {
        statusArray.push("check");
      }

      // 添加锁
      for (let i = 0; i < colockedNum; i++) {
        statusArray.push("lock");
      }

      // 添加空框
      const emptyNum = colockNum - colockedNum - removeColockNum;
      for (let i = 0; i < emptyNum; i++) {
        statusArray.push("empty");
      }

      return statusArray;
    },
    // 格式化日期查询数据
    formatDate(date) {
      if (date && date instanceof Date && !isNaN(date)) {
        // 使用本地时间
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")}`;
      }
      return null;
    },
    /** 查询班组列表 */
    getList() {
      // this.loading = true;
      listJobPlayTicket(this.queryParams).then((response) => {
        console.log(response, "response--作业票列表");
        this.jobList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getWorkareaList() {
      const data = {
        current: 1,
        size: -1,
      };
      listWorkarea(data).then((response) => {
        this.deptOptions = this.handleTree(
          response.data.records,
          "workareaId",
          "parentId",
          "children"
        );
        console.log(this.deptOptions, "作业区域下拉树形结构");
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.workareaId,
        label: node.workareaName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ticketCode: null,
        ticketName: null,
        ticketStatus: null,
        workareaName: null,
        workshopName: null,
        ticketType: null,
        pointCount: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = "";
      (this.queryParams.startTime = ""),
        (this.queryParams.endTime = ""),
        this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ticketId);
      this.codes = selection.map((item) => item.ticketCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(val) {
      this.reset();
      this.open = true;
      this.selectSopPoints(null);
      this.PointTableData(null);
      this.$router.push(`/mes/job/jobm/NewOperations?ticketId=null`);
      this.title = "添加隔离点";
      this.optType = "add";
    },
    // 查看
    handleLook(row) {
      localStorage.setItem('ticketId',row.ticketId)
      // 设置为true表示作业票里查看不可以点击隔离点
      this.$router.push(
        `/mes/job/jobplay/jobPlayDetail?ticketId=${row.ticketId}`
      );
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teamId = row.ticketId || this.ids;
      this.setSopLook(false);

      this.$router.push(
        `/mes/job/jobm/NewOperationsEdit?ticketId=${row.ticketId}`
      );
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.teamId != null) {
            updateTeam(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeam(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teamIds = row.ticketId || this.ids;
      const titcketCodes = row.ticketCode || this.codes;
      this.$modal
        .confirm('是否确认删除作业票编号为"' + titcketCodes + '"的数据项？')
        .then(function () {
          return deleteIsJobTicket(teamIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped>
.el-input-width {
  width: 380px !important;
}
.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);
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // position: relative;
}
</style>
