<style scoped lang="scss">

</style>
<template>
  <div class="system-dialog-container">
    <el-dialog
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        width="600px"
        draggable
        destroy-on-close
        :close-on-click-modal="false"
        align-center
        @open="onDialogOpen">
      <el-form
          inline
          :model="state.ruleForm"
          :rules="state.rules"
          label-position="top"
          ref="formRef"
          size="default"
          label-width="130px"
          class="mt5">
        <el-form-item label="设备名称" prop="deviceName" class="wd350">
          <el-input
              v-model="state.ruleForm.deviceName"
              placeholder="设备名称"
              clearable
              class="wd200">
          </el-input>
        </el-form-item>
        <el-form-item label="工位序号" prop="sequence" class="wd350">
          <el-input-number
              v-model="state.ruleForm.sequence"
              placeholder="工位序号"
              :min="1"
              class="wd200">
          </el-input-number>
        </el-form-item>
        <el-form-item label="所在网点" prop="stationId" class="wd350">
          <ext-select
              class="wd200"
              v-model="state.ruleForm.stationId"
              placeholder="所在网点"
              url="washStation/list"
              label-key="stationName"
              value-key="stationId">
          </ext-select>
        </el-form-item>
        <el-form-item label="网点ID" prop="stationId" class="wd350">
          <el-input
              v-model="state.ruleForm.stationId"
              placeholder="网点ID"
              clearable
              readonly
              class="w100">
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state" class="wd350">
          <el-select v-model="state.ruleForm.state" clearable placeholder="请选择" class="wd200">
            <el-option v-for="item in getStatusOptions()" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否有泡沫" prop="hasFoam" class="wd250">
          <el-switch v-model="state.ruleForm.hasFoam" active-text="有" inactive-text="无" />
        </el-form-item>
        <el-form-item label="是否有水" prop="hasWater" class="wd250">
          <el-switch v-model="state.ruleForm.hasWater" active-text="有" inactive-text="无" />
        </el-form-item>

        <el-form-item label="是否支持PA" prop="hasPa" class="wd250">
          <el-switch v-model="state.ruleForm.hasPa" active-text="是" inactive-text="否" />
        </el-form-item>

        <el-form-item label="板载温度" prop="temperatureChip" class="wd350">
          <el-input
              v-model="state.ruleForm.temperatureChip"
              placeholder="板载温度传感器的温度值"
              clearable
              class="w100">
          </el-input>
        </el-form-item>

        <el-form-item label="故障原因" prop="faultReason" class="w100">
          <el-input
              v-model="state.ruleForm.faultReason"
              placeholder="故障原因"
              clearable
              type="textarea"
              class="w100">
          </el-input>
        </el-form-item>
        <!--        <el-form-item label="设备主状态机的当前状态(状态可能增加或减少，仅供调试参考。)" prop="fsmState" class="wd350">
                  <el-input
                      v-model="state.ruleForm.fsmState"
                      placeholder="设备主状态机的当前状态(状态可能增加或减少，仅供调试参考。)"
                      clearable
                      class="w100">
                  </el-input>
                </el-form-item>-->
        <el-form-item label="功能" prop="functions" class="w100">
          <el-input
              v-model="state.ruleForm.functions"
              placeholder="功能"
              clearable
              class="w100">
          </el-input>
        </el-form-item>


      </el-form>

      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button :loading="state.btnLoading" type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="WashDeviceDialog">
import {defineAsyncComponent, reactive, ref} from 'vue';
import {Msg} from "/@/utils/message";
import {$body, $get} from "/@/utils/request";
import u from '/@/utils/u'
import {Session} from "/@/utils/storage";
import ExtSelect from "/@/components/form/ExtSelect.vue";


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const formRef = ref();
//定义初始变量，重置使用
const initState = () => ({
  ruleForm: {
    id: null
  },
  btnLoading: false,
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  rules: {
    deviceName: [u.validator.required],
  },
})

// 定义变量内容
const state = reactive(initState());

// 状态字典选项，直接从 Session 读取，避免 ext-d-select 组件挂载时序问题
const getStatusOptions = (): any[] => {
  const dicts = Session.get('dicts')
  return dicts?.['WashDevice.status'] || []
}

// 暂存打开参数，等弹窗动画完成后再加载
let pendingAction = ''
let pendingRow: any = null

// 弹窗打开后（动画完成、DOM 就绪）加载数据
const onDialogOpen = () => {
  if (pendingAction !== 'add' && pendingRow?.id) {
    loadData(pendingRow.id)
  } else if (pendingAction === 'add') {
    state.ruleForm = { id: null, ...pendingRow }
  }
}

// 打开弹窗
const open = (action: string = 'add', row: any) => {
  pendingAction = action
  pendingRow = row
  state.dialog.title = u.dialog.actions[action].title + "『洗车设备』"
  state.dialog.submitTxt = u.dialog.actions[action].btn + "『洗车设备』"
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state, initState())
};
// 取消
const onCancel = () => {
  onClose();
};
// 提交
const onSubmit = () => {
  formRef.value.validate((v: boolean) => {
    if (v) {
      state.btnLoading = true;
      const url = !!state.ruleForm.id  ? "washDevice/modify" : "washDevice/add"
      $body(url, state.ruleForm).then(() => {
        state.btnLoading = false;
        Msg.message('操作成功');
        //console.log('submit!')
        onClose();
        emit('refresh');
      })
    } else {
      state.btnLoading = false;
      Msg.message('请先完整填写表单', 'error');
    }
  })
};

const handleFormChange = (formData: any) => {
  //console.log(formData)
}

// 将后端 boolean 字段（int 0/1 或 string "0"/"1"）转为前端 boolean
const BOOL_FIELDS = ['hasFoam', 'hasWater', 'hasPa'] as const

const normalizeBooleans = (data: Record<string, any>) => {
  BOOL_FIELDS.forEach((key) => {
    const v = data[key]
    if (v === undefined || v === null) return
    if (typeof v === 'boolean') return
    data[key] = typeof v === 'number' ? v !== 0 : v === '1' || v === 'true'
  })
}

// 初始化数据
const loadData = (id: number) => {
  $get(`washDevice/detail/${id}`).then((res: any) => {
    normalizeBooleans(res)
    state.ruleForm = res
  })
}

// 暴露变量
defineExpose({
  open
});


</script>