<script setup lang="ts">
import { reactive, ref } from "vue";
import { http } from "@/utils/http";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit" | "view">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    name: "",
    remark: "",
    lightMode: "",
    maintenanceMode: "",
    workMode: "",
    screenType: "",
    userMessage1: "",
    userMessage2: "",
    motorFlowOn: false,
    motorFlowOff: false,
    motorOnDelay: 5000,
    motorOffDelay: 1000,
    motorOnInterval: 10000,
    noticeThresholdIdle: 60,
    noticeThresholdOperation: 300,
    operationTimeout: 3600,
    billDelay: 30,
    idleTimeout: 1200,
    lightTimePeriod1: "",
    lightTimePeriod2: "",
    workTimePeriod1: "",
    workTimePeriod2: "",
    tapOnDelay: 30,
    videoPlayDelay: 60,
    videoSource: "0",
    workLightDelay: 30,
    soundVolume: 50,
    priceBlow: 0,
    priceCleaner: 0,
    priceCoat: 0,
    priceFoam: 0,
    priceSpace: 0,
    priceTap: 0,
    priceUserExt: 0,
    priceWater: 0,
    quickOpenMoney: 0
  },
  rules: {
    name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],
    remark: [{ required: true, message: "请输入配置备注", trigger: "blur" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    name: "",
    remark: "",
    lightMode: "",
    maintenanceMode: "",
    workMode: "",
    screenType: "",
    userMessage1: "",
    userMessage2: "",
    motorFlowOn: false,
    motorFlowOff: false,
    motorOnDelay: 5000,
    motorOffDelay: 1000,
    motorOnInterval: 10000,
    noticeThresholdIdle: 60,
    noticeThresholdOperation: 300,
    operationTimeout: 3600,
    billDelay: 30,
    idleTimeout: 1200,
    lightTimePeriod1: "",
    lightTimePeriod2: "",
    workTimePeriod1: "",
    workTimePeriod2: "",
    tapOnDelay: 30,
    videoPlayDelay: 60,
    videoSource: "0",
    workLightDelay: 30,
    soundVolume: 50,
    priceBlow: 0,
    priceCleaner: 0,
    priceCoat: 0,
    priceFoam: 0,
    priceSpace: 0,
    priceTap: 0,
    priceUserExt: 0,
    priceWater: 0,
    quickOpenMoney: 0
  };
  formRef.value?.resetFields();
};

