<template>
  <div class="topOp">
    <span>当前台位</span>
    <span class="text">{{ store.user.opDescription || store.user.opName }}</span>
  </div>

  <!-- 状态显示框 -->
  <div class="status-box">
    <div class="title">状态监控</div>
    <div class="status-content">
      <div class="status-item">
        <div class="status-title">车体状态：</div>
        <span v-if="nowStatus.isCarArrive" class="status-value success">车体在位</span>
        <span v-else class="status-value warning">车体离位</span>
      </div>
      <div class="status-item">
        <div class="status-title">通道状态：</div>
        <span v-if="shippingTerms.isPeople" class="status-value success">通道无人</span>
        <span v-else class="status-value danger">通道有人</span>
      </div>
      <div class="status-item">
        <div class="status-title">护栏状态：</div>
        <span v-if="shippingTerms.isFence" class="status-value success">安装到位</span>
        <span v-else class="status-value warning">未安装到位</span>
      </div>
      <div class="status-item">
        <div class="status-title">RGV状态：</div>
        <span v-if="nowStatus.isRgvAlarm" class="status-value danger">RGV报警</span>
        <span v-else-if="nowStatus.isRgvWorking" class="status-value success">RGV工作中</span>
        <span v-else-if="nowStatus.isRgvIdle" class="status-value info">RGV空闲</span>
        <span v-else class="status-value info">无状态</span>
      </div>
      <div class="status-item">
        <div class="status-title">门禁状态：</div>
        <span v-if="nowStatus.isDoorLocked" class="status-value success">门禁锁死</span>
        <span v-else class="status-value danger">门禁开启</span>
      </div>
      <div class="status-item">
        <div class="status-title">MES连接：</div>
        <span v-if="nowStatus.isProductionOnline" class="status-value success">在线</span>
        <span v-else class="status-value danger">离线</span>
      </div>
      <div class="status-item">
        <div class="status-title">数据库连接：</div>
        <span v-if="nowStatus.isSqlOnline" class="status-value success">已连接</span>
        <span v-else class="status-value danger">已断开</span>
      </div>
      <div class="status-item">
        <div class="status-title">MQTT连接：</div>
        <span v-if="nowStatus.isMqttOnline" class="status-value success">已连接</span>
        <span v-else class="status-value danger">已断开</span>
      </div>
      <!-- <div class="status-item">
        <div class="status-title">MES连接：</div>
        <span v-if="nowStatus.isMesOnline" class="status-value success">已连接</span>
        <span v-else class="status-value danger">已断开</span>
      </div> -->
    </div>
  </div>

  <div class="carMainData" :class="{ 'two-columns': store.user.opName == 'RGVCH2' }">
    <template v-if="store.user.opName == 'RGVCH2'">
      <div class="column">
        <div class="column-title">台位1项目信息</div>
        <div class="item-row">
          <div class="item">
            <div class="title">项目编号：</div>
            {{ projectData.projectNo }}
          </div>
          <div class="item">
            <div class="title">项目名称：</div>
            {{ projectData.projectName }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">车体：</div>
            {{ projectData.carBody }}
          </div>
          <div class="item">
            <div class="title">车号：</div>
            {{ projectData.carNo }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">伸缩缝：</div>
            {{ projectData.expansionJoint }}
          </div>
          <div class="item">
            <div class="title">车节：</div>
            {{ projectData.carSection }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">调节参数：</div>
            {{ projectData.adjustTheParameters }}
          </div>
          <div class="item"></div>
        </div>
      </div>
      <div class="column">
        <div class="column-title">台位2项目信息</div>
        <div class="item-row">
          <div class="item">
            <div class="title">项目编号：</div>
            {{ projectData2.projectNo }}
          </div>
          <div class="item">
            <div class="title">项目名称：</div>
            {{ projectData2.projectName }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">车体：</div>
            {{ projectData2.carBody }}
          </div>
          <div class="item">
            <div class="title">车号：</div>
            {{ projectData2.carNo }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">伸缩缝：</div>
            {{ projectData2.expansionJoint }}
          </div>
          <div class="item">
            <div class="title">车节：</div>
            {{ projectData2.carSection }}
          </div>
        </div>
        <div class="item-row">
          <div class="item">
            <div class="title">调节参数：</div>
            {{ projectData2.adjustTheParameters }}
          </div>
          <div class="item"></div>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="item">
        <div class="title">项目编号：</div>
        {{ projectData.projectNo }}
      </div>
      <div class="item"></div>
      <div class="item">
        <div class="title">项目名称：</div>
        {{ projectData.projectName }}
      </div>
      <div class="item">
        <div class="title">车体：</div>
        {{ projectData.carBody }}
      </div>
      <div class="item">
        <div class="title">车号：</div>
        {{ projectData.carNo }}
      </div>
      <div class="item">
        <div class="title">伸缩缝：</div>
        {{ projectData.expansionJoint }}
      </div>
      <div class="item">
        <div class="title">车节：</div>
        {{ projectData.carSection }}
      </div>
      <div class="item">
        <div class="title">调节参数：</div>
        {{ projectData.adjustTheParameters }}
      </div>
    </template>
  </div>

  <div class="button">
    <el-checkbox v-model="shippingTerms.isCarArrive"
      :disabled="shippingList.length > 0 ? shippingList[0].送料状态 != 1 : false" label="车体到位" size="large"
      @change="checkBoxChange('车体到位时间')" />
    <el-checkbox v-model="shippingTerms.isPeople"
      :disabled="shippingList.length > 0 ? shippingList[0].送料状态 != 1 : false" label="确认通道无人" size="large"
      @change="checkBoxChange('确认通道无人时间')" />
    <el-checkbox v-model="shippingTerms.isFence" :disabled="shippingList.length > 0 ? shippingList[0].送料状态 != 1 : false"
      label="护栏安装到位" size="large" @change="checkBoxChange('护栏安装到位时间')" />
    <el-checkbox v-model="shippingTerms.isRgvShipping"
      :disabled="shippingList.length > 0 ? shippingList[0].送料状态 != 1 : false" label="RGV通道无障碍" size="large"
      @change="checkBoxChange('RGV通道无障碍时间')" />
  </div>

  <div class="table">
    <!--    <div class="row">-->
    <!--      <div>送料次数</div>-->
    <!--      <div>{{ count1 }}</div>-->
    <!--      <div>{{ count2 }}</div>-->
    <!--      <div>{{ count3 }}</div>-->
    <!--      <div>{{ count4 }}</div>-->
    <!--      <div>{{ count5 }}</div>-->
    <!--      <div></div>-->
    <!--    </div>-->
    <div class="row title">
      <div>使用位置</div>
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div></div>
    </div>
    <div v-for="(item, index) in shippingList" :key="'shipping-' + index" class="row">
      <div>送料状态</div>
      <div :style="{ backgroundColor: getStatusColor(item.位置1) }" @click="cutRGVStatus(item.位置1, 1, item)">
        {{ getStatus(item.位置1) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置2) }" @click="cutRGVStatus(item.位置2, 2, item)">
        {{ getStatus(item.位置2) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置3) }" @click="cutRGVStatus(item.位置3, 3, item)">
        {{ getStatus(item.位置3) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置4) }" @click="cutRGVStatus(item.位置4, 4, item)">
        {{ getStatus(item.位置4) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置5) }" @click="cutRGVStatus(item.位置5, 5, item)">
        {{ getStatus(item.位置5) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置6) }" @click="cutRGVStatus(item.位置6, 6, item)">
        {{ getStatus(item.位置6) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置7) }" @click="cutRGVStatus(item.位置7, 7, item)">
        {{ getStatus(item.位置7) }}
      </div>
      <div :style="{ backgroundColor: getStatusColor(item.位置8) }" @click="cutRGVStatus(item.位置8, 8, item)">
        {{ getStatus(item.位置8) }}
      </div>
      <div>
        <el-button v-if="item.送料状态 == 1" plain style="width: 100%;height: 100%;margin-top: -4px;font-size: 20px"
          type="primary" @click="submitPlan(item)">
          确认送料任务
        </el-button>
        <el-button v-if="item.送料状态 == 2" plain style="width: 100%;height: 100%;margin-top: -4px;font-size: 20px"
          type="warning">
          送料中
        </el-button>
        <el-button v-if="item.送料状态 == 4" plain style="width: 100%;height: 100%;margin-top: -4px;font-size: 20px"
          type="success" @click="reFeeding(item)">
          申请再次送料
        </el-button>
      </div>
    </div>
    <div v-for="(item, index) in shippingList" :key="'lk-status-' + index" class="row">
      <div>料框状态</div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置1_料框状态) }">
        {{ getLKStatus(item.位置1_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置2_料框状态) }">
        {{ getLKStatus(item.位置2_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置3_料框状态) }">
        {{ getLKStatus(item.位置3_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置4_料框状态) }">
        {{ getLKStatus(item.位置4_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置5_料框状态) }">
        {{ getLKStatus(item.位置5_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置6_料框状态) }">
        {{ getLKStatus(item.位置6_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置7_料框状态) }">
        {{ getLKStatus(item.位置7_料框状态) }}
      </div>
      <div :style="{ backgroundColor: getLKStatusColor(item.位置8_料框状态) }">
        {{ getLKStatus(item.位置8_料框状态) }}
      </div>
      <div>
        <el-button
          v-if="item.位置1_料框状态 == 1 || item.位置2_料框状态 == 1 || item.位置3_料框状态 == 1 || item.位置4_料框状态 == 1 || item.位置5_料框状态 == 1 || item.位置6_料框状态 == 1 || item.位置7_料框状态 == 1 || item.位置8_料框状态 == 1"
          plain style="width: 100%;height: 100%;margin-top: -4px;font-size: 20px" type="primary"
          @click="submitLKPlan(item)">
          请求下料框
        </el-button>
        <el-button v-else plain style="width: 100%;height: 100%;margin-top: -4px;font-size: 20px" type="success">
          下料框完成
        </el-button>
      </div>
    </div>
    <div class="row">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </div>

</template>

<script setup>
import { inject, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useAppStore } from "@/store/app.js";
import { ElMessage, ElMessageBox } from "element-plus";
import mqtt from "mqtt";

const store = useAppStore();

const CreateData = inject('CreateData')
const ExecDatabase = inject('ExecDatabase')
const ExecWritePLC = inject('ExecWritePLC')
const ExecReadPLC = inject('ExecReadPLC')
const ExecMultReadPLC = inject('ExecMultReadPLC')
const ExecIMESAPI = inject('ExecIMESAPI')

var client = null

const count1 = ref(2)
const count2 = ref(1)
const count3 = ref(0)
const count4 = ref(2)
const count5 = ref(1)
const count6 = ref(0)
const count7 = ref(0)
const count8 = ref(0)

const nowStatus = reactive({
  isPeople: false, // 护栏是否有人
  isCarArrive: false, // 车体到位
  isRgvShipping: false, // RGV开始送料
  isRgvWorking: false, // RGV工作中
  isRgvIdle: false, // RGV空闲
  isRgvAlarm: false, // RGV报警
  isDoorLocked: false, // 门禁状态
  isProductionOnline: false, // 生产模式
  isSqlOnline: false, // 数据库连接
  isMqttOnline: false, // MQTT连接
  isMesOnline: false, // MES连接
})

// 定时器对象
let timer1 = null

const projectData = reactive({
  projectNo: '', // 项目编号
  projectName: '', // 项目名称
  carNo: '',  // 车号
  carSection: '',  // 车节
  carBodyNo: '', // 车体流水号
  carBody: '',   // 车体
  carBodyCode: '',   // 车体流水号
  expansionJoint: '',  // 伸缩缝
  adjustTheParameters: '',  // 调节参数
})

const projectData2 = reactive({
  projectNo: '', // 项目编号
  projectName: '', // 项目名称
  carNo: '',  // 车号
  carSection: '',  // 车节
  carBodyNo: '', // 车体流水号
  carBody: '',   // 车体
  carBodyCode: '',   // 车体流水号
  expansionJoint: '',  // 伸缩缝
  adjustTheParameters: '',  // 调节参数
})

// 送料条件 车体到位、护栏安装到位、确认通道无人、RGV通道无障碍请求送料
const shippingTerms = reactive({
  isCarArrive: false, // 车体到位
  isPeople: false, // 确认通道无人
  isFence: false, // 护栏安装到位
  isRgvShipping: false, // RGV通道无障碍请求送料
})

const shippingList = reactive([])

onMounted(() => {
  getRGVData()
  getPLCStatus()
  connectMqtt()
  // 初始化时获取所有状态
  getConnectionStatus()
  timer1 = setInterval(() => {
    getRGVData()
    // getPLCStatus()
  }, 1000 * 5)
});

// 页面切换 关闭定时器
onUnmounted(() => {
  try {
    if (client) {
      client.end();
    }
  } catch (error) {
    console.log('关闭连接失败:', error);
  }
  client = null;
  clearInterval(timer1)
})

const getRGVData = () => {
  var param = []
  param[0] = ['opName', store.user.opName]
  var Data = CreateData('11', 'CRRC_台位_RGV送料Moby_送料平台_查询', param)
  ExecDatabase(Data).then(response => {
    count1.value = 0
    count2.value = 0
    count3.value = 0
    count4.value = 0
    count5.value = 0
    count6.value = 0
    count7.value = 0
    count8.value = 0
    shippingList.length = 0
    if (response.data.length > 0) {
      let data = response.data[0]
      projectData.projectNo = data.项目编号
      projectData.projectName = data.项目名称
      projectData.carNo = data.车号
      projectData.carSection = data.车节
      projectData.carBodyNo = data.车体流水号
      projectData.carBody = data.车体
      projectData.carBodyCode = data.车体流水号
      projectData.expansionJoint = data.伸缩缝
      projectData.adjustTheParameters = data.调节参数

      if (response.data.length > 1) {
        projectData2.projectNo = response.data[1].项目编号
        projectData2.projectName = response.data[1].项目名称
        projectData2.carNo = response.data[1].车号
        projectData2.carSection = response.data[1].车节
        projectData2.carBodyNo = response.data[1].车体流水号
        projectData2.carBody = response.data[1].车体
        projectData2.carBodyCode = response.data[1].车体流水号
        projectData2.expansionJoint = response.data[1].伸缩缝
        projectData2.adjustTheParameters = response.data[1].调节参数
      }

      shippingTerms.isCarArrive = data.车体到位时间 != null
      shippingTerms.isPeople = data.确认通道无人时间 != null
      shippingTerms.isFence = data.护栏安装到位时间 != null
      shippingTerms.isRgvShipping = data.RGV通道无障碍时间 != null

      shippingList.push(response.data[0])

      // 计算送料次数
      // 送料前每车位状态 0不用 1缺料 2需送料 4已到位
      // 送料状态 1 待确认 2 送料中 3 已完成
      for (let i = 0; i < response.data.length; i++) {
        let item = response.data[i]
        if (item.位置1 == 4) count1.value++
        if (item.位置2 == 4) count2.value++
        if (item.位置3 == 4) count3.value++
        if (item.位置4 == 4) count4.value++
        if (item.位置5 == 4) count5.value++
        if (item.位置6 == 4) count6.value++
        if (item.位置7 == 4) count7.value++
        if (item.位置8 == 4) count8.value++
      }
    }
  })
}

// 获取PLC状态（批量读取方式）
const getPLCStatus = async () => {
  // 100021:通道是否有人 100030:车体是否到位 100001:RGV是否工作中 1002:RGV报警 100010:RGV空闲 100022:门禁状态
  let responseReadPLC = await ExecMultReadPLC(store.user.opName, ["100021", "100030", "100001", "1002", "100010", "100022"])
  console.log('批量读取PLC状态：', responseReadPLC)
  if (responseReadPLC.data.code == 0) {
    // 处理通道是否有人
    const peopleStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "100021")
    if (peopleStatus) {
      nowStatus.isPeople = peopleStatus.tagValue === 'True'
    }

    // 处理车体是否到位
    const carArriveStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "100030")
    if (carArriveStatus) {
      nowStatus.isCarArrive = carArriveStatus.tagValue === 'True'
    }

    // 处理RGV是否工作中
    const rgvWorkingStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "100001")
    if (rgvWorkingStatus) {
      nowStatus.isRgvShipping = rgvWorkingStatus.tagValue === 'True'
      nowStatus.isRgvWorking = rgvWorkingStatus.tagValue === 'True'
    }

    // 处理RGV报警状态
    const rgvAlarmStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "1002")
    if (rgvAlarmStatus) {
      nowStatus.isRgvAlarm = rgvAlarmStatus.tagValue === 'True'
    }

    // 处理RGV空闲状态
    const rgvIdleStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "100010")
    if (rgvIdleStatus) {
      nowStatus.isRgvIdle = rgvIdleStatus.tagValue === 'True'
    }

    // 处理门禁状态
    const doorStatus = responseReadPLC.data.ReadRes_SignalValues.find(item => item.tagTypeCodeID === "100022")
    if (doorStatus) {
      nowStatus.isDoorLocked = doorStatus.tagValue === 'True'
    }
  }
}

const shipping = () => {
  var param = []
  param[0] = ['OPName', store.user.opName]
  param[1] = ['CarNumber', projectData.carBodyNo]
  param[2] = ['Operator', store.user.AID]
  param[3] = ['AddType', 1]
  var Data = CreateData('11', 'CRRC_生产_RGV送料_新增', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      if (response.data[0].result == 1) {
        ElMessage.success(response.data[0].msg)
        getRGVData()
      } else {
        ElMessage.error(response.data[0].msg)
      }
    } else {
      ElMessage.error('数据异常')
    }
  })
}

const getStatus = (type) => {
  switch (type) {
    case 0:
      return '不送料'
    case 1:
      return '缺料'
    case 2:
      return '需送料'
    case 4:
      return '已到位'
    default:
      return ''
  }
}

const getLKStatus = (type) => {
  switch (type) {
    case 0:
      return '无料框'
    case 1:
      return '有料框'
    default:
      return ''
  }
}

const cutRGVStatus = (type, index, item) => {
  if (item.送料状态 != 1) return
  // 0不用 1缺料 2需送料 4已到位
  // 需送料可以改成缺料 缺料可以切换为 需送料
  let posList = [100031, 100032, 100033, 100034, 100035,100105,100106,100107,100110,100111 ]
  if (type == 0) {
    ElMessageBox.confirm(
      '是否将该位置送料状态切换为需送料状态?',
      '切换确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      ExecWritePLC(store.user.opName, posList[index - 1], false).then(res => {
        if (res.data.code != 0) {
          ElMessage.error(res.data.msg)
          return;
        }
        var param = []
        param[0] = ['OPName', store.user.opName]
        param[1] = ['CarNumber', projectData.carBodyNo]
        param[2] = ['FeedingTimes', item.送料次数]
        param[3] = ['Pos_RGV', '位置' + index]
        param[4] = ['value', 2]
        var Data = CreateData('11', 'CRRC_生产_RGV送料_切换送料状态', param)
        ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            if (response.data[0].result == 1) {
              ElMessage.success(response.data[0].msg)
              getRGVData()
            } else {
              ElMessage.error(response.data[0].msg)
            }
          } else {
            ElMessage.error('数据异常')
          }
        })
      })
    })
  } else if (type == 2) {
    ElMessageBox.confirm(
      '是否将该位置送料状态切换为不送料状态?',
      '切换确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      ExecWritePLC(store.user.opName, posList[index - 1], true).then(res => {
        if (res.data.code != 0) {
          ElMessage.error(res.data.msg)
          return;
        }
        var param = []
        param[0] = ['OPName', store.user.opName]
        param[1] = ['CarNumber', projectData.carBodyNo]
        param[2] = ['FeedingTimes', item.送料次数]
        param[3] = ['Pos_RGV', '位置' + index]
        param[4] = ['value', 0]
        var Data = CreateData('11', 'CRRC_生产_RGV送料_切换送料状态', param)
        ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            if (response.data[0].result == 1) {
              ElMessage.success(response.data[0].msg)
              getRGVData()
            } else {
              ElMessage.error(response.data[0].msg)
            }
          } else {
            ElMessage.error('数据异常')
          }
        })
      })
    })
  }
}

