<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1080px" class="failure-report-dialog">
    <template #title>
      <div class="dialog-header mb-6">
        <div class="dialog-header__icon">
          <Icon icon="ep:warning" :size="22" />
        </div>
        <div>
          <div class="dialog-title">{{ dialogTitle }}</div>
          <div class="dialog-subtitle">维护故障基础信息、处理状态与现场描述</div>
        </div>
      </div>
    </template>

    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      size="default"
      label-width="110px"
      class="failure-report-form"
      :class="{ 'is-readonly': disabled }">
      <section class="info-card">
        <div class="info-card__header">
          <div class="info-card__title">
            <span class="info-card__marker"></span>
            <span>基础信息</span>
          </div>
        </div>
        <div class="info-card__body">
          <el-row :gutter="16">
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.failureType')" prop="failureType">
                <el-select
                  v-model="formData.failureType"
                  :placeholder="t('faultForm.failureTypeHolder')"
                  :disabled="disabled"
                  clearable
                  class="form-control">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.FAILURE_TYPE)"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.device')" prop="deviceName">
                <el-select
                  v-if="disabled"
                  v-model="formData.deviceName"
                  :disabled="disabled"
                  :placeholder="t('faultForm.choose')"
                  clearable
                  class="form-control"
                  @clear="handleClear" />
                <el-select
                  v-else
                  v-model="formData.deviceName"
                  :placeholder="t('faultForm.choose')"
                  clearable
                  class="form-control"
                  @click="openForm"
                  @clear="handleClear" />
              </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')"
                  :disabled="disabled"
                  class="form-control" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.failureTime')" prop="failureTime">
                <el-date-picker
                  v-model="formData.failureTime"
                  :disabled="disabled"
                  type="datetime"
                  value-format="x"
                  :placeholder="t('faultForm.failureTimeHolder')"
                  class="form-control" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.shutDown')" prop="ifStop">
                <el-select
                  v-model="formData.ifStop"
                  :placeholder="t('faultForm.choose')"
                  clearable
                  :disabled="disabled"
                  class="form-control">
                  <el-option
                    v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.picture')" prop="pic">
                <UploadImg v-model="formData.pic" height="60px" :disabled="disabled" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </section>

      <section class="info-card">
        <div class="info-card__header">
          <div class="info-card__title">
            <span class="info-card__marker"></span>
            <span>处理信息</span>
          </div>
        </div>
        <div class="info-card__body">
          <el-row :gutter="16">
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.solve')" prop="ifDeal">
                <el-select
                  v-model="formData.ifDeal"
                  :placeholder="t('faultForm.choose')"
                  clearable
                  :disabled="disabled"
                  class="form-control"
                  @change="dealChange">
                  <el-option
                    v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.assist')" prop="needHelp">
                <el-select
                  v-model="formData.needHelp"
                  :placeholder="t('faultForm.choose')"
                  clearable
                  :disabled="disabled"
                  class="form-control"
                  @change="helpChange">
                  <el-option
                    v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.ifDeal" :xs="24" :sm="12">
              <el-form-item :label="t('faultForm.dealTime')" prop="dealTime">
                <el-date-picker
                  v-model="formData.dealTime"
                  :disabled="disabled"
                  type="datetime"
                  value-format="x"
                  placeholder="选择故障解决时间"
                  class="form-control"
                  @change="endTimeBlur" />
              </el-form-item>
            </el-col>
            <el-col v-if="!formData.ifDeal && approvalShow" :xs="24" :sm="12">
              <el-form-item
                :label="t('faultForm.approvalId')"
                prop="approvalId"
                :rules="!formData.ifDeal ? approvalRule : []">
                <el-select
                  v-model="formData.approvalId"
                  multiple
                  :placeholder="t('faultForm.approvalHolder')"
                  filterable
                  clearable
                  :disabled="disabled"
                  class="form-control">
                  <el-option
                    v-for="ap in approver"
                    :key="ap.id"
                    :label="ap.nickname"
                    :value="ap.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </section>

      <section class="info-card">
        <div class="info-card__header">
          <div class="info-card__title">
            <span class="info-card__marker"></span>
            <span>故障描述</span>
          </div>
        </div>
        <div class="info-card__body">
          <el-row :gutter="16">
            <el-col :span="24">
              <el-form-item :label="t('faultForm.faultImpact')" prop="failureInfluence">
                <el-input
                  v-model="formData.failureInfluence"
                  type="textarea"
                  :rows="2"
                  :placeholder="t('faultForm.faultImpactHolder')"
                  :disabled="disabled" />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.ifDeal" :span="24">
              <el-form-item
                label="解决办法"
                prop="solution"
                :rules="formData.ifDeal ? solutionRule : []">
                <el-input
                  v-model="formData.solution"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入解决办法"
                  :disabled="disabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="t('faultForm.faultDescription')" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  :disabled="disabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="t('faultForm.remark')" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="2"
                  :placeholder="t('faultForm.rHolder')"
                  :disabled="disabled" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </section>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ t('faultForm.cancel') }}</el-button>
        <el-button v-if="!disabled" type="primary" :disabled="formLoading" @click="submitForm">
          {{ t('faultForm.ok') }}
        </el-button>
      </div>
    </template>
    <DeviceList ref="deviceFormRef" @choose="deviceChoose" />
  </Dialog>
