<!-- 服务编辑弹窗 -->
<template >
  <ele-modal
    :width="400"
    :visible="visible"
    :confirm-loading="loading"
    :title="'更换电池'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
    <a-form-item label="新电池编号">
      <a-input
        allow-clear
        :maxlength="32"
        placeholder="请输入新电池编号"
        v-model:value="equipmentCode"
      />
      </a-form-item>

    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import type { Order } from '@/api/order/model';
  import { Equipment } from "@/api/apps/equipment/model";
  import { batteryChange } from '@/api/order';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Order | null;

  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Equipment>({
    orderId: props.data?.orderId,
    equipmentCode: ''
  });

  const equipmentCode = ref('')

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    equipmentCode: [
      {
        required: true,
        message: '请输入新电池编号',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    const app = this
    if (!formRef.value) {
      return;
    }
    formRef.value.validate()
      .then(() => {
        loading.value = true
        batteryChange({
          orderId:form.orderId,
          equipmentCode: equipmentCode.value
        })
          .then((msg) => {
            loading.value = false
            message.success("更换电池成功！");
            updateVisible(false);
            emit('done');
            loading.value = false;
          })
          .catch((e) => {
            loading.value = false;
            message.error("更换电池失败！" + e);
          });
      })
      .catch(() => {});
  };

  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