const reFeeding = async (item) => {
  // 判断 下料框是否完成
  if (item.位置1_料框状态 == 0 && item.位置2_料框状态 == 0 && item.位置3_料框状态 == 0 && item.位置4_料框状态 == 0 && item.位置5_料框状态 == 0 && item.位置6_料框状态 == 0 && item.位置7_料框状态 == 0 && item.位置8_料框状态 == 0) {
    // 弹窗提示是否重新送料
    ElMessageBox.confirm(
      '是否生成新的送料申请?',
      '二次确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      var param = []
      param[0] = ['OPName', store.user.opName]
      var Data = CreateData('11', 'CRRC_生产_重新送料申请', param)
      ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          if (response.data[0].result == 1) {
            ElMessage.success(response.data[0].msg)
            getRGVData()
          } else {
            ElMessage.error(response.data[0].msg)
          }
        } else {
          ElMessage.error('数据异常')
        }
      })
    })
  } else {
    ElMessage.warning("料框未下完，请下完后再试")
  }
}

const checkBoxChange = async (name) => {
  let value;
  switch (name) {
    case '车体到位时间':
      value = shippingTerms.isCarArrive
      break
    case '确认通道无人时间':
      value = shippingTerms.isPeople
      break
    case '护栏安装到位时间':
      value = shippingTerms.isFence
      break
    case 'RGV通道无障碍时间':
      value = shippingTerms.isRgvShipping
      break
  }
  var param = []
  param[0] = ['OPName', store.user.opName]
  param[1] = ['字段名', name]
  param[2] = ['值', value]
  var Data = CreateData('11', 'CRRC_生产_RGV送料_切换安全状态', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      if (response.data[0].result == 1) {
        ElMessage.success(response.data[0].msg)
        getRGVData()
      } else {
        ElMessage.error(response.data[0].msg)
      }
    } else {
      ElMessage.error('数据异常')
    }
  })
}

