<template>
  <el-dialog
    :title="dataForm.id ? '编辑' : '新增'"
    v-model="visible"
    width="600px"
    :close-on-click-modal="false"
    draggable>
    <el-form
      ref="formRef"
      :model="dataForm"
      :rules="dataRules"
      label-width="100px"
      v-loading="loading">
      <el-form-item label="代理名称" prop="agentName">
        <el-input
          v-model="dataForm.agentName"
          placeholder="请输入代理名称"
          clearable />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input
          v-model="dataForm.contactPerson"
          placeholder="请输入联系人"
          clearable />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="dataForm.contactPhone"
          placeholder="请输入联系电话"
          clearable />
      </el-form-item>
      <el-form-item label="登录用户名" prop="username">
        <el-input
          v-model="dataForm.username"
          placeholder="请输入登录用户名（不填则自动生成）"
          clearable
          :disabled="!!dataForm.id" />
        <div class="form-tip" v-if="!dataForm.id">新增时自动创建系统用户，默认密码：Aa123456，角色：招标代理</div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="dataForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PurchaseAgentForm">
import { reactive, ref, nextTick } from 'vue'
import { getObj, addObj, editObj } from '/@/api/purchase/purchaseagent';
import { useMessage } from '/@/hooks/message';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const formRef = ref();
const dataForm = reactive({
  id: '',
  agentName: '',
  contactPerson: '',
  contactPhone: '',
  username: '',
  remark: '',
});
const visible = ref(false);
const loading = ref(false);

const dataRules = ref({
  agentName: [
    { required: true, message: '请输入代理名称', trigger: 'blur' }
  ],
});

// 打开弹窗
const openDialog = async (type: string, rowData?: any) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.agentName = '';
  dataForm.contactPerson = '';
  dataForm.contactPhone = '';
  dataForm.username = '';
  dataForm.remark = '';

  nextTick(() => {
    formRef.value?.resetFields();
    if (type === 'edit' && rowData?.id) {
      // 编辑时，先获取详情数据
      loading.value = true;
      getObj(rowData.id).then((res: any) => {
        if (res.data) {
          Object.assign(dataForm, {
            id: res.data.id || '',
            agentName: res.data.agentName || '',
            contactPerson: res.data.contactPerson || '',
            contactPhone: res.data.contactPhone || '',
            username: res.data.username || '',
            remark: res.data.remark || '',
          });
        }
        loading.value = false;
      }).catch((err: any) => {
        useMessage().error(err.msg || '获取详情失败');
        loading.value = false;
      });
    }
  });
};

// 提交
const onSubmit = async () => {
  // 立即设置 loading，防止重复点击
  if (loading.value) return;
  loading.value = true;

  try {
    const valid = await formRef.value.validate().catch(() => {});
    if (!valid) {
      loading.value = false;
      return false;
    }

    if (dataForm.id) {
      await editObj(dataForm);
      useMessage().success('编辑成功');
    } else {
      await addObj(dataForm);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || (dataForm.id ? '编辑失败' : '新增失败'));
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>

