<template>
  <a-modal
    ref="formDataRef"
    v-model:visible="visible"
    :ok-loading="loading"
    @before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ isNull(props.rule) || props.rule.id === 0 ? '新增' : '编辑' }}规则
    </template>
    <a-form ref="formDataRef" :model="formData">
      <a-form-item field="name" label="规则" required>
        <a-input v-model="formData.name" />
      </a-form-item>
      <a-form-item field="targetUserId" label="目标账户" required>
        <a-select v-model="formData.targetUserId" placeholder="请选择目标账户">
          <a-option
            v-for="item in state.targetUserList"
            :key="item.id"
            :value="item.id"
            :label="item.userName"
            :disabled="item.disable"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="storageUserId" label="存储用户" required>
        <a-select v-model="formData.storageUserId" placeholder="请选择存储用户">
          <a-option
            v-for="item in state.storageUserList"
            :key="item.id"
            :value="item.id"
            :label="item.userName"
            :disabled="item.disable"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="amount" label="金额(元)" required>
        <a-input-number v-model="formData.amount" />
      </a-form-item>
      <a-form-item field="targetAmount" label="面额(元)" required>
        <a-input-number v-model="formData.targetAmount" />
      </a-form-item>
      <a-form-item field="intervalTime" label="延迟时间(秒)" required>
        <a-input-number v-model="formData.intervalTime" />
      </a-form-item>
      <a-form-item field="status" label="是否启用" required>
        <a-switch
          v-model="formData.status"
          size="small"
          :checked-value="1"
          :unchecked-value="0"
        >
          <template #checked-icon>
            <icon-check />
          </template>
          <template #unchecked-icon>
            <icon-close />
          </template>
        </a-switch>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  AppleCardStealList,
  addAppleCardStealRule,
  AppleCardStealAdd,
  editAppleCardStealRule
} from '@/api/apple-card-steal-settings';
import { getAllSimpleUserList, UserSimpleInfo } from '@/api/user';
import useLoading from '@/hooks/loading';
import { isNull, isUndefined } from '@/utils/is';
import { FormInstance, Message } from '@arco-design/web-vue';
import { onMounted, PropType, reactive, ref, watch, watchEffect } from 'vue';

const props = defineProps({
  rule: {
    type: Object as PropType<AppleCardStealList>,
    default: () => ({})
  }
});

const generateFormData = () => {
  return {
    name: '',
    targetUserId: '',
    storageUserId: '',
    amount: 0,
    targetAmount: 0,
    intervalTime: 0,
    status: 1
  };
};

const visible = defineModel<boolean>('visible', {
  type: Boolean,
  default: false
});

interface UserSimpleOption extends UserSimpleInfo {
  disable: boolean;
}
const state = reactive<{
  targetUserList: UserSimpleOption[];
  storageUserList: UserSimpleOption[];
}>({
  targetUserList: [],
  storageUserList: []
});
const formData = ref<AppleCardStealAdd>(generateFormData());
const formDataRef = ref<FormInstance>();

const { loading, setLoading } = useLoading(false);

const handleOk = (done: (closed: boolean) => void) => {
  formDataRef.value.validate().then(async res => {
    if (res) return done(false);
    // 面额不能大于金额
    if (formData.value.targetAmount > formData.value.amount) {
      Message.error({
        content: '面额不能大于金额'
      });
      return done(false);
    }
    try {
      setLoading(true);
      if (isNull(props.rule) || isUndefined(props.rule)) {
        await addAppleCardStealRule(formData.value);
      } else {
        await editAppleCardStealRule({ id: props.rule.id, ...formData.value });
      }
      done(true);
      visible.value = false;
      formData.value = generateFormData();
    } catch (error) {
      done(false);
    } finally {
      setLoading(false);
    }
  });
};
const handleCancel = () => {
  visible.value = false;
  formData.value = generateFormData();
};
watchEffect(() => {
  // 目标账户和存储用户不能相同
  state.storageUserList.forEach(item => {
    item.disable = item.id === formData.value.targetUserId;
  });
  state.targetUserList.forEach(item => {
    item.disable = item.id === formData.value.storageUserId;
  });
});
watch(
  () => props.rule,
  val => {
    if (!isNull(props.rule) && !isUndefined(props.rule)) {
      formData.value = { ...props.rule };
    } else {
      formData.value = generateFormData();
    }
    getAllSimpleUsers();
  }
);

const getAllSimpleUsers = () => {
  getAllSimpleUserList().then(data => {
    state.storageUserList = [];
    state.targetUserList = [];
    data.data.list.forEach(item => {
      state.targetUserList.push({
        ...item,
        disable: false
      });
      state.storageUserList.push({
        ...item,
        disable: false
      });
    });
  });
};

onMounted(() => {
  getAllSimpleUsers();
});
</script>