const submitPlan = async (item) => {
  // 判断四个条件是否满足 不满足不允许进行送料
  if (!shippingTerms.isCarArrive) {
  
    ElMessage.warning('未确认车体到位，请确认！')
    return
  }
  if (!shippingTerms.isPeople) {
    ElMessage.warning('未确认通道无人，请确认！')
    return
  }
  if (!shippingTerms.isFence) {
    ElMessage.warning('未确认护栏安装到位，请确认！')
    return
  }
  if (!shippingTerms.isRgvShipping) {
    ElMessage.warning('未确认RGV通道无障碍，请确认！')
    return
  }


  ElMessageBox.confirm(
    '是否确认送料任务，确认后不可再次修改本次送料状态?',
    '送料确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // // 100021 通道是否有人 PLC
    // let responseReadPLC = await ExecReadPLC(store.user.opName, 100021)
    // if (responseReadPLC.data.code == 0) {
    //   if (responseReadPLC.data.tagValue == "1" || responseReadPLC.data.tagValue == "true") {
    //     ElMessage.error('当前通道有人，请确认人已离开后再次尝试送料')
    //     return;
    //   }
    // }
    var param = {
      OPName: store.user.opName,
      // CarFlowNo: projectData.carBodyNo,
      Operator: store.user.AID,
    }
    let response = await ExecIMESAPI('CallMaterial', param)
    if (response.data.code != 0) {
      ElMessage.error(response.data.msg)
    } else {
      ElMessage.success("确认送料成功！！")
      getRGVData()
    }

    // var Data = CreateData('11', 'CRRC_生产_RGV送料_确认修改', param)
    // ExecDatabase(Data).then(async response => {
    //   if (response.data.length > 0) {
    //     if (response.data[0].result == 1) {
    //
    //
    //       // 请求送料
    //       let reqFeed = await ExecWritePLC(store.user.opName, 100040, true)
    //       if (reqFeed.data.code != 0) {
    //         ElMessage.error('请求送料写入失败，终止送料')
    //         return;
    //       }
    //       ElMessage.success(response.data[0].msg)
    //       getRGVData()
    //     } else {
    //       ElMessage.error(response.data[0].msg)
    //     }
    //   } else {
    //     ElMessage.error('数据异常')
    //   }
    // })
  })
}

