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

  <div class="main">
    <!-- 状态显示框 -->
    <div class="status-box">
      <div class="title">状态监控</div>
      <div class="status-content">
        <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="project-box">
      <div class="title">项目信息</div>
      <div class="project-content">
        <div class="project-item">
          <div class="project-title">项目编号：</div>
          <el-autocomplete v-model="carInputData.projectNo" :fetch-suggestions="(queryString, cb) => {
            const results = queryString
              ? projectList.filter(item => item.项目编号.toLowerCase().includes(queryString.toLowerCase()))
              : projectList
            cb(results.map(item => ({
              value: item.项目编号,
              label: `${item.项目编号} - ${item.项目名称}`
            })))
          }" placeholder="请输入或选择项目编号" clearable @select="({ value }) => handleProjectChange(value)"
            @input="handleProjectInput" @blur="handleProjectBlur" style="width: 86%" />
        </div>
        <div class="project-item">
        </div>
        <div class="project-item">
          <div class="project-title">项目名称：</div>
          <el-input v-model="carInputData.projectName" placeholder="项目名称" />
        </div>
        <div class="project-item">
          <div class="project-title">车体：</div>
          <el-select v-model="carInputData.carBody" filterable allow-create placeholder="请输入或选择车体" clearable
            style="flex: 1">
            <el-option v-for="item in carBodyList" :key="item.车体" :label="item.车体" :value="item.车体" />
          </el-select>
        </div>
        <div class="project-item">
          <div class="project-title">车号：</div>
          <el-input v-model="carInputData.carNo" placeholder="车号" />
        </div>
        <div class="project-item">
          <div class="project-title">伸缩缝：</div>
          <el-select v-model="carInputData.expansionJoint" filterable allow-create placeholder="请输入或选择伸缩缝" clearable
            style="flex: 1">
            <el-option v-for="item in expansionJointList" :key="item.伸缩缝" :label="item.伸缩缝" :value="item.伸缩缝" />
          </el-select>
        </div>
        <div class="project-item">
          <div class="project-title">车节：</div>
          <el-select v-model="carInputData.carSection" filterable allow-create placeholder="请输入或选择车节号" clearable
            @change="editCarSection" style="flex: 1">
            <el-option v-for="item in carSectionList" :key="item.车节" :label="item.车节" :value="item.车节" />
          </el-select>
        </div>
        <div class="project-item">
          <div class="project-title">调节参数：</div>
          <el-select v-model="carInputData.adjustTheParameters" filterable allow-create placeholder="请输入或选择调节参数"
            clearable style="flex: 1">
            <el-option v-for="item in adjustParametersList" :key="item.调节参数" :label="item.调节参数" :value="item.调节参数" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button plain type="danger" @click="carPlace">车体到位</el-button>
      <el-button :disabled="carInputData.fenceTime" plain type="primary" @click="guardrailsAreInstalledInPlace">
        护栏安装到位
      </el-button>
      <el-button plain type="warning" @click="carLeave">车体离位</el-button>
    </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 { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import mqtt from "mqtt";

const router = useRouter()
const store = useAppStore()
const { user, isLoading, routerData } = storeToRefs(store)

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

const isEnableUI = ref(false)

const carSectionList = reactive([])
const projectList = reactive([])
const carBodyList = reactive([]) // 车体列表
const expansionJointList = reactive([]) // 伸缩缝列表
const adjustParametersList = reactive([]) // 调节参数列表
const carInputData = reactive({
  projectNo: '', // 项目编号
  projectName: '', // 项目名称
  carNo: '',  // 车号
  carSection: '',  // 车节
  carBody: '',   // 车体
  carBodyCode: '',   // 车体流水号
  expansionJoint: '',  // 伸缩缝
  adjustTheParameters: '',  // 调节参数
  fenceTime: '',  // 护栏安装到位时间
  pos1: true,
  pos2: true,
  pos3: true,
  pos4: true,
  pos5: true,
})

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连接
})

var client = null
var timer1 = null

onMounted(() => {
  getCarData()
  getCarSectionList()
  getProjectList()
  getCarBodyList()
  getExpansionJointList()
  getAdjustParametersList()
  connectMqtt()
  // 初始化时获取所有状态
  getConnectionStatus()
})

// 离开网页 删除定时器
onUnmounted(() => {
  try {
    if (client) {
      client.end();
    }
  } catch (error) {
    console.log('关闭连接失败:', error);
  }
  client = null;
})

//连接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) {
        // 处理连接状态
        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);
  });
}