const open = async (type: "add" | "edit" | "view", row?: any) => {
  dialogType.value = type;
  resetForm();
  
  if (type !== "add" && row?.id) {
    loading.value = true;
    try {
      const res = await http.request("post", `/device-config/${row.id}`);
      Object.assign(state.ruleForm, res);
    } catch (e) {
      ElMessage.error("获取详情失败");
    } finally {
      loading.value = false;
    }
  }
  
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;
  
  loading.value = true;
  try {
    const url = state.ruleForm.id ? "/device-config/modify" : "/device-config/add";
    await http.request("post", url, { data: state.ruleForm });
    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

const isView = () => dialogType.value === "view";

const getTitle = () => {
  const map = { add: "新增配置", edit: "编辑配置", view: "配置详情" };
  return map[dialogType.value];
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="820px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="state.ruleForm"
      :rules="state.rules"
      label-position="top"
      :disabled="isView()"
    >
      <div class="form-group-title">基本参数</div>
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="state.ruleForm.name" placeholder="请输入配置名称" />
      </el-form-item>
      <el-form-item label="配置备注" prop="remark">
        <el-input
          v-model="state.ruleForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入配置备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <div class="form-group-title">选项参数</div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="灯光工作模式（0：全天暂停营业 1:全天营业 2:根据时间段开始营业）" prop="lightMode">
            <el-input v-model="state.ruleForm.lightMode" placeholder="灯光工作模式" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维护模式（0：未设置，1：已设置）" prop="maintenanceMode">
            <el-input v-model="state.ruleForm.maintenanceMode" placeholder="维护模式" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作模式（0：全天暂停营业 1:全天营业 2:根据时间段开始营业）" prop="workMode">
            <el-input v-model="state.ruleForm.workMode" placeholder="工作模式" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="屏幕类型（0:不支持视频播放，1:支持视频播放）" prop="screenType">
            <el-input v-model="state.ruleForm.screenType" placeholder="屏幕类型" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="屏幕左下方文本" prop="userMessage1">
            <el-input v-model="state.ruleForm.userMessage1" placeholder="屏幕左下方文本" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="屏幕右下方文本" prop="userMessage2">
            <el-input v-model="state.ruleForm.userMessage2" placeholder="屏幕右下方文本" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="form-group-title">时间参数</div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="自动启动（有流量时是否自动启动水泵）" prop="motorFlowOn">
            <el-switch v-model="state.ruleForm.motorFlowOn" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自动关闭（没有流量时是否自动关闭水泵）" prop="motorFlowOff">
            <el-switch v-model="state.ruleForm.motorFlowOff" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="启动延时（毫秒，推荐5000）" prop="motorOnDelay">
            <el-input-number v-model="state.ruleForm.motorOnDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关闭延时（毫秒，推荐1000）" prop="motorOffDelay">
            <el-input-number v-model="state.ruleForm.motorOffDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="关闭灵敏度（毫秒，推荐10000）" prop="motorOnInterval">
            <el-input-number v-model="state.ruleForm.motorOnInterval" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="空闲超时提示音倒计时（秒）" prop="noticeThresholdIdle">
            <el-input-number v-model="state.ruleForm.noticeThresholdIdle" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="操作超时提示音倒计时（秒）" prop="noticeThresholdOperation">
            <el-input-number v-model="state.ruleForm.noticeThresholdOperation" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作超时关机（秒，3600=60分钟）" prop="operationTimeout">
            <el-input-number v-model="state.ruleForm.operationTimeout" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="洗车结束后费用明细显示时长（秒）" prop="billDelay">
            <el-input-number v-model="state.ruleForm.billDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="空闲超时关机（秒，1200=20分钟）" prop="idleTimeout">
            <el-input-number v-model="state.ruleForm.idleTimeout" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="照明时间段1（如：18:00 - 22:00）" prop="lightTimePeriod1">
            <el-input v-model="state.ruleForm.lightTimePeriod1" placeholder="照明时间段1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="照明时间段2（如：18:00 - 08:00）" prop="lightTimePeriod2">
            <el-input v-model="state.ruleForm.lightTimePeriod2" placeholder="照明时间段2" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业时间段1（如：08:00 - 12:00）" prop="workTimePeriod1">
            <el-input v-model="state.ruleForm.workTimePeriod1" placeholder="营业时间段1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业时间段2（如：14:00 - 21:00）" prop="workTimePeriod2">
            <el-input v-model="state.ruleForm.workTimePeriod2" placeholder="营业时间段2" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="水龙头自动关闭延时（秒）" prop="tapOnDelay">
            <el-input-number v-model="state.ruleForm.tapOnDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="视频播放延时（秒）" prop="videoPlayDelay">
            <el-input-number v-model="state.ruleForm.videoPlayDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="视频源（0:内置，1:TF卡，2:U盘）" prop="videoSource">
            <el-input v-model="state.ruleForm.videoSource" placeholder="视频源" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作指示灯关闭延时（秒）" prop="workLightDelay">
            <el-input-number v-model="state.ruleForm.workLightDelay" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="form-group-title">声音参数</div>
      <el-form-item label="提示音音量（0-100）" prop="soundVolume">
        <el-input-number v-model="state.ruleForm.soundVolume" :min="0" :max="100" class="w100" />
      </el-form-item>

      <div class="form-group-title">价格参数（分/分钟）</div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="吹气单价" prop="priceBlow">
            <el-input-number v-model="state.ruleForm.priceBlow" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="吸尘单价" prop="priceCleaner">
            <el-input-number v-model="state.ruleForm.priceCleaner" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="镀膜单价" prop="priceCoat">
            <el-input-number v-model="state.ruleForm.priceCoat" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="泡沫单价" prop="priceFoam">
            <el-input-number v-model="state.ruleForm.priceFoam" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="场地费单价" prop="priceSpace">
            <el-input-number v-model="state.ruleForm.priceSpace" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="洗手单价" prop="priceTap">
            <el-input-number v-model="state.ruleForm.priceTap" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="扩展项目单价" prop="priceUserExt">
            <el-input-number v-model="state.ruleForm.priceUserExt" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="清水单价" prop="priceWater">
            <el-input-number v-model="state.ruleForm.priceWater" :min="0" class="w100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="快速开机金额" prop="quickOpenMoney">
            <el-input-number v-model="state.ruleForm.quickOpenMoney" :min="0" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button v-if="!isView()" :loading="loading" type="primary" @click="handleSubmit">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.form-group-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin: 15px 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.w100 {
  width: 100%;
}
</style>