const submitLKPlan = async (item) => {
  console.log(item)
  ElMessageBox.confirm(
    '是否请求进行下料框?',
    '下料框确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    var param = {
      OPName: store.user.opName,
      Operator: store.user.AID,
    }
    let response = await ExecIMESAPI('WebReturnEmpty', param)
    if (response.data.code != 0) {
      ElMessage.error(response.data.msg)
    } else {
      ElMessage.success("请求下料成功！！")
    }
  })
}

const getStatusColor = (type) => {
  switch (type) {
    case 1:
      return '#d9001b'
    case 2:
      return '#f59a23'
    case 4:
      return '#02a862'
    default:
      return '#f2f2f2'
  }
}

const getLKStatusColor = (type) => {
  switch (type) {
    case 0:
      return '#aaa9a9'
    case 1:
      return '#f59a23'
    default:
      return '#f2f2f2'
  }
}

//连接MQTT
const connectMqtt = async () => {
  const topics = ['PLCToWebUI']
  // 连接选项
  const options = {
    keepalive: 60,          // 心跳时间
    reconnectPeriod: 3000,  // 重新连接间隔时间
    clean: true,            // 是否清除会话
    clientId: 'WEB_Op_' + getUUID(),//要确保唯一性，例如随机数或者UUID,
    username: '',//mqtt服务器配置里面的账号,
    password: ''//mqtt服务器配置里面的密码,
  }
  console.log(window.g.Mqtt_Ip)
  client = mqtt.connect(window.g.Mqtt_Ip, options);
  client.on('reconnect', (error) => {
    console.log('正在重连:', error)
    ElMessage.warning('正在重连' + error)
  })
  client.on('error', (error) => {
    console.log('连接失败:', error)
    ElMessage.warning('连接失败' + error)
  })
  client.on('connect', (e) => {
    console.log('MQTT连接成功');
    // 订阅多个主题
    client.subscribe(topics, { qos: 0 }, function (err) {
      if (!err) {
        console.log('订阅成功');
      } else {
        console.error('订阅失败:', err);
        ElMessage.warning('订阅失败' + err)
      }
    })
  })
  client.on('message', (topic, message, packet) => {
    messageHandle(topic, message.toString())
  })
}

