<template>
  <ContentWrap>
    <el-tabs
      v-model="activeTab"
      type="border-card"
      tab-position="left"
      v-loading="loading"
      style="height: 84vh"
    >
      <el-tab-pane
        style="height: 100%"
        v-for="(tab, tabIndex) in tabs"
        :key="tab.deviceName"
        :name="String(tabIndex)"
      >
        <template #label>
          <span class="custom-label">
            {{ tab.deviceName }} ({{ completedSteps(tabIndex) }}/{{ tab.orderDetails.length }})
                  <el-tooltip :content="tab.routeDesc" placement="top" effect="dark">
                    <Icon icon="ep:info-filled" />
                  </el-tooltip>
          </span>
        </template>

        <div class="step-container">
          <el-steps direction="vertical" :active="currentStep[tabIndex]" class="steps-nav">
            <el-step
              v-for="(step, stepIndex) in tab.orderDetails"
              :key="stepIndex"
              :title="`${step.item}`"
              :status="getStepStatus(tabIndex, stepIndex)"
            >
              <template #title>
                <div class="step-title-wrapper">
                  <span class="title-text">{{ step.item }}</span>
                  <el-tooltip :content="step.standard" placement="top" effect="dark">
                    <Icon icon="ep:info-filled" />
                  </el-tooltip>
                </div>
              </template>
            </el-step>
          </el-steps>

          <div class="form-wrapper">
            <ContentWrap>
              <el-form
                :model="formData[tabIndex][currentStep[tabIndex]]"
                :rules="formRules"
                ref="formRefs"
                label-width="120px"
              >
                <el-form-item label="设备id" v-if="false" prop="deviceId">
                  <el-input
                    v-model="formData[tabIndex][currentStep[tabIndex]].deviceId"
                    :model-value="tab.deviceId"
                    clearable
                  />
                </el-form-item>
                <el-form-item :label="t('inspect.isException')" prop="ifNormal">
                  <el-select
                    v-model="formData[tabIndex][currentStep[tabIndex]].ifNormal"
                    :placeholder="t('inspect.isException')"
                    clearable
                  >
                    <el-option
                      v-for="dict in getBoolDictOptions(DICT_TYPE.PMS_INSPECT_WRITE)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item
                  :label="t('inspect.exceptionDes')"
                  prop="description"
                  :rules="formData[tabIndex][currentStep[tabIndex]].ifNormal ?  []: descriptionRule"
                >
                  <el-input
                    v-model="formData[tabIndex][currentStep[tabIndex]].description"
                    type="textarea"
                    :rows="5"
                    :placeholder="t('inspect.exceptionDes')"
                  />
                </el-form-item>

                <el-form-item :label="t('deviceForm.picture')" prop="picUrl">
                  <UploadImg
                    v-model="formData[tabIndex][currentStep[tabIndex]].picUrl"
                    height="55px"
                    width="30em"
                  />
                </el-form-item>
              </el-form>

              <div class="navigation-controls">
                <el-button :disabled="currentStep[tabIndex] === 0" @click="handlePrev(tabIndex)">
                  上一步
                </el-button>

                <el-button
                  type="primary"
                  :disabled="!isStepValid(tabIndex)"
                  @click="handleNext(tabIndex, tab.deviceId)"
                >
                  {{ isLastStep(tabIndex) ? '完成提交' : '下一步' }}
                </el-button>
              </div>
            </ContentWrap>
            <ContentWrap style="margin-top: 50px">
              <el-card>
                <span style="font-weight: bold">{{ t('inspect.InspectionStandards') }}：</span
                >{{ tab.orderDetails[currentStep[tabIndex]].standard }}<br />
                <el-divider />
                <span style="font-weight: bold">{{ t('fileInfo.appendix') }}：</span>
                <el-button
                  v-if="tab.orderDetails[currentStep[tabIndex]].urls"
                  link
                  type="primary"
                  @click="openWeb(tab.orderDetails[currentStep[tabIndex]].urls)"
                >
                  <Icon size="19" icon="ep:view" />
                  {{ t('action.preview') }}
                </el-button>
              </el-card>
            </ContentWrap>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup>
import { useTagsViewStore } from '@/store/modules/tagsView'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { IotInspectOrderApi } from '@/api/pms/inspect/order'
import { DICT_TYPE, getBoolDictOptions } from '@/utils/dict'

defineOptions({ name: 'InspectOrderWrite' })
const { t } = useI18n() // 国际化