const getCarData = () => {
  // 获取权限列表
  var param = []
  param[0] = ['opName', store.user.opName]
  var Data = CreateData('11', 'CRRC_台位_Moby_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      let data = response.data[0]
      carInputData.projectNo = data.项目编号
      carInputData.projectName = data.项目名称
      carInputData.carNo = data.车号
      carInputData.carSection = data.车节
      carInputData.carBody = data.车体参数1
      carInputData.carBodyCode = data.车体流水号
      carInputData.expansionJoint = data.伸缩缝参数1
      carInputData.adjustTheParameters = data.调节参数1
      carInputData.fenceTime = data.护栏安装到位确认时间
      carInputData.pos1 = data.位置1 == 1
      carInputData.pos2 = data.位置2 == 1
      carInputData.pos3 = data.位置3 == 1
      carInputData.pos4 = data.位置4 == 1
      carInputData.pos5 = data.位置5 == 1
    }
  })
}

const getCarSectionList = () => {
  carSectionList.length = 0
  // 获取车节列表
  var param = []
  param.push(['参数类型', '车节'])
  var Data = CreateData('11', 'CRRC_基础数据_车体参数_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      carSectionList.push(...response.data)
    }
  })
}

// 获取车体列表
const getCarBodyList = () => {
  carBodyList.length = 0
  var param = []
  param.push(['参数类型', '车体'])
  var Data = CreateData('11', 'CRRC_基础数据_车体参数_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      carBodyList.push(...response.data)
    }
  })
}

// 获取伸缩缝列表
const getExpansionJointList = () => {
  expansionJointList.length = 0
  var param = []
  param.push(['参数类型', '伸缩缝'])
  var Data = CreateData('11', 'CRRC_基础数据_车体参数_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      expansionJointList.push(...response.data)
    }
  })
}

// 获取调节参数列表
const getAdjustParametersList = () => {
  adjustParametersList.length = 0
  var param = []
  param.push(['参数类型', '调节参数'])
  var Data = CreateData('11', 'CRRC_基础数据_车体参数_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      adjustParametersList.push(...response.data)
    }
  })
}

const getProjectList = () => {
  projectList.length = 0
  var param = []
  var Data = CreateData('11', 'CRRC_车体_项目_下拉查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      projectList.push(...response.data)
    }
  })
}

const handleProjectChange = (val) => {
  // 查找选中的项目
  const selectedProject = projectList.find(item => item.项目编号 === val)
  if (selectedProject) {
    // 同步更新项目名称
    carInputData.projectName = selectedProject.项目名称
  }
  // 如果车节也有值，查询历史车体参数
  if (carInputData.carSection) {
    getHistoryCarBody()
  }
}

// 处理项目编号输入
const handleProjectInput = (val) => {
  // 查找是否有匹配的项目
  const matchedProject = projectList.find(item => item.项目编号 === val)
  if (matchedProject) {
    carInputData.projectName = matchedProject.项目名称
  } else {
    carInputData.projectName = ''
  }
}

// 处理项目编号失焦
const handleProjectBlur = () => {
  // 如果车节也有值，查询历史车体参数
  if (carInputData.projectNo && carInputData.carSection) {
    getHistoryCarBody()
  }
}

// 处理车节选择
const handleCarSectionChange = (val) => {
  editCarSection()
}

// 处理车节输入
const handleCarSectionInput = (val) => {
  // 输入时暂不做处理，等失焦时再查询
}

// 处理车节失焦
const handleCarSectionBlur = () => {
  // 先尝试从车节列表中查找匹配的记录
  for (let i = 0; i < carSectionList.length; i++) {
    if (carSectionList[i].车节 == carInputData.carSection) {
      let clickItem = carSectionList[i]
      carInputData.carBody = clickItem.车体参数1
      carInputData.expansionJoint = clickItem.伸缩缝参数1
      carInputData.adjustTheParameters = clickItem.调节参数1
      break
    }
  }
  // 如果项目编号也有值，查询历史车体参数
  if (carInputData.projectNo && carInputData.carSection) {
    getHistoryCarBody()
  }
}

const editCarSection = () => {
  // 获取 车节列表对应项
  for (let i = 0; i < carSectionList.length; i++) {
    if (carSectionList[i].车节 == carInputData.carSection) {
      let clickItem = carSectionList[i]
      carInputData.carBody = clickItem.车体参数1
      carInputData.expansionJoint = clickItem.伸缩缝参数1
      carInputData.adjustTheParameters = clickItem.调节参数1
    }
  }
  // 如果项目编号也有值，查询历史车体参数
  if (carInputData.projectNo) {
    getHistoryCarBody()
  }
}

// 查询历史车体参数
const getHistoryCarBody = () => {
  if (!carInputData.projectNo || !carInputData.carSection) {
    return
  }
  var param = []
  param.push(['项目编号', carInputData.projectNo])
  param.push(['车节', carInputData.carSection])
  var Data = CreateData('11', 'CRRC_基础数据_车体参数_根据项目号车节_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      // 直接将查询到的结果赋值到输入框
      carInputData.carBody = response.data[0].车体 || ''
      carInputData.expansionJoint = response.data[0].伸缩缝 || ''
      carInputData.adjustTheParameters = response.data[0].调节参数 || ''
    }
  }).catch(error => {
    console.error('查询历史车体参数失败:', error)
  })
}