// 获取连接状态
const getConnectionStatus = async () => {
  var param = []
  param[0] = ['ControlCode', window.g.API_MES_ControlCode]
  var Data = CreateData('11', 'CRRC_台位_Moby_连接状态初始化查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      let data = response.data[0]
      nowStatus.isSqlOnline = data.DBConnState === 1
      nowStatus.isMqttOnline = data.MQTTConnState === 1
      nowStatus.isMesOnline = data.MESConnState === 1
      nowStatus.isProductionOnline = data.MESConnState === 1
    }
  })
}

// 处理MQTT消息
const messageHandle = (topic, message) => {
  switch (topic) {
    case 'PLCToWebUI':
      let reqData = JSON.parse(message)
      console.log(reqData)
      if (reqData.OPCode == store.user.opName) {
        // 处理通道状态
        if (reqData.tagTypeCodeID == 100021) {
          nowStatus.isPeople = reqData.tagValue === '1'
        }
        // 处理RGV状态
        else if (reqData.tagTypeCodeID == 1002) {
          nowStatus.isRgvAlarm = reqData.tagValue === '1'
        }
        else if (reqData.tagTypeCodeID == 100001) {
          nowStatus.isRgvWorking = reqData.tagValue === '1'
        }
        else if (reqData.tagTypeCodeID == 100010) {
          nowStatus.isRgvIdle = reqData.tagValue === '1'
        }
        // 处理门禁状态
        else if (reqData.tagTypeCodeID == 100022) {
          nowStatus.isDoorLocked = reqData.tagValue === '1'
        }
      } else {
        // 处理连接状态
        switch (reqData.OPCode) {
          case 'OnLine_MES':
            nowStatus.isProductionOnline = reqData.tagValue === '1'
            nowStatus.isMesOnline = reqData.tagValue === '1'
            break
          case 'OnLine_Sql':
            nowStatus.isSqlOnline = reqData.tagValue === '1'
            break
          case 'OnLine_MQTT':
            nowStatus.isMqttOnline = reqData.tagValue === '1'
            break
        }
      }
      break;
    default:
      return
      break;
  }
}

const getUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
</script>

<style lang="scss" scoped>
.carMainData {
  width: 90vw;
  display: flex;
  flex-wrap: wrap;
  margin: 10vh auto 30px auto;
  border: 1px solid #a8a8a8;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  padding: 10px 0;

  &.two-columns {
    flex-wrap: nowrap;
    gap: 20px;

    .column {
      flex: 1;
      border-radius: 8px;
      padding: 15px;
      background: #f9f9f9;

      .column-title {
        width: 100% !important;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
      }

      .item-row {
        display: flex;
        width: 100%;
        margin: 5px 0;
        
        .item {
          flex: 1;
          display: flex;
          line-height: 32px;
          
          .title {
            width: 40%;
            text-align: right;
          }
        }
      }
    }
  }

  .item {
    width: 100%;
    margin: 5px 0;
    display: flex;
    line-height: 32px;

    .title {
      width: 40%;
      text-align: right;
    }
  }

  .two-columns .item {
    width: auto;
  }
}

.button {
  width: 100vw;
  display: flex;
  justify-content: center;
  font-size: 26px;
  line-height: 80px;
  margin: 1vh auto 0 auto;


  :deep(.el-checkbox.el-checkbox--large) {
    zoom: 200%;
  }
}

.table {
  width: 95vw;
  margin: 2vh auto 30px auto;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  text-align: center;

  //.row:first-child {
  //  height: 5vh;
  //  line-height: 5vh;
  //  font-size: 17px;
  //}

  .row {
    display: flex;
    width: 100%;
    height: 6vh;
    line-height: 6vh;
    font-size: 18px;

    div {
      flex: 1;
      border: 1px solid #686868;
    }

    :first-child {
      flex: 1.5;
    }

    :last-child {
      flex: 2;
    }
  }

  .row.title {
    font-weight: bold;
    font-size: 21px;
  }
}

