<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="700px"
    :close-on-click-modal="false"
    draggable
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="规则编码" prop="ruleCode">
            <el-input v-model="form.ruleCode" placeholder="请输入规则编码" :disabled="isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则类型" prop="ruleType">
            <el-select v-model="form.ruleType" placeholder="请选择规则类型" style="width: 100%">
              <el-option
                v-for="item in ruleTypes"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="sortOrder">
            <el-input-number v-model="form.sortOrder" :min="1" :max="999" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="金额区间">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-input-number
                v-model="form.amountMin"
                :min="0"
                :precision="2"
                :controls="false"
                placeholder="金额下限"
                style="width: 200px;"
                @change="handleAmountMinChange"
              />
              <span>元</span>
              <span style="margin: 0 8px;">至</span>
              <el-input-number
                v-model="form.amountMax"
                :min="0"
                :precision="2"
                :controls="false"
                placeholder="金额上限"
                style="width: 200px;"
                @change="handleAmountMaxChange"
              />
              <span>元</span>
              <span style="color: #909399; font-size: 12px;">（不填表示不限）</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附加条件字段">
            <el-select v-model="form.conditionField" placeholder="请选择" clearable style="width: 100%">
              <el-option label="是否集采" value="isCentralized" />
              <el-option label="是否特殊情况" value="isSpecial" />
              <el-option label="是否有推荐供应商" value="hasSupplier" />
              <el-option label="项目类别" value="projectType" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附加条件值">
            <el-input v-model="form.conditionValue" placeholder="如：0、1、A等" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="动作类型" prop="actionType">
            <el-select v-model="form.actionType" placeholder="请选择动作类型" style="width: 100%">
              <el-option label="设置字段值" value="SET_FIELD" />
              <el-option label="切换模板" value="SWITCH_TEMPLATE" />
              <el-option label="要求文件" value="REQUIRE_FILE" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="动作目标" prop="actionTarget">
            <el-select v-model="form.actionTarget" placeholder="请选择" allow-create filterable style="width: 100%">
              <el-option v-if="form.actionType === 'SET_FIELD'" label="采购形式" value="purchaseMode" />
              <el-option v-if="form.actionType === 'SET_FIELD'" label="学校采购方式" value="purchaseSchool" />
              <el-option v-if="form.actionType === 'SWITCH_TEMPLATE'" label="比选模板" value="bidTemplate" />
              <el-option v-if="form.actionType === 'REQUIRE_FILE'" label="可行性论证报告" value="feasibilityReport" />
              <el-option v-if="form.actionType === 'REQUIRE_FILE'" label="会议纪要" value="meetingMinutes" />
              <el-option v-if="form.actionType === 'REQUIRE_FILE'" label="政府采购意向表" value="governmentIntention" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="动作值">
            <el-input v-model="form.actionValue" placeholder="设置的值" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用">
            <el-radio-group v-model="form.isEnabled">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规则描述">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="2"
              placeholder="请输入规则描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, getRuleTypes } from "/@/api/purchase/purchasingRuleConfig";

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

const visible = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const formRef = ref();
const ruleTypes = ref<{ code: string; name: string }[]>([]);

const isEdit = ref(false);
const dialogTitle = computed(() => isEdit.value ? '编辑规则' : '新增规则');

const form = reactive({
  id: '',
  ruleCode: '',
  ruleName: '',
  ruleType: '',
  amountMin: null as number | null,
  amountMax: null as number | null,
  conditionField: '',
  conditionValue: '',
  actionType: '',
  actionTarget: '',
  actionValue: '',
  description: '',
  sortOrder: 1,
  isEnabled: '1',
  remark: ''
});

const rules = {
  ruleCode: [{ required: true, message: '请输入规则编码', trigger: 'blur' }],
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  actionType: [{ required: true, message: '请选择动作类型', trigger: 'change' }],
  actionTarget: [{ required: true, message: '请输入动作目标', trigger: 'blur' }]
};

const openDialog = async (id?: string) => {
  visible.value = true;
  isEdit.value = !!id;
  resetForm();

  const res = await getRuleTypes();
  ruleTypes.value = res.data || [];

  if (id) {
    loading.value = true;
    try {
      const response = await getObj(id);
      if (response.data) {
        Object.assign(form, response.data);
      }
    } finally {
      loading.value = false;
    }
  }
};

const resetForm = () => {
  form.id = '';
  form.ruleCode = '';
  form.ruleName = '';
  form.ruleType = '';
  form.amountMin = null;
  form.amountMax = null;
  form.conditionField = '';
  form.conditionValue = '';
  form.actionType = '';
  form.actionTarget = '';
  form.actionValue = '';
  form.description = '';
  form.sortOrder = 1;
  form.isEnabled = '1';
  form.remark = '';
  formRef.value?.resetFields();
};

const handleSubmit = async () => {
  await formRef.value?.validate();
  const submitData = {
    ...form,
    amountMin: form.amountMin ?? null,
    amountMax: form.amountMax ?? null
  };
  submitLoading.value = true;
  try {
    if (isEdit.value) {
      await putObj(submitData);
      useMessage().success('修改成功');
    } else {
      await addObj(submitData);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    submitLoading.value = false;
  }
};

const handleAmountMinChange = (val: number | undefined) => {
  form.amountMin = val ?? null;
};

const handleAmountMaxChange = (val: number | undefined) => {
  form.amountMax = val ?? null;
};

defineExpose({ openDialog });
</script>