<script setup lang="ts">
import { useRequest } from 'alova/client';
import { getDeviceManageDetailMethod, updateDeviceManageMethod } from '@/request/api/device.api';
import { branchMethod } from '@/request/api/system.api';
import type { DeviceManageModel } from '@/model/device.model';
import { AioFlowConfig, type FlowRequestData } from '@/pages/aio/flow-config/index';
type FollowModel = Partial<DeviceManageModel>;
const flowData = ref<FlowRequestData>();
const loading = ref<boolean>(false);

const props = defineProps<{ data: FollowModel }>();

const emits = defineEmits<{
  submit: [data?: DeviceManageModel];
}>();

const model = ref<DeviceManageModel>({});

// 获取详情
const getDetail = async () => {
  try {
    const res = await getDeviceManageDetailMethod(props.data);
    if (res && JSON.stringify(res) !== '{}') {
      flowData.value = { ...res } as FlowRequestData;
      loading.value = false;
      model.value = { ...res };
    }
  } catch (error: any) {
    console.error(error, 'error');
    loading.value = false;
  }
};

onMounted(() => {
  if (props.data && props.data.id) {
    getDetail();
  }
});

const branch = ref<any[]>([]);
useRequest(branchMethod(0, 1, 1)).onSuccess(({ data }) => {
  const to = (data?: any[]): any[] => {
    return Array.isArray(data)
      ? data.map((item) => {
          return {
            ...item,
            value: item.id,
            key: item.id.toString(),
            children: to(item.children),
          };
        })
      : [];
  };
  branch.value = to(data);
});

const { loading: submitting, send: submit } = useRequest(updateDeviceManageMethod, { immediate: false }).onSuccess(() => {
  emits('submit');
});

const flowRef = useTemplateRef<InstanceType<typeof AioFlowConfig>>('flow');
const save = async () => {
  // 改为仅透传提交事件，由父级统一关闭弹窗，避免重复 close 导致内部状态异常
  try {
    await flowRef.value!.validate(/* 传入 false 不展示错误信息 */ true);
    flowData.value!.id = model.value?.id as string;
    submit(flowData.value as any);
  } catch (error: any) {
    console.error('保存错误', error.message);
  }
};
const reset = () => {
  flowRef.value?.update(flowData.value as FlowRequestData);
};
</script>

<template>
  <div class="form-container">
    <div class="summary-container">
      <div class="summary-item mb-3">
        <span class="label" v-if="model?.warrant">设备ID：</span><span class="value">{{ model.warrant }}</span>
      </div>
      <div class="flex">
        <div class="summary-item mr-6" v-if="model && model.orgName">
          <span class="label">组织名称：</span><span class="value">{{ model.orgName }}</span>
        </div>
        <div class="summary-item" v-if="model && model.institutionName">
          <span class="label">机构名称：</span><span class="value">{{ model.institutionName }}</span>
        </div>
      </div>
    </div>
    <!-- 流程配置 -->
    <div class="content-container">
      <div class="title">流程配置</div>
      <span class="section-divider"></span>
      <!-- validate 方法通过后会自动更新 -->
      <AioFlowConfig ref="flow" :loading="loading" v-model:request-data="flowData"></AioFlowConfig>
    </div>
    <!-- 保存和重置 -->
    <div class="button-container">
      <vxe-button type="reset" content="重置" @click="reset()"></vxe-button>
      <vxe-button type="submit" status="primary" content="保存" @click="save()" :loading="submitting"></vxe-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.form-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.summary-container {
  flex: none;
  margin-bottom: 20px;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; 
  > div:not(.title) {
    flex: auto;
    overflow: auto; 
  }
  > .title {
    flex: none;
    padding: 12px 12px 12px 0;
    font-size: 16px;
    font-weight: 800;
  }
}

.section-divider {
  height: 1px !important;
  background-color: #d9d9d9;
  margin-bottom: 15px !important;
}

.button-container {
  flex: none;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding-top: 20px;
}
</style>
