<!-- 外部客户端新建/编辑弹窗 -->
<template>
  <ele-modal
    width="760px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改外部客户端' : '新建外部客户端'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col v-if="isUpdate" :span="12">
          <el-form-item label="客户端 ID:">
            <el-input v-model="form.clientId" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统名称:" prop="systemName">
            <el-input
              v-model="form.systemName"
              clearable
              :maxlength="100"
              placeholder="请输入外部系统名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统编码:" prop="systemCode">
            <el-input
              v-model="form.systemCode"
              clearable
              :maxlength="100"
              placeholder="请输入外部系统编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂:" prop="factoriesId">
            <factory-select
              v-model="form.factoriesId"
              clearable
              placeholder="请选择工厂"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源 IP 白名单:">
            <el-input
              v-model="form.ipWhitelist"
              clearable
              placeholder="多个 IP 使用英文逗号分隔，留空表示不限制"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效时间:">
            <el-date-picker
              v-model="form.effectiveTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              clearable
              placeholder="请选择生效时间"
              class="ele-block"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效时间:">
            <el-date-picker
              v-model="form.expireTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              clearable
              placeholder="请选择失效时间"
              class="ele-block"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-alert
        title="来源 IP 白名单请使用英文半角逗号分隔。"
        type="info"
        :closable="false"
        show-icon
      />
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import {
    addExternalClient,
    getExternalClient,
    updateExternalClient
  } from '@/api/system/externalClient';
  import factorySelect from '@/components/CommomSelect/factory-select.vue';

  const defaultForm = {
    id: null,
    clientId: '',
    systemCode: '',
    systemName: '',
    factoriesId: '',
    effectiveTime: '',
    expireTime: '',
    ipWhitelist: ''
  };

  export default {
    components: {
      factorySelect
    },
    props: {
      visible: Boolean,
      data: {
        type: Object,
        default: null
      }
    },
    data() {
      return {
        form: { ...defaultForm },
        rules: {
          systemName: [
            { required: true, message: '请输入外部系统名称', trigger: 'blur' }
          ],
          systemCode: [
            { required: true, message: '请输入外部系统编码', trigger: 'blur' }
          ],
          expireTime: [
            {
              validator: (rule, value, callback) => {
                if (!value || !this.form.effectiveTime) {
                  callback();
                  return;
                }
                callback(
                  new Date(value).getTime() >
                    new Date(this.form.effectiveTime).getTime()
                    ? undefined
                    : new Error('失效时间必须晚于生效时间')
                );
              },
              trigger: 'change'
            }
          ]
        },
        isUpdate: false,
        loading: false,
        detailLoading: false
      };
    },
    watch: {
      visible(value) {
        if (value) {
          this.initForm();
        } else {
          this.resetForm();
        }
      }
    },
    methods: {
      async initForm() {
        this.isUpdate = Boolean(this.data && this.data.id);
        this.form = {
          ...defaultForm,
          ...(this.data || {})
        };
        if (!this.isUpdate) {
          return;
        }
        this.detailLoading = true;
        try {
          const detail = await getExternalClient(this.data.id);
          this.form = {
            ...defaultForm,
            ...detail
          };
        } catch (error) {
          this.$message.error(error.message || '获取客户端详情失败');
          this.updateVisible(false);
        } finally {
          this.detailLoading = false;
        }
      },
      resetForm() {
        this.form = { ...defaultForm };
        this.isUpdate = false;
        this.loading = false;
        this.detailLoading = false;
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      },
      save() {
        if (this.loading || this.detailLoading) {
          return;
        }
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return;
          }
          this.loading = true;
          const payload = {
            ...(this.isUpdate ? { id: this.form.id } : {}),
            systemName: this.form.systemName,
            systemCode: this.form.systemCode,
            factoriesId: this.form.factoriesId
              ? Number(this.form.factoriesId)
              : undefined,
            effectiveTime: this.form.effectiveTime || undefined,
            expireTime: this.form.expireTime || undefined,
            ipWhitelist: this.form.ipWhitelist || undefined
          };
          const request = this.isUpdate
            ? updateExternalClient(payload)
            : addExternalClient(payload);
          request
            .then((result) => {
              this.$message.success(this.isUpdate ? '修改成功' : '创建成功');
              this.updateVisible(false);
              this.$emit('done', result);
            })
            .catch((error) => {
              this.$message.error(error.message || '保存失败');
            })
            .finally(() => {
              this.loading = false;
            });
        });
      },
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    }
  };
</script>
