<script setup lang="ts">
import { VxeUI, type VxeFormProps, type VxeFormListeners } from 'vxe-pc-ui';
import { useRequest } from 'alova/client';
import { addDeviceRegisterMethod, getDeviceRegisterDetailMethod } from '@/request/api/device.api';
import { branchMethod } from '@/request/api/system.api';
import { notification } from 'ant-design-vue';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import type { EquirementModel } from '@/model/device.model';

type FollowModel = Partial<EquirementModel>;

const defaultModel = {
  deviceIds: [''],
};

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

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

const model = ref<EquirementModel>({ ...defaultModel });

watchEffect(() => {
  if (props.data) {
    model.value = { ...defaultModel, ...props.data };
  }
});
// 获取详情
const getDetail = async () => {
  const res = await getDeviceRegisterDetailMethod(props.data);
  if (res) {
    model.value = { ...defaultModel, ...res };
    model.value.deviceIds = [model.value.deviceCode ?? ''];
  }
};

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

const branch = ref<any[]>([]);
const { loading: branchLoading } = 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(addDeviceRegisterMethod, { immediate: false }).onSuccess(() => {
  emits('submit');
});
// 获取设备类型
const deviceTypes = ref<{ id: string; name: string }[]>([]);
const deviceTypesLoading = ref(false);
// 获取设备类型
async function getDeviceType() {
  deviceTypesLoading.value = true;
  const res = await getDictionaryMethod('fdhb_device_type');
  if (res && res.length > 0) {
    console.log(res, 'res==>');
    deviceTypes.value = res.map((item: any) => ({
      id: item.value,
      name: item.label,
    }));
  }
  console.log(deviceTypes.value, 'deviceTypes==>');
  // 设备类型加载后，若当前值是名称则映射成对应的id
  normalizeDeviceTypeToId();
  deviceTypesLoading.value = false;
}
const showDept = ref(false);
const insArr = ref<any[]>([]);
const insLoading = ref(false);
async function getInstitution(orgId: string | number) {
  insLoading.value = true;
  const res = await branchMethod(1, 0, Number(orgId));
  if (res && res.length > 0) {
    insArr.value = res;
  }
  insLoading.value = false;
}
watch(
  () => model.value.orgId,
  async (newVal, oldVal) => {
    showDept.value = !!newVal;
    if (showDept.value) {
      // 加载机构列表，确保编辑时机构名称可显示
      await getInstitution(newVal ?? '');
    } else {
      insArr.value = [];
    }
    // 仅当组织实际发生切换时清空机构
    if (oldVal !== undefined && newVal !== oldVal) {
      model.value.institutionId = '';
    }
  },
  { immediate: true }
);
// 始终以数组形式暴露设备ID，避免模板类型告警
const deviceIdsSafe = computed<string[]>({
  get() {
    if (!Array.isArray(model.value.deviceIds)) {
      model.value.deviceIds = [''];
    }
    return model.value.deviceIds as string[];
  },
  set(newVal: string[]) {
    model.value.deviceIds = newVal;
  },
});
const formItems = computed(() => {
  const baseItems: any[] = [
    {
      field: 'deviceType',
      title: '设备名称',
      span: 13,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择',
          loading: deviceTypesLoading.value,
          options: computed(() => deviceTypes.value),
          optionProps: { value: 'id', label: 'name' },
          // optionGroupProps: { options: 'groups' },
          clearable: true,
          filterable: true,
        },
      },
    },
    {
      field: 'id',
      title: '设备ID',
      span: 24,
      slots: {
        title: 'deviceIdTitleSlot',
        default: 'deviceIdSlot',
      },
    },
    {
      field: 'orgId',
      title: '组织名称',
      span: 13,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择',
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: {
            value: 'value',
            label: 'label',
          },
          clearable: true,
        },
      },
    },
    {
      field: 'remark',
      title: '备注',
      span: 24,
      slots: {
        default: 'remarksSlot',
      },
    },
    { align: 'center', span: 24, slots: { default: 'active' } },
  ];

  // 如果 showDept 为 true，在 institutionId 后面插入 institutionId
  if (showDept.value) {
    baseItems.splice(3, 0, {
      field: 'institutionId',
      title: '机构名称',
      span: 13,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          placeholder: '请选择',
          loading: computed(() => insLoading.value),
          options: computed(() => insArr.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    });
  }

  return baseItems;
});

const formProps = reactive<VxeFormProps>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: computed(() => model.value),
  items: [] as any, // 临时设置为空数组，我们将在模板中使用动态items
  rules: {
    deviceType: [{ required: true, message: '请选择设备名称' }],
    deviceIds: [{ required: true, message: '请输入设备ID' }],
    orgId: [{ required: true, message: '请选择组织名称' }],
    institutionId: [{ required: true, message: '请选择机构名称' }],
  },
});