// 初始化
const carInit = async () => {
  var param = {
    OPName: store.user.opName,
    Operator: store.user.AID
  }
  let response = await ExecIMESAPI('WebInit', param)
  if (response.data.code != 0) {
    ElMessage.error(response.data.msg)
  } else {
    ElMessage.success('初始化成功！')
    getCarData()
  }
}

// 车体到位
const carPlace = async () => {
  var param = {
    OPName: store.user.opName,
    ProBH: carInputData.projectNo,
    ProName: carInputData.projectName,
    CarBH: carInputData.carNo,
    CarBody: carInputData.carSection,
    CarBodyParam: carInputData.carBody, // 车体参数
    ExpansionJoint: carInputData.expansionJoint, // 伸缩缝参数
    AdjustParam: carInputData.adjustTheParameters, // 调节参数
    // Position_1: carInputData.pos1 ? 1 : 0,
    // Position_2: carInputData.pos2 ? 1 : 0,
    // Position_3: carInputData.pos3 ? 1 : 0,
    // Position_4: carInputData.pos4 ? 1 : 0,
    // Position_5: carInputData.pos5 ? 1 : 0,
    Operator: store.user.AID
  }
  let response = await ExecIMESAPI('CarArrived', param)
  if (response.data.code != 0) {
    ElMessage.error(response.data.msg)
  } else {
    ElMessage.success('车体到位成功！')
    getCarData()
    getCarBodyList()
    getExpansionJointList()
    getAdjustParametersList()
    getCarSectionList()
    getProjectList()
    // routerTo({path: 'MaterialPlatform'})
  }
}

// 车体离位
const carLeave = async () => {
  // let responseReadPLC = await ExecWritePLC(store.user.opName, 100001, 0)
  // if (responseReadPLC.data.code == 0) {
  //   var param = []
  //   param.push(['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)
  //         getCarData()
  //       } else {
  //         ElMessage.error(response.data[0].msg)
  //       }
  //     } else {
  //       ElMessage.error('数据异常')
  //     }
  //   })
  // } else {
  //   ElMessage.error(responseReadPLC.data.msg)
  // }
  var param = {
    OPName: store.user.opName,
    Operator: store.user.AID
  }
  let response = await ExecIMESAPI('CarLeave', param)
  if (response.data.code != 0) {
    ElMessage.error(response.data.msg)
  } else {
    ElMessage.success('车体离位成功！')
    getCarData()
    getCarBodyList()
    getExpansionJointList()
    getAdjustParametersList()
    getCarSectionList()
    getProjectList()
    // routerTo({path: 'MaterialPlatform'})
  }
}

// 护栏安装到位  更新到 moby 不点无所谓 不跳转可不选
const guardrailsAreInstalledInPlace = async () => {
  // // 判断当前是否有初始化的车体 有才允许点击CarBodyPlace 
  // if (carInputData.carBody == '') {
  //   ElMessage.error('请先选择车体')
  //   return
  // }
  // if (carInputData.carBodyCode == '') {
  //   ElMessage.error('请先选择车体流水号')
  //   return
  // }
  // 二次确认护栏是否安装到位
  ElMessageBox.confirm('护栏是否安装到位？', '二次确认').then(() => {
    var param = []
    param.push(['opName', store.user.opName])
    var Data = CreateData('11', 'CRRC_台位_Moby_护栏安装到位', param)
    ExecDatabase(Data).then(response => {
      if (response.data.length > 0) {
        if (response.data[0].result === 1) {
          ElMessage.success(response.data[0].msg)
          getCarData()
        } else {
          ElMessage.error(response.data[0].msg)
        }
      } else {
        ElMessage.error('数据异常')
      }
    })
  })
}

const routerTo = (item) => {
  const targetRoute = routerData.value.userRouterList.find(r => r.path === item.path)
  if (targetRoute) {
    routerData.nowRouterPath = targetRoute.path
    routerData.nowRouterTitle = targetRoute.权限模块
    routerData.selected = true
    router.push({ path: '/' + targetRoute.path })

    console.log(targetRoute)
  }
}

</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 3vh;

  .title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
  }

  .status-box,
  .project-box {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
  }

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

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

  .status-title {
    width: 100px;
    text-align: right;
    color: #666;
  }

  .status-value {
    padding: 4px 12px;
    border-radius: 4px;
    color: #fff;
    font-weight: 500;

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

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

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

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

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

  .project-item {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .project-title {
    width: 100px;
    text-align: right;
    color: #666;
  }

  .project-value {
    flex: 1;
    padding: 8px 12px;
    background: #f5f7fa;
    border-radius: 4px;
    color: #333;
  }

  .el-input,
  .el-select,
  .el-autocomplete {
    flex: 1;
  }

  .button-group {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-top: 30px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .el-button {
      width: 180px;
      height: 60px;
      font-size: 20px;
      border-radius: 8px;
      font-weight: bold;
      letter-spacing: 2px;

      &:hover {
        transform: scale(1.05);
        transition: all 0.3s ease;
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }
}

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

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