<template>
  <el-card shadow="always" :body-style="{ padding: '10px' }">
    <div class="app-container">
      <div class="main-wrap">
        <div class="left">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
            <el-form-item prop="machineTool" label="机台" style="width: 500px">
              <el-select
                v-model="form.machineTool"
                filterable
                @change="machineToolChange"
              >
                <el-option
                  v-for="(item, index) in lineOptions"
                  :key="index"
                  :label="item.productionLineName"
                  :value="item.id"
                >
                  <span class="discribe" style="float: left">{{item.productionLineName }}</span>
                  <span
                    style="float: right; color: #8492a6; font-size: 13px"
                  >{{ item.productionLineDepartment }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="scid" label="丝车">
              <el-select
                v-model="form.scid"
                filterable
              >
                <el-option
                  v-for="(item, index) in silkcartList"
                  :key="index"
                  :label="item.scname"
                  :value="item.id"
                >
                  <span class="discribe" style="float: left">{{item.scname }}</span>
                  <span
                    style="float: right; color: #8492a6; font-size: 13px"
                  >{{ item.scWeight }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="卷数" prop="js" style="width: 278px">
              <el-input v-model="form.js" placeholder="请输入卷数"/>
            </el-form-item>
            <el-form-item label="毛重" prop="standby" style="width: 278px">
              <el-input v-model="form.standby" placeholder="请输入毛重" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
        <div class="right">
          <div class="table-wrap">
            <el-table
              ref="proTableRef"
              :data="batchTableData"
              border
              stripe
              width="100%"
              max-height="260"
              highlight-current-row
              :row-class-name="tableRowClassName"
              @row-click="handleCurrentChange"
            >
              <!-- <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                ></el-table-column> -->
              <el-table-column
                v-for="col in columns"
                :prop="col.id"
                :key="col.id"
                :label="col.label"
              >
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>





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

      <!-- 添加或修改线边舱库存对话框 -->

    </div>
  </el-card>
</template>

<script>
import { listLineSideCabin, getLineSideCabin, delLineSideCabin, addLineSideCabin, updateLineSideCabin,  getLineOptionLsit,  finishedProductList, listSilkcart,} from "@/api/lineSideCabin/lineSideCabin";
import {getSilkcart} from "@/api/silkcart/silkcart";

export default {
  name: "LineSideCabin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 线边舱库存表格数据
      lineSideCabinList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productNo: null,
        productName: null,
        productSpecifications: null,
        productId: null,
        batchNumber: null,
        colours: null,
        machineTool: null,
        js: null,
        status: null,
        standby: null,
        standby1: null,
        standby2: null,
        standby3: null,
        workshop: null,
        recipient: null,
        collectTime: null,
        confirm: null,
        confirmTime: null,
        scid:null
      },
      // 表单参数
      form: {
        id: null,
        productNo: null,
        productName: null,
        productSpecifications: null,
        productId: null,
        batchNumber: null,
        colours: null,
        machineTool: null,//机台号
        js: null,
        status: null,
        standby: '',  // 确保初始化为空字符串
        standby1: null,
        standby2: null,
        standby3: null,
        workshop: null,
        recipient: null,
        collectTime: null,
        confirm: null,
        confirmTime: null,
        scid: null
      },
      // 表单校验
      rules: {
      },
      batchData: [], //所有批号数据
      batchTableData: [], //批号表格数据
      lineOptions: [], //机台选项数据
      silkcartList: [], //丝车列表
      xzbatchTableData: [], //选中的批号表格数据
      currentRow: null, // 添加当前选中行
      columns: [
        {
          id: "productNo",
          label: this.$t('printIndex.columns.productNo'),
        },
        {
          id: "productName",
          label: this.$t('printIndex.columns.productName'),
        },
        {
          id: "productSpecifications",
          label: this.$t('printIndex.columns.productSpecifications'),
        },
        {
          id: "lotNum",
          label: this.$t('printIndex.columns.lotNum'),
        },
        {
          id: "productColor",
          label: this.$t('printIndex.columns.productColor'),
        },
        // {
        //   id: "productName",
        //   label: "订单号",
        // },
      ],
      websocket: null,
      wsUrl: 'ws://localhost:8721/DBCc',
    };
  },
  created() {
    // 确保在创建新连接前关闭旧连接
    if (this.websocket) {
      this.closeWebSocket();
    }
    this.getList();
    this.initWebSocket();
  },
  mounted() {
    this.getLineOptionLsit();
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  beforeRouteLeave(to, from, next) {
    // 路由离开时关闭连接
    this.closeWebSocket();
    next();
  },
  methods: {
    /** 查询线边舱库存列表 */
    getList() {
      this.loading = true;
      listLineSideCabin(this.queryParams).then(response => {
        this.lineSideCabinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productNo: null,
        productName: null,
        productSpecifications: null,
        productId: null,
        batchNumber: null,
        colours: null,
        machineTool: null,
        js: null,
        status: null,
        standby: '', // 确保重置时也初始化为空字符串
        standby1: null,
        standby2: null,
        standby3: null,
        workshop: null,
        recipient: null,
        collectTime: null,
        confirm: null,
        confirmTime: null,
        scid: null
      };
      this.resetForm("form");
    },
    /** 机台相关 */
    // 机台改变回调
    machineToolChange(id) {
      console.log("================选中机台")
      if (id) {
        this.form.machineToolNo = this.lineOptions.find(
          (item) => item.id == id
        ).productionLineNo;
      }
      this.getAllBatchData(id);
    },
    // 获取机台选项数据
    async getLineOptionLsit() {
      let payLoad = {
        isEnablePaging: false,
      };
      try {
        let res = await getLineOptionLsit(payLoad);
        let scres = await listSilkcart(payLoad);
        if (res.code == 200) {
          this.lineOptions = res.rows;
          this.silkcartList = scres.rows;
          if (this.lineOptions.length > 0 && this.excuteType == 1) {
            this.form.machineTool = this.lineOptions[0].id;
            this.machineToolChange(this.form.machineTool);
          }
        } else {
        }
      } catch (error) {}

      console.log("------------------",this.silkcartList)
    },
    // 获取所有批次数据
    async getAllBatchData(id) {

      try {
        console.log('===================获取批次数据')
        let payload = { machineTool: id };
        let res = await finishedProductList(payload);
        if (res.code == 200) {
          this.batchData = res.data;
          this.batchTableData = res.data;
        } else {
        }
      } catch (error) {}
    },
    // 表格点击回调
    async handleCurrentChange(val) {
      if (!val) return;
      
      // 设置当前选中行的高亮
      this.$refs.proTableRef.setCurrentRow(val);
      
      this.xzbatchTableData = val;
      console.log("表格点击回调",this.xzbatchTableData)
      
      //判断是否为纺丝部如果是则不做处理
      if(val?.productionlinedepartment && val.productionlinedepartment !== undefined && val.productionlinedepartment !== "纺丝部" && val.productionlinedepartment !== ""){
        this.form.tubeColor = val.tubeColor;//管色
        this.form.boxWeight = val.boxWeight;//箱重
        this.form.canisterWeight = val.canisterWeight;//筒重
      }

      if (this.isStartReadNum || this.excuteType != 1) {
        return;
      }
      
      if (!this.currentRow || val.id != this.currentRow.id) {
        this.tableData = [];
        this.nowWeight = 0;
        this.getQrCodeHandle();
        this.summertId = new Date().getTime(); //总码单id重新生成
      }
      
      this.currentRow = val;
    },
    /** 机台相关 */
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加线边舱库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLineSideCabin(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改线边舱库存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.productNo = this.xzbatchTableData.productNo;
        this.form.productName = this.xzbatchTableData.productName;
        this.form.productSpecifications = this.xzbatchTableData.productSpecifications;
        this.form.productId = this.xzbatchTableData.productId;//类型字段变更为存储产品id
        this.form.batchNumber = this.xzbatchTableData.lotNum;
        this.form.colours = this.xzbatchTableData.productColor;
        this.form.standby3 = this.xzbatchTableData.id;//任务id
        if (valid) {
          if (this.form.id != null) {
            updateLineSideCabin(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLineSideCabin(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除线边舱库存编号为"' + ids + '"的数据项？').then(function() {
        return delLineSideCabin(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lineSideCabin/lineSideCabin/export', {
        ...this.queryParams
      }, `lineSideCabin_${new Date().getTime()}.xlsx`)
    },
    /** 初始化 WebSocket 连接 */
    initWebSocket() {
      this.closeWebSocket();

      try {
        console.log('开始连接WebSocket:', this.wsUrl);
        this.websocket = new WebSocket(this.wsUrl);
        
        this.websocket.onopen = () => {
          console.log('WebSocket 连接成功');
        };
        
        this.websocket.onmessage = this.handleWebSocketMessage;
        
        this.websocket.onerror = () => {
          console.log('WebSocket 连接错误');
          this.closeWebSocket();
        };
        
        this.websocket.onclose = () => {
          console.log('WebSocket 连接关闭');
          this.websocket = null;
        };
        
      } catch (e) {
        console.error('WebSocket 连接错误:', e);
        this.closeWebSocket();
      }
    },
    /** 关闭 WebSocket 连接 */
    closeWebSocket() {
      if (this.websocket) {
        try {
          this.websocket.close();
          this.websocket = null;
          console.log('WebSocket 连接已关闭');
        } catch (error) {
          console.error('关闭 WebSocket 连接失败:', error);
        }
      }
    },
    /** 处理WebSocket消息 */
    handleWebSocketMessage(e) {
      try {
        const data = JSON.parse(e.data);
        // 处理权重数据
        if (data.weight !== undefined) {
          const weight = parseFloat(data.weight);
          if (!isNaN(weight)) {
            this.$set(this.form, 'standby', weight.toFixed(2));
            console.log('更新重量数据:', weight.toFixed(2), '是否稳定:', data.isStable);
            
            // 如果重量稳定，显示提示
            if (data.isStable) {
              this.$message({
                type: 'success',
                message: `重量已稳定: ${weight.toFixed(2)}kg`,
                duration: 2000
              });
            }
          }
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error);
      }
    },
    // 表格行的类名
    tableRowClassName({row, rowIndex}) {
      if (this.currentRow && row.id === this.currentRow.id) {
        return 'current-row';
      }
      return '';
    },
  }
};
</script>
<style lang="scss" scoped>
.main-wrap {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .left {
    width: 30%;

    .top-area {
      display: flex;
      justify-content: space-between;

      .msg {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 700;
      }

      .btn-list {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }

    .count-area {
      display: flex;
      flex-wrap: wrap;

      .count-item {
        display: flex;
        margin-bottom: 10px;
        width: 50%;
      }
    }
  }

  .right {
    width: 70%;
    // flex: 1;
    .queryForm {
      width: 100%;
      padding: 0 10px;
      display: flex;

      .label {
        text-align: right;
        color: #606266;
        line-height: 30px;
        display: block;
        width: 100px;
        font-weight: 700;
        text-decoration: aliceblue;
        margin-right: 10px;
      }
    }

    .table-wrap {
      margin-top: 5px;
      width: 100%;
      overflow-x: scroll;
    }
  }
}

::v-deep .el-date-editor.el-input {
  width: 100%;
}

::v-deep .el-input-number--mini {
  width: 99%;
}

::v-deep .el-table__body tr.current-row > td.el-table__cell {
  background-color: #55e905 !important;
}

::v-deep .el-table__body tr.hover-row.current-row > td.el-table__cell {
  background-color: #55e905 !important;
}

::v-deep .el-table__body tr.hover-row > td.el-table__cell {
  background-color: #55e905 !important;
}
</style>