</template>
<script setup lang="ts">
import { IotFailureReportApi, IotFailureReportVO } from '@/api/pms/failure'
import { DICT_TYPE, getBoolDictOptions, getStrDictOptions } from '@/utils/dict'
import DeviceList from '@/views/pms/failure/DeviceList.vue'
import dayjs from 'dayjs'
import { IotDeviceApi } from '@/api/pms/device'

/** 故障上报 表单 */
defineOptions({ name: 'IotFailureReportForm' })

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 approvalShow = ref(true)
const approver = ref([])
let company = ''
const formData = ref({
  failureType: undefined,
  approvalId: undefined,
  id: undefined,
  failureCode: undefined,
  failureName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  status: undefined,
  ifStop: undefined,
  failureTime: undefined,
  dealTime: undefined,
  failureInfluence: undefined,
  failureSystem: undefined,
  description: undefined,
  pic: undefined,
  ifDeal: undefined,
  needHelp: undefined,
  solution: undefined,
  remark: undefined,
  deptId: undefined
})
const dealChange = () => {
  formData.value.needHelp = !formData.value.ifDeal
  if (!formData.value.ifDeal) {
    IotFailureReportApi.getApproval().then((res) => {
      approver.value = res
    })
  }
}
const helpChange = () => {
  formData.value.ifDeal = !formData.value.needHelp
}
const deviceChoose = async (row) => {
  formData.value.deviceId = row.id
  formData.value.deviceName = row.deviceName
  formData.value.deviceCode = row.deviceCode
  formData.value.deptId = row.deptId

  company = await IotDeviceApi.getCompanyByDevice(row.id)
  if ('rh' === company) {
    approvalShow.value = false
  } else {
    approvalShow.value = true
  }
  // deviceLabel.value = row.deviceName
}
const endTimeBlur = () => {
  if (formData.value.dealTime <= formData.value.failureTime) {
    message.error('故障解决时间不得早于故障时间')
    formData.value.dealTime = undefined
  }
  const now = dayjs()
  const target = dayjs(formData.value.dealTime)
  if (target.isAfter(now)) {
    message.error('故障解决时间不得晚于当前时间')
    formData.value.dealTime = undefined
  }
}
const handleClear = () => {
  formData.value.deviceId = undefined
  formData.value.deviceName = undefined
  formData.value.deptId = undefined
}
/** 添加/修改操作 */
const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open()
}
const formRules = ref({
  failureType: [{ required: true, message: '故障类型不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  ifDeal: [{ required: true, message: '是否解决不能为空', trigger: 'blur' }],
  needHelp: [{ required: true, message: '是否协助不能为空', trigger: 'blur' }],
  failureTime: [{ required: true, message: '故障时间不能为空', trigger: 'blur' }],
  failureSystem: [{ required: true, message: '故障系统不能为空', trigger: 'blur' }],
  dealTime: [{ required: true, message: '故障解决时间不能为空', trigger: 'blur' }]
  // solution:[{required: ()=> formData.value.ifDeal==='true', message: '解决办法不能为空', trigger: 'blur'}],
})
const solutionRule = [{ required: true, message: '解决办法不能为空', trigger: 'blur' }]
const approvalRule = [{ required: true, message: '审批人不能为空', trigger: 'blur' }]
const formRef = ref() // 表单 Ref
const disabled = ref(false)
/** 打开弹窗 */
const open = async (type: string, id?: number, disable?: boolean) => {
  disabled.value = disable
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.deviceId = null
  formData.value.deviceName = null
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotFailureReportApi.getIotFailureReport(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // formData.value.pic = formData.value.pic.path;
    const data = formData.value as unknown as IotFailureReportVO
    if (!formData.value.ifDeal) {
      if (company !== 'rh') formData.value.approvalId = formData.value.approvalId.join(',')
    }
    if (formType.value === 'create') {
      await IotFailureReportApi.createIotFailureReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotFailureReportApi.updateIotFailureReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    failureCode: undefined,
    failureName: undefined,
    deviceId: undefined,
    status: undefined,
    ifStop: undefined,
    failureTime: undefined,
    failureInfluence: undefined,
    failureSystem: undefined,
    description: undefined,
    pic: undefined,
    ifDeal: undefined,
    needHelp: undefined,
    solution: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss">
.failure-report-dialog {
  .el-dialog {
    overflow: hidden;
    border-radius: 8px;
  }

  .el-dialog__header {
    min-height: 56px;
    padding: 8px 18px;
    margin-right: 0 !important;
    background: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-dialog__body {
    padding: 14px 16px 0 !important;
    background: var(--el-bg-color);
  }

  .el-dialog__footer {
    padding: 10px 18px;
    background: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>

<style scoped lang="scss">
.dialog-header {
  display: flex;
  gap: 10px;
  align-items: center;
}

.dialog-header__icon {
  display: flex;
  width: 36px;
  height: 36px;
  color: var(--el-color-primary);
  background: rgb(64 158 255 / 12%);
  border: 1px solid rgb(64 158 255 / 18%);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
}

.dialog-title {
  font-size: 16px;
  font-weight: 600;
  line-height: 22px;
  color: var(--el-text-color-primary);
}

.dialog-subtitle {
  margin-top: 2px;
  font-size: 12px;
  line-height: 16px;
  color: var(--el-text-color-secondary);
}

.failure-report-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 16px;
}

.info-card {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 6px 18px rgb(31 45 61 / 4%);
}

.info-card__header {
  display: flex;
  min-height: 40px;
  padding: 0 16px;
  background: linear-gradient(90deg, rgb(64 158 255 / 8%) 0%, rgb(255 255 255 / 0%) 72%);
  border-bottom: 1px solid var(--el-border-color-lighter);
  align-items: center;
}

.info-card__title {
  display: flex;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  line-height: 22px;
  color: var(--el-text-color-primary);
  align-items: center;
}

.info-card__marker {
  width: 4px;
  height: 16px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.info-card__body {
  padding: 12px 16px 0;
}

.form-control {
  width: 100%;
}

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

.failure-report-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: var(--el-text-color-regular);
}

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

@media (width <= 768px) {
  .info-card__header {
    min-height: auto;
    padding: 10px 14px;
  }

  .info-card__body {
    padding: 12px 14px 0;
  }
}
</style>
