// https://docs.authing.cn/v3/reference/sdk/node/management/%E7%AE%A1%E7%90%86%E7%BB%84%E7%BB%87%E6%9C%BA%E6%9E%84/update-department.html
const { ManagementClient,Models } = require('authing-node-sdk')
const managementClient  = new ManagementClient({
    accessKeyId: '669b25e1731d50c59f5494d1', // 用户池级别AKSK
    accessKeySecret: "4cfc095a72a67e22065c97e90054315c",
    host: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
})

/**
 * @example
 curl -X POST -H "Content-Type: application/json" -H "X-Parse-Application-Id: edu-textbook" -d '{
  "name": "测试部门",
  "organizationCode": 1000000
}' http://127.0.0.1:61337/parse/classes/Department
 */
export function defineDepartmentTrigger(){
    Parse.Cloud.beforeSave("Department", async (request) => {
        try{
            await syncDepartmentInfo(request,request.object)
        }catch(err){
            console.error(err)
        }
    });

    Parse.Cloud.beforeDelete("Department", async (request) => {
        let organizationCode = request?.object?.get("organizationCode")
        if(organizationCode) organizationCode = String(organizationCode)
        const result = await managementClient.deleteDepartment({
            // 替换组织 Code 和部门 ID
            organizationCode: organizationCode,
            departmentId: request?.object?.id
        });
    });
}


async function syncDepartmentInfo(request,depart){
    let authDepartment = {}
    if(depart?.id) authDepartment.departmentId = depart?.id
    if(depart?.get("status")) authDepartment.status = depart?.get("status")
    if(depart?.get("code")) authDepartment.code = depart?.get("code")
    if(depart?.get("name")) authDepartment.name = depart?.get("name")
    if(depart?.get("organizationCode")) authDepartment.organizationCode = String(depart?.get("organizationCode"))
    if(depart?.get("discription")) authDepartment.discription = depart?.get("discription")
    let parentDepartmentId = depart?.get("parent")?.id || depart?.get("parent")?.objectId || "root"
    if(parentDepartmentId) authDepartment.parentDepartmentId = parentDepartmentId

    let result
    if(depart?.id){ // 修改

    // INSERT INTO "Department" ("objectId", "organizationCode", "name", "description","branch","parent","code","createdAt","updatedAt","status","type","hasChildren")

        // let objectId = depart?.departmentId
        // if(!depart?.hasChildren){ // 最后一级，类型为单位
        //     depart.type = "单位"
        // }
        // let parentId = depart?.parent?.departmentId // 指针是正常的
        // let branchName = depart?.branch?.name // 分值为当前单位最上级分支（表示应用下，分支最高级名称）

        // rowData.push([
        //     // 1-5
        //     objectId, depart?.organizationCode, depart?.name, depart?.description, branchName,
        //     // 6-10
        //     parentId, depart?.code, depart?.createdAt || new Date(), depart?.updatedAt || new Date(), depart?.status,
        //     // 11
        //     depart?.type,depart?.hasChildren
        // ])

        // authDepartment.departmentIdType = Models.UpdateDepartmentReqDto.departmentIdType.DEPARTMENT_ID
        console.log(authDepartment)
        result = await managementClient.updateDepartment(authDepartment);
        
    }else{ // 新建
        // authDepartment.openDepartmentId = depart?.id
        // console.log(authDepartment)
        result = await managementClient.createDepartment(authDepartment);
        if(result?.statusCode==200){
            request.object.id = result?.data?.departmentId
        }
    }
    // console.log(result)
}