import com.atlassian.jira.component.ComponentAccessor
import org.apache.commons.io.IOUtils


def componentFiles = [
    "mcu-asw-components.csv" : "MCUASW",
    "mcu-bsw-components.csv" : "MCUBSW",
    "mcu-bsw-supplier-components.csv" : "MCUBSWSUP",
    "tcu-asw-components.csv" : "TCUASW",
    "tcu-bsw-supplier-components.csv" : "TCUBSWSUP"
]


def projectManager = ComponentAccessor.projectManager
def attachmentManager = ComponentAccessor.attachmentManager
def userManager = ComponentAccessor.userManager
def projectComponentManager = ComponentAccessor.projectComponentManager
def commentManager = ComponentAccessor.commentManager
def loggedInUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser


def projectPrefix = issue.getCustomFieldValue("Project Name")

if(!projectPrefix){
    log.error("Project Name为空,无法创建组件")
    return
}


log.error("项目编号前缀:${projectPrefix}")


def attachments = attachmentManager.getAttachments(issue)
        .findAll{
            componentFiles.containsKey(it.filename.toLowerCase())
        }


if(attachments.isEmpty()){
    log.error("未找到组件CSV附件")
    return
}


def assigneeTypeMapping = [
    "PROJECT_LEAD":1L,
    "COMPONENT_LEAD":2L,
    "UNASSIGNED":3L
]


int totalCreated = 0
int totalSkipped = 0

def result = []


attachments.each { attachment ->

    try{

        def attachmentName = attachment.filename.toLowerCase()

        def suffix = componentFiles[attachmentName]

        def targetProjectKey = projectPrefix + suffix


        def targetProject = projectManager.getProjectObjByKey(targetProjectKey)


        if(!targetProject){

            log.error("目标项目不存在,跳过:${targetProjectKey}")

            result << "${targetProjectKey}:项目不存在"

            return
        }


        log.error("开始创建组件,项目:${targetProjectKey}")


        def csvText = attachmentManager.streamAttachmentContent(
            attachment,
            { InputStream inputStream ->
                IOUtils.toString(inputStream,"UTF-8")
            }
        )


        def parseComponents = []


        csvText.readLines().eachWithIndex { line, idx ->


            if(idx == 0){
                return
            }


            if(!line.trim()){
                return
            }


            def parts = line.split(/[,,]/).collect{
                it?.trim()
            }


            if(parts.size() < 2){

                log.error("${attachmentName} 第${idx+1}行格式错误")

                return
            }


            def compName = parts[0]

            def compLead = parts[1]

            def description = parts.size()>2 ? parts[2] : ""

            def defaultAssignee = parts.size()>3 ?
                    parts[3]?.toUpperCase() :
                    "UNASSIGNED"



            if(!compName || !compLead){

                log.error("${attachmentName} 第${idx+1}行组件名称或负责人为空")

                return
            }


            def leadUser = userManager.getUserByName(compLead)


            if(!leadUser || !leadUser.isActive()){

                log.error(
                    "${attachmentName} 组件${compName}负责人不存在:${compLead}"
                )

                return
            }



            if(!assigneeTypeMapping.containsKey(defaultAssignee)){

                log.error(
                    "组件${compName}默认经办人配置错误:${defaultAssignee},使用UNASSIGNED"
                )

                defaultAssignee="UNASSIGNED"
            }


            parseComponents << [
                name:compName,
                lead:leadUser.key,
                description:description,
                assigneeType:assigneeTypeMapping[defaultAssignee]
            ]

        }



        def existsComponents =
                projectComponentManager.findAllForProject(targetProject.id)
                .collect{
                    it.name.toLowerCase()
                } as Set



        parseComponents.each { comp ->


            if(existsComponents.contains(comp.name.toLowerCase())){

                log.error(
                    "组件已存在,跳过:${targetProjectKey}/${comp.name}"
                )

                totalSkipped++

                return
            }


            def component =
                    projectComponentManager.create(
                        comp.name,
                        comp.description,
                        comp.lead,
                        comp.assigneeType,
                        targetProject.id
                    )


            if(component){

                totalCreated++

                log.error(
                    "创建成功:${targetProjectKey}/${comp.name}"
                )
            }

        }


    }catch(Exception e){

        log.error(
            "处理附件失败:${attachment.filename},${e.message}",
            e
        )

    }

}



def resultMsg =
"""
组件创建完成

项目:
${projectPrefix}

创建组件:
${totalCreated}

跳过已存在:
${totalSkipped}

${result.join("\n")}
"""


commentManager.create(
    issue,
    loggedInUser,
    resultMsg,
    true
)


log.error(resultMsg)