<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <template #detail>
        <a-form ref="formRef">
          <a-row>
            <a-col :span="24">
              <a-form-item label="ip" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[formRules.ip]">
                <a-input v-model:value="modelRef.ip" placeholder="请输入ip" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="黑白名单" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[formRules.blackOrWhite]">
                <a-select placeholder="请选择黑白名单" v-model:value="modelRef.blackOrWhite">
                  <a-select-option :value="0">黑名单</a-select-option>
                  <a-select-option :value="1">白名单</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
              <a-button @click="submitForm">提 交</a-button>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </j-form-container>
  </a-spin>
</template>

<script lang="ts" setup name="AdwebBlackIpForm">
  import { httpAction, getAction } from '/@/api/manage/manage';
  import pick from 'lodash.pick';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Form } from 'ant-design-vue';
  import { computed, onBeforeMount, reactive, ref, toRaw } from 'vue';

  const emit = defineEmits(['ok', 'close']);

  const { createMessage } = useMessage();

  const useForm = Form.useForm;

  const props = defineProps({
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  });

  let modelRef = reactive({ id: '', ip: '', blackOrWhite: null });

  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 5 },
  });

  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });

  const confirmLoading = ref(false);

  const url = reactive({
    add: '/blackip/adwebBlackIp/add',
    edit: '/blackip/adwebBlackIp/edit',
    queryById: '/blackip/adwebBlackIp/queryById',
  });

  const formRules = reactive({
    ip: [
      { required: true, message: '请输入ip' },
      { max: 31, message: '关键词长度不能超过31' },
    ],
    blackOrWhite: [{ required: true, message: '请输入黑白名单', trigger: 'blur' }],
  });

  const { validate } = useForm(modelRef, formRules);

  // 定义一个计算属性
  const formDisabled = computed(() => {
    if (props.formBpm === true) {
      return props.formData.disabled !== false;
    }
    return props.disabled;
  });

  const showFlowSubmitButton = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return true;
      }
    }
    return false;
  });

  onBeforeMount(() => {
    showFlowData();
  });

  function add() {
    edit({});
  }

  async function edit(record) {
    if (Object.keys(record).length === 0) {
      modelRef.id = '';
      modelRef.ip = '';
      modelRef.blackOrWhite = null;
    } else {
      Object.assign(modelRef, pick(record, 'id', 'ip', 'blackOrWhite'));
    }
  }

  function showFlowData() {
    if (props.formBpm === true) {
      let params = { id: props.formData.dataId };
      getAction(url.queryById, params).then((res) => {
        if (res.code === 200) {
          edit(res.result);
        }
      });
    }
  }

  const onSubmit = () => {
    validate()
      .then(() => {
        confirmLoading.value = true;

        let httpUrl = '';
        let method = '';

        if (!modelRef.id) {
          httpUrl = url.add;
          method = 'post';
        } else {
          httpUrl = url.edit;
          method = 'put';
        }

        let formData = toRaw(modelRef);
        console.log('表单提交数据', formData);

        httpAction(httpUrl, formData, method)
          .then((res) => {
            if (res.success) {
              createMessage.success(res.message);
              emit('ok');
            } else {
              createMessage.warning(res.message);
            }
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      })
      .catch((err) => {
        console.log('error', err);
      });
  };

  function submitForm() {
    onSubmit();
  }

  defineExpose({
    submitForm,
    add,
    edit,
  });
</script>
