<template>
  <div class="container">
    <!-- 数据栏 -->
    <div class="data-section">
      <div class="data-grid">
        <div class="data-item">
          <span class="label">工位名称：</span>
          <span class="value">{{ user.opNameText }}</span>
        </div>
        <div class="data-item">
          <span class="label">工位编号：</span>
          <span class="value">{{ user.opName }}</span>
        </div>
        <div class="data-item">
          <span class="label">操作者：</span>
          <span class="value">{{ user.name }}</span>
        </div>
        <div class="data-item">
          <span class="label">产品编号：</span>
          <span class="value long-text">{{ opSatus.productNumber }}</span>
        </div>
        <div class="data-item">
          <span class="label">产品型号：</span>
          <span class="value">{{ opSatus.productModel }}</span>
        </div>
        <div class="data-item">
          <span class="label">订单号：</span>
          <span class="value">{{ opSatus.orderNumber }}</span>
        </div>
      </div>
      <div class="data-item chassis-item">
        <span class="label">底盘编号：</span>
        <span class="value">{{ opSatus.chassisNumber }}</span>
      </div>
    </div>

    <!-- 功能按钮 -->
    <div class="button-section">
      <el-button type="primary" class="action-button" @click="showScanDialog">
        产品进站
      </el-button>
      <el-button type="warning" class="action-button" @click="handleProblemReport">
        检查项确认
      </el-button>
      <el-button type="success" class="action-button" @click="handleProcessComplete">
        装配完成
      </el-button>
      <el-button type="danger" class="action-button" @click="handleLogout">
        退出登录
      </el-button>
    </div>

    <!-- 扫码弹窗 -->
    <el-dialog v-model="scanDialogVisible" title="扫码" width="80%" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <div class="scan-dialog-content">
        <el-input v-model="scanCode" placeholder="请扫描或输入随车码" size="large" @keyup.enter="submitScanCode" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeScanDialog">取消</el-button>
          <el-button type="primary" @click="submitScanCode">
            提交码值
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 装配完成弹窗 -->
    <el-dialog v-model="workFinishDialogVisible" title="装配完成" width="80%" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <div class="work-finish-dialog-content">
        <el-form :model="workFinishForm" :rules="workFinishFormRules" ref="workFinishFormRef">
          <el-form-item label="订单号：" prop="orderCode">
            <el-input v-model="workFinishForm.orderCode" readonly />
          </el-form-item>
          <el-form-item label="产品编号：" prop="productNumber">
            <el-input v-model="workFinishForm.productNumber" readonly />
          </el-form-item>
          <el-form-item label="产品型号：" prop="productModel">
            <el-input v-model="workFinishForm.productModel" readonly />
          </el-form-item>
          <el-form-item label="底盘编号：" prop="chassisNumber">
            <el-input v-model="workFinishForm.chassisNumber" readonly />
          </el-form-item>
          <el-form-item label="结果：" prop="isOk">
            <el-select v-model="workFinishForm.isOk" placeholder="请选择结果">
              <el-option label="通过" value="1" />
              <el-option label="未通过" value="0" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="workFinishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="finishWorkSubmit">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 检查项弹窗 -->
    <el-dialog v-model="checkItemsDialogVisible" title="检查项确认" :top="'10vh'" width="100%"
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div v-loading="checkItemsLoading" class="check-items-dialog-content">
        <el-table :data="checkItemsList" border style="width: 100%" max-height="400px">
          <el-table-column prop="排序" label="序号" width="60" align="center" />
          <el-table-column prop="检查内容" label="检查内容" min-width="120">
            <template #default="scope">
              <div class="multiline-cell">{{ scope.row.检查内容 }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="检查要求" label="检查要求" min-width="180">
            <template #default="scope">
              <div class="multiline-cell">{{ scope.row.检查要求 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.检查结果 === '0'" type="warning">未确认</el-tag>
              <el-tag v-else-if="scope.row.检查结果 === '1'" type="success">OK</el-tag>
              <el-tag v-else-if="scope.row.检查结果 === '2'" type="danger">NOK</el-tag>
              <span v-else>{{ scope.row.检查结果 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <div v-if="scope.row.检查结果 === '0'">
                <el-button type="success" size="mini" @click="handleCheckResult(scope.row, '1')">OK</el-button>
                <el-button type="danger" size="mini" @click="handleCheckResult(scope.row, '2')">NOK</el-button>
              </div>
              <div v-else>
                <el-button type="info" size="mini" disabled>已确认</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="检查备注" label="备注" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.检查结果 !== '0'">{{ scope.row.检查备注 || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkItemsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- NOK备注弹窗 -->
    <el-dialog v-model="nokRemarkDialogVisible" title="NOK备注" width="500px" :append-to-body="true">
      <el-form :model="nokRemarkForm" ref="nokRemarkFormRef" :rules="nokRemarkRules">
        <el-form-item label="NOK原因" prop="remark" label-width="80px">
          <el-input v-model="nokRemarkForm.remark" type="textarea" :rows="3" placeholder="请输入NOK原因">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="nokRemarkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmNokRemark">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

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

const ExecDatabaseByParam = inject('ExecDatabaseByParam')

const isEnableUI = ref(false)

const carSectionList = reactive([])
const opSatus = reactive({
  workstationName: '',
  workstationCode: '',
  operator: '',
  productNumber: '',
  productModel: '',
  orderNumber: '',
  chassisNumber: '',
})

const nowStatus = reactive({
  isPeople: false,
  isCarArrive: false,
  isRgvShipping: false,
})

var timer1 = null

// 扫码相关
const scanDialogVisible = ref(false)
const scanCode = ref('')

// 装配完成相关
const workFinishDialogVisible = ref(false)
const workFinishForm = reactive({
  orderCode: '',
  productNumber: '',
  productModel: '',
  chassisNumber: '',
  isOk: '1'
})
const workFinishFormRef = ref(null)
const workFinishFormRules = {
  orderCode: [
    { required: true, message: '请输入订单号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  productNumber: [
    { required: true, message: '请输入产品编号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  productModel: [
    { required: true, message: '请输入产品型号', trigger: 'blur' },
    { min: 0, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  chassisNumber: [
    { required: true, message: '请输入底盘编号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  isOk: [
    { required: true, message: '请选择结果', trigger: 'change' }
  ]
}

// 检查项相关
const checkItemsDialogVisible = ref(false)
const checkItemsLoading = ref(false)
const checkItemsList = ref([])
const nokRemarkDialogVisible = ref(false)
const nokRemarkForm = reactive({
  id: null,
  remark: '',
  resultType: ''
})
const nokRemarkRules = {
  remark: [
    { required: true, message: '请输入NOK原因', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ]
}

onMounted(() => {
  setTimeout(() => {
    getOpMoby()
  }, 1000)
  store.isLoading = false
})

// 离开网页 删除定时器
onUnmounted(() => {
  clearInterval(timer1)
})

// 显示扫码弹窗
const showScanDialog = async () => {
  await getOpMoby()
  if (opSatus.productNumber != '') {
    ElMessage.warning('当前工件未离站 不可重新进站')
    return
  }

  scanCode.value = ''
  scanDialogVisible.value = true
}

// 关闭扫码弹窗
const closeScanDialog = () => {
  scanDialogVisible.value = false
  scanCode.value = ''
}

// 提交扫码数据
const submitScanCode = async () => {
  if (!scanCode.value) {
    ElMessage.warning('请输入随车码')
    return
  }

  try {
    const param = []
    param[0] = ['工位号', user.value.opName]
    param[1] = ['产品编码', scanCode.value]
    param[2] = ['操作者', user.value.name]
    let response = await ExecDatabaseByParam('11', 'CATL_测量数据车体MOBY_车体进站', param)
    if (response.data.length > 0) {
      const isOk = response.data[0].是否合格
      const msg = response.data[0].msg
      if (isOk === 1) {
        ElMessage.success(msg || '产品进站成功')
        closeScanDialog()
        getOpMoby()
      } else {
        ElMessage.error(msg || '产品进站失败')
      }
    } else {
      ElMessage.error('产品进站失败！')
    }
  } catch (error) {
    console.error('提交失败：', error)
    ElMessage.error('系统错误，请重试')
  }
}

// 获取工位数据
const getOpMoby = async () => {
  let param = []
  console.log(store.user.opName)
  param[0] = ['工位号', store.user.opName]
  let response = await ExecDatabaseByParam('11', 'CATL_测量数据工位MOBY_详细信息_查询', param)
  if (response.data.length > 0) {
    opSatus.workstationName = response.data[0].工位名称
    opSatus.workstationCode = response.data[0].工位编号
    opSatus.operator = response.data[0].操作者
    opSatus.productNumber = response.data[0].Last_发动机号
    opSatus.productModel = response.data[0].Last_机型号
    opSatus.orderNumber = response.data[0].Last_工单号
    opSatus.chassisNumber = response.data[0].车体二维码
  } else {
    opSatus.workstationName = ''
    opSatus.workstationCode = ''
    opSatus.productNumber = ''
    opSatus.productModel = ''
    opSatus.orderNumber = ''
    opSatus.chassisNumber = ''
  }
}

// 装配完成前检查
const handleProcessComplete = async () => {
  if (!opSatus.productNumber) {
    ElMessage.error('工位未在工作!')
    return
  }

  try {
    let param = []
    param[0] = ['产品编码', opSatus.productNumber]
    let response = await ExecDatabaseByParam('11', 'CATL_测量数据_出站前检查', param)

    if (response.data.length > 0) {
      const isOk = response.data[0].是否合格
      const msg = response.data[0].msg
      if (isOk === 1) {
        showFinishDialog()
      } else {
        ElMessage.error(msg || '出站检查未通过')
      }
    } else {
      ElMessage.error('产品出站失败！')
    }
  } catch (error) {
    console.error('出站检查失败：', error)
    ElMessage.error('系统错误，请重试')
  }
}

// 显示装配完成弹窗
const showFinishDialog = () => {
  workFinishForm.orderCode = opSatus.orderNumber
  workFinishForm.productNumber = opSatus.productNumber
  workFinishForm.productModel = opSatus.productModel
  workFinishForm.chassisNumber = opSatus.chassisNumber
  workFinishForm.isOk = '1'
  workFinishDialogVisible.value = true
}

// 装配完成提交
const finishWorkSubmit = async () => {
  try {
    let param = []
    param[0] = ['发动机流水号', workFinishForm.productNumber]
    param[1] = ['工位编码', user.value.opName]
    param[2] = ['托盘号', 1]
    param[3] = ['过点属性', 1]
    param[4] = ['采集时间', '']
    param[5] = ['操作者', user.value.name]
    param[6] = ['合格标志', workFinishForm.isOk]
    param[7] = ['过站状态', 1]
    param[8] = ['岔道上下件', 1]
    param[9] = ['重量', '0']
    param[10] = ['操作标记', 1]
    param[11] = ['车体二维码', workFinishForm.chassisNumber]
    let response = await ExecDatabaseByParam('12', 'Event_MOM_过点数据', param)
    if (response.data.length > 0 && response.data[0].result == "1") {
      ElMessage.success('装配完成')
      workFinishDialogVisible.value = false
      getOpMoby() // 刷新数据
    } else {
      ElMessage.error(response.data[0]?.msg || '装配完成失败')
    }
  } catch (error) {
    console.error('装配完成失败：', error)
    ElMessage.error('系统错误，请重试')
  }
}

// 检查项相关
const handleProblemReport = async () => {
  if (!opSatus.productNumber) {
    ElMessage.error('工位未在工作!')
    return
  }

  checkItemsDialogVisible.value = true
  loadCheckItems()
}

// 加载检查项列表
const loadCheckItems = async () => {
  checkItemsLoading.value = true
  try {
    let param = []
    param[0] = ['工位号', user.value.opName]
    param[1] = ['工件编号', opSatus.productNumber]

    let response = await ExecDatabaseByParam('11', 'CATL_工位检查项_记录表_工位查询', param)
    checkItemsList.value = response.data || []
  } catch (error) {
    console.error('加载检查项失败：', error)
    ElMessage.error('加载检查项失败')
  } finally {
    checkItemsLoading.value = false
  }
}

// 处理检查结果
const handleCheckResult = (row, resultType) => {
  if (resultType === '2') {
    // NOK需要填写备注
    nokRemarkForm.id = row.ID
    nokRemarkForm.resultType = resultType
    nokRemarkForm.remark = ''
    nokRemarkDialogVisible.value = true
  } else {
    // OK直接提交
    submitCheckResult(row.ID, resultType, '')
  }
}

// 确认NOK备注
const confirmNokRemark = () => {
  if (!nokRemarkForm.remark) {
    ElMessage.warning('请输入NOK原因')
    return
  }
  submitCheckResult(nokRemarkForm.id, nokRemarkForm.resultType, nokRemarkForm.remark)
  nokRemarkDialogVisible.value = false
}

// 提交检查结果
const submitCheckResult = async (id, resultType, remark) => {
  try {
    let param = []
    param[0] = ['ID', id]
    param[1] = ['操作者', user.value.name]
    param[2] = ['检查结果', resultType]
    param[3] = ['检查备注', remark]

    let response = await ExecDatabaseByParam('12', 'CATL_工位检查项_记录表_工位检查确认', param)

    if (response.data?.[0]?.result === '1') {
      ElMessage.success(resultType === '1' ? '检查项确认OK' : '检查项确认NOK')
      loadCheckItems() // 刷新列表
    } else {
      ElMessage.error('提交失败')
    }
  } catch (error) {
    console.error('提交检查结果失败：', error)
    ElMessage.error('提交失败')
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.warning('退出登录成功!')
    store.$reset() // 重置pinia数据
    router.push('/login')
  }).catch(() => { })
}

</script>

<style lang="scss" scoped>
.container {
  height: 80vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f7fa;
}

.data-section {
  flex: 1;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 15px;
}

.data-item {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;

  .label {
    width: 120px;
    color: #606266;
    font-weight: bold;
  }

  .value {
    flex: 1;
    color: #303133;
    word-break: break-all;
  }

  .long-text {
    font-size: 1rem;
  }
}

.chassis-item {
  grid-column: 1 / -1;
  border-top: 2px solid #dcdfe6;
  margin-top: 10px;
  padding-top: 15px;
}

.button-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-button {
  height: 60px;
  font-size: 1.2rem;
  border-radius: 8px;
}

.el-button+.el-button {
  margin-left: 0px;
}

// 响应式调整
@media screen and (max-width: 1024px) {
  .data-item {
    font-size: 1rem;

    .label {
      width: 100px;
    }
  }

  .action-button {
    height: 50px;
    font-size: 1rem;
  }
}

.scan-dialog-content {
  padding: 20px;

  .el-input {
    width: 100%;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 调整按钮样式
.button-section {
  .el-button--danger {
    background-color: #f56c6c;
    border-color: #f56c6c;

    &:hover {
      background-color: #f78989;
      border-color: #f78989;
    }
  }
}

.work-finish-dialog-content {
  padding: 20px;
}

.check-items-dialog-content {
  padding: 20px;
}

.nok-remark-dialog-content {
  padding: 20px;
}

.multiline-cell {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
}
</style>