.topOp {
  position: absolute;
  top: 7vh;
  left: 5vw;
  font-size: 2vw;

  .text {
    background-color: #008000;
    margin-left: 20px;
    padding: 0 1vw;
    color: #fff;
  }
}

.status-box {
  width: 70vw;
  margin: 2vh auto;
  padding: 20px 0;
  background: #fff;
  border: 1px solid #a8a8a8;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  border-radius: 10px;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
  }

  .status-content {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
  }

  .status-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;

    .status-title {
      min-width: 100px;
      text-align: right;
      color: #333;
      font-weight: 500;
    }

    .status-value {
      padding: 4px 12px;
      border-radius: 4px;
      color: #fff;
      font-weight: 500;
      min-width: 80px;
      text-align: center;

      &.success {
        background-color: #00802d;
      }

      &.warning {
        background-color: #ff9900;
      }

      &.danger {
        background-color: #b32f43;
      }

      &.info {
        background-color: #7b7e87;
      }
    }
  }
}

.carMainData {
  margin-top: 2vh;
  width: 95vw;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid #a8a8a8;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  padding: 10px 0;

  .title {
    width: 100%;
    text-align: center;
    font-size: 20px;
    font-weight: bold;
  }

  .item {
    width: 50%;
    margin: 5px 0;
    display: flex;
    line-height: 32px;

    .title {
      width: 30%;
      text-align: right;
    }
  }
}
</style>
