<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="min(920px, 92vw)"
    class="inspect-item-form-dialog">
    <template #title>
      <div class="dialog-title mb-4">
        <div class="dialog-title__icon"><Icon icon="ep:list" /></div>
        <div class="dialog-title__content">
          <div class="dialog-title__text">{{ dialogTitle }}</div>
          <div class="dialog-title__subtitle">维护巡检设备、巡检项目与执行标准</div>
        </div>
      </div>
    </template>

    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      size="default"
      label-width="100px"
      class="inspect-item-form">
      <section class="form-section">
        <header class="section-heading"><span></span>基础信息</header>
        <div class="form-grid">
          <el-form-item :label="t('monitor.category')" prop="deviceClassify">
            <el-tree-select
              v-model="formData.deviceClassify"
              :data="productClassifyList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              :placeholder="t('deviceForm.categoryHolder')"
              filterable
              clearable />
          </el-form-item>
          <el-form-item :label="t('iotDevice.brand')" prop="brandName">
            <el-select
              v-model="formData.brandName"
              :placeholder="t('iotDevice.brandHolder')"
              clearable
              @clear="brandClear"
              @click="openBrand" />
          </el-form-item>
          <el-form-item :label="t('monitor.deviceName')" prop="deviceId">
            <el-select
              v-model="formData.deviceId"
              :model-value="deviceLabel"
              :placeholder="t('monitor.nameHolder')"
              @click="openForm" />
          </el-form-item>
          <el-form-item :label="t('common.sort')" prop="sort">
            <el-input v-model="formData.sort" type="number" :placeholder="t('common.sortHolder')" />
          </el-form-item>
          <el-form-item :label="t('fileInfo.appendix')" prop="urls" class="form-grid__full">
            <UploadFile
              v-model="formData.urls"
              :limit="1"
              :is-show-tip="false"
              class="min-w-80px" />
          </el-form-item>
        </div>
      </section>

      <section class="form-section">
        <header class="section-heading"><span></span>巡检内容</header>
        <div class="form-content">
          <el-form-item :label="t('inspect.InspectionItems')" prop="item">
            <el-input v-model="formData.item" :placeholder="t('inspect.itemHolder')" />
          </el-form-item>
          <el-form-item :label="t('inspect.InspectionStandards')" prop="standard">
            <el-input
              v-model="formData.standard"
              type="textarea"
              :rows="3"
              :placeholder="t('inspect.stanHolder')" />
          </el-form-item>
          <el-form-item :label="t('form.remark')" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              :placeholder="t('deviceForm.remarkHolder')" />
          </el-form-item>
        </div>
      </section>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('faultForm.cancel') }}</el-button>
      <el-button type="primary" :loading="formLoading" @click="submitForm">
        {{ t('faultForm.ok') }}
      </el-button>
    </template>
  </Dialog>
  <DeviceList ref="deviceFormRef" @choose="deviceChoose" />
  <BrandList ref="brandFormRef" @choose="brandChoose" />
</template>
<script setup lang="ts">
import { IotInspectItemApi, IotInspectItemVO } from '@/api/pms/inspect/item'
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductClassifyApi from '@/api/pms/productclassify'
import DeviceList from '@/views/pms/failure/DeviceList.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import BrandList from '@/views/pms/device/BrandList.vue'
/** 巡检项 表单 */
defineOptions({ name: 'IotInspectItemForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const productClassifyList = ref<Tree[]>([]) // 树形结构
const deviceLabel = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  item: undefined,
  standard: undefined,
  sort: undefined,
  remark: undefined,
  deptId: undefined,
  deviceClassify: undefined,
  deviceClassifyName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  urls: undefined,
  brand: undefined,
  brandName: undefined
})
const formRules = reactive({
  deviceClassify: [{ required: true, message: '设备类别不能为空', trigger: 'blur' }],
  item: [{ required: true, message: '巡检项不能为空', trigger: 'blur' }],
  standard: [{ required: true, message: '巡检标准不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const deviceChoose = (row) => {
  formData.value.deviceId = row.id
  formData.value.deviceName = row.deviceName
  formData.value.deviceCode = row.deviceCode
  formData.value.deptId = row.deptId
  deviceLabel.value = row.deviceName
}

const brandFormRef = ref()
const openBrand = () => {
  brandFormRef.value.open()
}
const brandChoose = (row) => {
  formData.value.brand = row.id
  // brandLabel.value = row.value
  formData.value.brandName = row.label
}
const brandClear = () => {
  formData.value.brand = undefined
  formData.value.brandName = undefined
}
/** 打开弹窗 */
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 IotInspectItemApi.getIotInspectItem(id)
      deviceLabel.value = formData.value.deviceName
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.sort = 0
    deviceLabel.value = ''
  }

  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open(formData.value.deviceClassify)
}

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    item: undefined,
    standard: undefined,
    sort: undefined,
    remark: undefined,
    deptId: 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__content {
  min-width: 0;
}

.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);
}

.inspect-item-form {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding-top: 8px;
}

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

.section-heading {
  display: flex;
  align-items: center;
  height: 42px;
  padding: 0 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;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 24px;
  padding: 18px 18px 2px;
}

.form-grid__full {
  grid-column: 1 / -1;
}

.form-content {
  padding: 18px 18px 2px;
}

.inspect-item-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

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

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

  .form-grid {
    grid-template-columns: minmax(0, 1fr);
    padding: 14px 14px 0;
  }

  .form-grid__full {
    grid-column: auto;
  }

  .form-content {
    padding: 14px 14px 0;
  }
}
</style>
