<script setup lang="ts">
import { tryOnMounted } from '@vueuse/core';
import { useRequest } from 'alova/client';
import { batchUpdateDeviceManageMethod, getDeviceManageDetailMethod, updateDeviceManageMethod } from '@/request/api/device.api';
import { notification } from 'ant-design-vue';
import { AioFlowConfig, type FlowRequestData } from '@/pages/aio/flow-config/index';
import type { DeviceManageModel } from '@/model/device.model';
const flowData = ref<FlowRequestData>();
const loading = ref(false);
// const defaultModel: DeviceManageModel = {};
(notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
const props = defineProps<{ data: DeviceManageModel[] }>();

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

// 批量修改
const { loading: submitting, send: submit } = useRequest(batchUpdateDeviceManageMethod, { immediate: false }).onSuccess(() => {
  emits('submit');
  notification.success({ message: '修改成功' });
});
// 单个修改
const { loading: submittingSingle, send: submitSingle } = useRequest(updateDeviceManageMethod, { immediate: false }).onSuccess(() => {
  emits('submitSingle');
  notification.success({ message: '修改成功' });
});
// 右侧设备列表
const tableData = computed<DeviceManageModel[]>(() => {
  const src = props.data as any;
  if (Array.isArray(src)) return src;
  if (src && Array.isArray(src.data)) return src.data;
  return src ? [src] : [];
});

// 设备ID增删在批量配置不需要
let ids = ref<string[]>([]);
tryOnMounted(async () => {
  if (props.data && Array.isArray(props.data) && props.data.length > 1) {
    props.data?.forEach((item: any) => {
      ids.value.push(item.id);
    });
    flowData.value = mock();
  } else if (props.data && props.data.length === 1) {
    flowData.value = (await getDeviceManageDetailMethod({ id: props.data[0].id })) as FlowRequestData;
  }
});
// 初始化数据
const mock = () => {
  return {
    tabletProcessModules: ['patient_file', 'tongueface_upload', 'tongueface_analysis', 'health_analysis'],
    tabletFileFields: ['phone:required', 'sex', 'age', 'isEasyAllergy'],
    tabletRequiredPageOperationElements: [
      'health_analysis_report_page_appletbutton'
    ],
    technicalSupporter: '',
  };
};
const flowRef = useTemplateRef<InstanceType<typeof AioFlowConfig>>('flow');
// 保存
const save = async () => {
  // 改为仅透传提交事件，由父级统一关闭弹窗，避免重复 close 导致内部状态异常
  await flowRef.value!.validate(/* 传入 false 不展示错误信息 */ true);
  if (Array.isArray(props.data) && props.data.length > 1) {
    await submit({ ...flowData.value, ids: ids.value });
  } else if (Array.isArray(props.data) && props.data.length === 1) {
    await submitSingle({ ...flowData.value, id: props.data[0].id } as DeviceManageModel);
  }
};
const reset = () => {
  flowRef.value?.update();
};
</script>

<template>
  <div class="two-pane h-full">
    <div class="left form-container flex flex-col">
      <!-- 流程配置 -->
      <div class="flex-auto content-container">
        <div class="title">流程配置</div>
        <!-- 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 || submittingSingle"></vxe-button>
      </div>
    </div>
    <!-- 右侧设备列表 -->
    <div class="right table-container flex flex-col">
      <div class="table-title flex-none">待配置设备</div>
      <div class="table-wrapper flex-auto">
        <table class="simple-table">
          <thead>
            <tr>
              <th>设备ID</th>
              <th>组织</th>
              <th>机构名称</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in tableData" :key="item.id">
              <td>{{ item.warrant }}</td>
              <td>{{ item.orgName }}</td>
              <td>{{ item.institutionName }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.content-container {
  width: 100%;
  //height: 600px;
  display: flex;
  flex-direction: column;
  > div:not(.title) {
    flex: auto;
  }
  > .title {
    flex: none;
    padding: 12px;
    font-size: 16px;
    font-weight: 800;
  }
}
.two-pane {
  display: flex;
  gap: 24px;
}
.left {
  flex: 1;
}
.right {
  width: 30%;
  min-width: 420px;
}
.table-title {
  font-weight: 600;
  margin-bottom: 8px;
}
.table-wrapper {
  border: 1px solid #eee;
  //height: 100%;
  overflow: auto;
}
.simple-table {
  width: 100%;
  border-collapse: collapse;
}
.simple-table th,
.simple-table td {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 12px;
  text-align: left;
}
.form-container {
  //padding: 20px;
}
.section-divider {
  height: 1px;
  background-color: #d9d9d9;
  margin-bottom: 15px;
}
.button-container {
  flex: none;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding-top: 20px;
}
</style>
