<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="760px"
    :fullscreen="false"
    class="information-form-dialog">
    <template #title>
      <div class="dialog-title mb-4">
        <div class="dialog-title__icon">
          <Icon icon="ep:notebook" />
        </div>
        <div>
          <div class="dialog-title__text">{{ dialogTitle }}</div>
          <div class="dialog-title__subtitle">维护设备故障现象、影响及解决方案</div>
        </div>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="default"
      label-width="92px"
      class="information-form"
      v-loading="formLoading">
      <section class="form-section">
        <div class="section-heading"><span></span>基础信息</div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item :label="t('info.deviceClass')" prop="deviceType">
              <el-tree-select
                v-model="formData.deviceType"
                :data="productClassifyList"
                :props="defaultProps"
                check-strictly
                node-key="id"
                :placeholder="t('deviceForm.category')"
                filterable
                clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item :label="t('faultForm.faultImpact')" prop="failureInfluence">
              <el-input
                v-model="formData.failureInfluence"
                :placeholder="t('faultForm.faultImpactHolder')" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item :label="t('faultForm.faultySystem')" prop="failureSystem">
              <el-input
                v-model="formData.failureSystem"
                :placeholder="t('faultForm.faultySystemHolder')" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item :label="t('iotMaintain.solution')" prop="solutions">
              <el-input v-model="formData.solutions" :placeholder="t('iotMaintain.soHolder')" />
            </el-form-item>
          </el-col>
        </el-row>
      </section>

      <section class="form-section">
        <div class="section-heading"><span></span>补充说明</div>
        <el-form-item :label="t('info.description')" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" resize="none" />
        </el-form-item>
        <el-form-item :label="t('iotMaintain.remark')" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            resize="none"
            :placeholder="t('iotMaintain.remarkHolder')" />
        </el-form-item>
      </section>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="default" @click="dialogVisible = false">
          {{ t('iotMaintain.cancel') }}
        </el-button>
        <el-button size="default" type="primary" :loading="formLoading" @click="submitForm">
          {{ t('iotMaintain.ok') }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { IotInformationDbApi, IotInformationDbVO } from '@/api/pms/information'
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductClassifyApi from '@/api/pms/productclassify'

/** 故障知识库 表单 */
defineOptions({ name: 'IotInformationDbForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const productClassifyList = ref<Tree[]>([]) // 树形结构
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceType: undefined,
  failureInfluence: undefined,
  failureSystem: undefined,
  description: undefined,
  solutions: undefined,
  remark: undefined,
  processInstanceId: undefined,
  auditStatus: undefined
})
const formRules = reactive({
  deviceType: [{ required: true, message: t('info.classHolder1'), trigger: 'change' }],
  failureInfluence: [{ required: true, message: t('info.faultyImpact'), trigger: 'change' }],
  solutions: [{ required: true, message: t('info.solution'), trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotInformationDbApi.getIotInformationDb(id)
    } finally {
      formLoading.value = false
    }
  }
  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as IotInformationDbVO
    if (formType.value === 'create') {
      await IotInformationDbApi.createIotInformationDb(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotInformationDbApi.updateIotInformationDb(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceType: undefined,
    failureInfluence: undefined,
    failureSystem: undefined,
    description: undefined,
    solutions: undefined,
    remark: undefined,
    processInstanceId: undefined,
    auditStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.dialog-title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.dialog-title__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  margin-right: 12px;
  font-size: 18px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.dialog-title__text {
  font-size: 17px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.dialog-title__subtitle {
  margin-top: 1px;
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.information-form {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.form-section {
  padding: 0 16px 2px;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.section-heading {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  margin: 0 -16px 16px;
  font-size: 15px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-heading span {
  width: 4px;
  height: 17px;
  margin-right: 9px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.information-form :deep(.el-select),
.information-form :deep(.el-tree-select) {
  width: 100%;
}

.information-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

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

.dialog-footer :deep(.el-button) {
  margin-left: 0;
}

@media (width <= 768px) {
  .dialog-title__subtitle {
    display: none;
  }

  .form-section {
    padding-right: 12px;
    padding-left: 12px;
  }

  .section-heading {
    padding-right: 12px;
    padding-left: 12px;
    margin-right: -12px;
    margin-left: -12px;
  }
}
</style>