const formEmits: VxeFormListeners = {
  submit({ data }) {
    // 提交前确保 deviceType 存为 id
    normalizeDeviceTypeToId();
    // 验证必填字段
    if (!data.deviceType) {
      notification.error({
        message: '请选择设备名称',
      });
      return false; // 阻止表单提交
    }

    if (!data.deviceIds || data.deviceIds.length === 0 || data.deviceIds.every((id: string) => !id.trim())) {
      notification.error({
        message: '请输入设备ID',
      });
      return false; // 阻止表单提交
    }

    if (!data.orgId) {
      notification.error({
        message: '请选择组织名称',
      });
      return false; // 阻止表单提交
    }
    if (!data.institutionId) {
      notification.error({
        message: '请选择机构名称',
      });
      return false; // 阻止表单提交
    }

    if (data.id) {
      data.deviceCode = data.deviceIds[0];
    }
    data.remark ??= '';
    console.log(data, 'data==>');
    submit(data).then(() => {
      notification.success({
        message: '操作成功',
      });
      VxeUI.modal.close('equipment-modal');
    });
  },
};

function cancel() {
  VxeUI.modal.close('equirement-modal');
}

function addDeviceId() {
  if (!model.value.deviceIds) {
    model.value.deviceIds = [''];
  }
  model.value.deviceIds.push('');
}

function removeDeviceId(index: number) {
  if (model.value.deviceIds && model.value.deviceIds.length > 1) {
    model.value.deviceIds.splice(index, 1);
  }
}

onBeforeMount(async () => {
  if (props.data) {
    model.value = { ...defaultModel, ...props.data };
  }
  // 获取设备名称·
  getDeviceType();
});

// 若 deviceType 当前为名称，按照选项映射成对应的 id
function normalizeDeviceTypeToId() {
  const current = model.value.deviceType;
  if (!current) return;
  const options = deviceTypes.value || [];
  // 已经是有效 id 则不处理
  const existsById = options.some((opt) => String(opt.id) === String(current));
  if (existsById) return;
  // 如果值是名称，回填为对应的 id
  const byName = options.find((opt) => String(opt.name) === String(current));
  if (byName) {
    model.value.deviceType = String(byName.id);
  }
}
</script>

<template>
  <div class="form-container">
    <vxe-form
      :title-width="formProps.titleWidth"
      :title-align="formProps.titleAlign"
      :title-colon="formProps.titleColon"
      :data="formProps.data"
      :items="formItems"
      :rules="formProps.rules"
      v-on="formEmits"
      :loading="submitting"
    >
      <template #deviceIdTitleSlot> <span style="color: #f56c6c; font-size: 20px">*</span> 设备ID </template>

      <template #deviceIdSlot>
        <div class="device-ids-container">
          <div v-for="(deviceId, index) in deviceIdsSafe" :key="index" class="device-id-item">
            <vxe-input v-model="deviceIdsSafe[index]" placeholder="请输入" style="width: 200px" />
            <vxe-button v-if="(model.deviceIds || []).length > 1" type="text" style="color: #ff4d4f; margin-left: 8px" @click="removeDeviceId(index)">
              <template #default>×</template>
            </vxe-button>
          </div>
          <vxe-button type="text" style="border: 1px dashed #d9d9d9; width: 32px; height: 32px; margin-bottom: 8px" @click="addDeviceId" v-if="!model?.id">
            <template #default>+</template>
          </vxe-button>
        </div>
      </template>

      <template #remarksSlot>
        <div class="section-container">
          <textarea
            v-model="model.remark"
            placeholder="请输入"
            rows="3"
            style="width: 100%; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px; resize: vertical; font-family: inherit"
          />
        </div>
      </template>

      <template #active>
        <vxe-button type="reset" content="取消" :disabled="submitting" @click="cancel"></vxe-button>
        <vxe-button type="submit" status="warning" content="确定" :loading="submitting"></vxe-button>
      </template>
    </vxe-form>
  </div>
</template>

<style scoped lang="scss">
.form-container {
  padding: 20px;
}

.device-ids-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;

  .device-id-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }
}

.section-container {
  margin-bottom: 20px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
  }

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

.process-config {
  .config-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 8px;

    .config-label {
      font-weight: bold;
      min-width: 80px;
    }

    .report-label {
      margin-left: 40px;
      color: #666;
      margin-right: 10px;
    }

    .radio-group {
      display: flex;
      align-items: center;
      gap: 30px;

      .radio-item {
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;

        input[type='radio'] {
          margin: 0;
          cursor: pointer;
        }

        span {
          font-size: 14px;
        }
      }

      .badge {
        background-color: #faad14;
        color: white;
        border-radius: 12px;
        padding: 2px 8px;
        font-size: 12px;
        min-width: 20px;
        text-align: center;
      }
    }
  }
}

:deep(.vxe-form--item) {
  .vxe-form--item-wrapper {
    .vxe-form--item-content {
      .vxe-input {
        width: 100%;
      }
    }
  }
}

.required-field {
  :deep(.vxe-form--item-title) {
    position: relative;

    &::before {
      content: '*';
      color: #ff4d4f;
      position: absolute;
      left: -8px;
      top: 0;
    }
  }
}
</style>