const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const message = useMessage() // 消息弹窗
const tabs = ref([])
const { params, name } = useRoute() // 查询参数
const id = params.id
onMounted(async () => {
  if (id) {
    const iotInspectOrderDetail = await IotInspectOrderApi.getIotInspectOrderDetail(id)
    tabs.value = iotInspectOrderDetail
    initFormData(iotInspectOrderDetail)
    loading.value = false
  }
})
const openWeb = (url) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
// 响应式状态
const loading = ref(true)
const activeTab = ref('0')
const currentStep = ref({})
const formRefs = ref([])
const formData = reactive([])
const descriptionRule = [{ required: true, message: '描述不能为空', trigger: 'blur' }]
// 表单验证规则
const formRules = reactive({
  ifNormal: [{ required: true, message: '请输入是否异常', trigger: 'blur' }]
  // description: [
  //   { required: true, message: '请输入异常描述', trigger: 'blur' },
  // ],
})

// 初始化表单数据
const initFormData = (tabsData) => {
  tabsData.forEach((tab, tabIndex) => {
    formData[tabIndex] = tab.orderDetails.map((item) => ({
      deviceId: item.deviceId,
      indexId: item.indexId,
      ifNormal: item.ifNormal,
      description: item.description,
      picUrl: item.picUrl
    }))
    currentStep.value[tabIndex] = 0
  })
}

// 步骤状态计算
const getStepStatus = (tabIndex, stepIndex) => {
  if (stepIndex < currentStep.value[tabIndex]) return 'finish'
  return stepIndex === currentStep.value[tabIndex] ? 'process' : 'wait'
}

// 完成步骤数计算
const completedSteps = (tabIndex) => {
  return formData[tabIndex].filter((item) => item.ifNormal != null).length
}

// 步骤验证
const isStepValid = (tabIndex) => {
  const current = currentStep.value[tabIndex]
  if (
    formData[tabIndex][current].ifNormal === null ||
    formData[tabIndex][current].ifNormal === undefined
  ) {
    return false
  }
  if (
    !formData[tabIndex][current].ifNormal &&
    (formData[tabIndex][current].description === undefined ||
      formData[tabIndex][current].description === null ||
      formData[tabIndex][current].description === '')
  ) {
    return false
  }
  return true
}

// 导航控制
const handlePrev = (tabIndex) => {
  if (currentStep.value[tabIndex] > 0) {
    currentStep.value[tabIndex]--
  }
}

const handleNext = (tabIndex, deviceId) => {
  if (!isStepValid(tabIndex)) {
    return ElMessage.warning('请先完成当前步骤的必填项')
  }
  const current = currentStep.value[tabIndex]
  const totalSteps = tabs.value[tabIndex].orderDetails.length
  if (currentStep.value[tabIndex] < totalSteps - 1) {
    formData[tabIndex][current].indexId = current + 1
    formData[tabIndex][current].deviceId = deviceId
    currentStep.value[tabIndex]++
    submitForm(tabIndex, current, '')
  } else {
    formData[tabIndex][current].indexId = current + 1
    formData[tabIndex][current].deviceId = deviceId
    submitForm(tabIndex, current, 'finish')
  }
}

const isLastStep = (tabIndex) => {
  return currentStep.value[tabIndex] === tabs.value[tabIndex].orderDetails.length - 1
}

// 提交表单
const submitForm = (tabIndex, current, type) => {
  try {
    IotInspectOrderApi.writeIotInspectOrder(formData[tabIndex][current], id)
    if (type === 'finish') {
      message.success(t('common.createSuccess'))
      delView(unref(currentRoute))
      push({ name: 'IotInspectOrder', params: {} })
    }
  } catch (error) {
    ElMessage.error('提交失败，请检查数据')
  }
}
</script>

<style scoped>
.step-container {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 10px;
  height: 100%;
  min-height: 600px;
}

.steps-nav {
  overflow-y: auto;
  padding-right: 15px;
}

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

.navigation-controls {
  margin-top: 40px;
  text-align: center;
}

.custom-label {
  font-weight: 1000;
  font-size: 17px;
  padding: 0 10px;
}
::v-deep .el-step__icon {
  background-color: #409eff;
  color: #fff;
  border: 0px;
}
.step-title-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  position: relative;
  padding-right: 25px;
}

/* 覆盖步骤条默认样式 */
:deep(.custom-steps) {
  /* 调整头部位置 */
  .el-step__head {
    top: 3px;
  }

  /* 标题容器定位 */
  .el-step__title {
    display: inline-block;
    margin-left: 10px;
    padding-right: 0;
  }

  /* 步骤连接线 */
  .el-step__line {
    left: 11px;
    background-color: #ebeef5;
  }

  /* 当前步骤样式 */
  .is-process .title-text {
    font-weight: 600;
    color: #409eff;
  }

  /* 完成状态图标 */
  .is-finish .tip-icon {
    color: #67c23a;
  }
}
</style>
