import { _decorator, Component, UITransform, Vec3 } from 'cc'
import { prefabOp } from './prefabOp'
import { PrefabNames } from './constant'
const { ccclass, property } = _decorator

import { sys, native } from 'cc'

@ccclass('main')
export class main extends Component {
  private prefab: prefabOp = new prefabOp()
  async start() {
    let assetsPath = ''
    if (sys.isNative) {
      // 原生平台
      assetsPath = native.fileUtils.getWritablePath() + '../assets'
    } else {
      // Web 平台
      assetsPath = window.location.href.replace(/\/[^/]*$/, '') + '/assets'
    }
    console.log('Final Assets Path:', assetsPath)
    const instance = await this.prefab.LoadAsync(PrefabNames.Login)
    this.node.addChild(instance)

    // 获取父节点和预制体的尺寸
    const parentTransform = this.node.getComponent(UITransform)
    const instanceTransform = instance.getComponent(UITransform)

    if (parentTransform && instanceTransform) {
      // 计算左下角坐标（考虑锚点）
      const x = -parentTransform.width * (0.5 - parentTransform.anchorX) + instanceTransform.width * (0.5 - instanceTransform.anchorX)
      const y = -parentTransform.height * (0.5 - parentTransform.anchorY) + instanceTransform.height * (0.5 - instanceTransform.anchorY)

      console.log('Final Assets Path:', x, '  ', y)
      instance.setPosition(new Vec3(x, y, 0))
      instance.active = true
    }
  }

  protected onDestroy(): void {
    this.prefab.Release(PrefabNames.Login)
  }
  update(deltaTime: number) {}
}
