package com.iscs.bozzys.ui.pages.detail.job

import android.content.Context
import android.content.Intent
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.iscs.bozzys.R
import com.iscs.bozzys.ui.common.PageBase
import com.iscs.bozzys.ui.common.Title
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.create.job.openPageCreateJob
import com.iscs.bozzys.ui.pages.edit.step.openPageEditStep
import com.iscs.bozzys.ui.pages.vm.VMDetailJob
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.utils.DateUtil.getShowDateOrTime

/**
 * 跳转到作业详情页面
 */
fun Context.openPageDetailJob(id: Int) {
    startActivity(Intent(this, PageDetailJob::class.java).apply {
        // 传递序列化的对象
        putExtra("id", id)
    })
}

/**
 * 作业详情页面
 */
class PageDetailJob : PageBase() {

    @Composable
    override fun GetViews(pv: PaddingValues) {
        val id = intent.getIntExtra("id", 0)
        val vm: VMDetailJob = viewModel()
        val state by vm.state.collectAsState()
        // val pb = pv.calculateBottomPadding()
        LaunchedEffect(Unit) {
            vm.toast.initToast()
            vm.loading.initLoading()
            vm.init(id)
        }
        Column(modifier = Modifier.background(Color(0xFFF8F8F8))) {
            Title(
                pv,
                state.job.name,
                rightShow = state.job.id > 0 && state.job.status == "unreleased",
                rightIcon = R.drawable.edit,
                rightClick = { openPageCreateJob(state.job.id) })
            // 作业信息完整再加载
            if (state.job.id > 0) {
                // 作业基本信息
                JobInfo(vm)
                // 任务进度
                JobProgress(vm)
            }
            Column(
                modifier = Modifier
                    .weight(1f)
                    .verticalScroll(state = rememberScrollState())
                    .padding(16.dp)
            ) {

            }
            // 底部功能按钮
//            Row(
//                modifier = Modifier
//                    .padding(bottom = if (pb.value <= 0) 10.dp else pb, top = 10.dp)
//                    .padding(horizontal = 24.dp)
//                    .fillMaxWidth()
//            ) {
//                Button(
//                    {}, modifier = Modifier
//                        .weight(1f)
//                        .height(50.dp)
//                        .clip(RoundedCornerShape(12.dp)),
//                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFFFF0E6)),
//                    shape = RoundedCornerShape(12.dp)
//                ) {
//                    Row(verticalAlignment = Alignment.CenterVertically) {
//                        Icon(
//                            painter = painterResource(R.drawable.job_close),
//                            contentDescription = null,
//                            modifier = Modifier
//                                .padding(end = 5.dp)
//                                .size(16.dp),
//                            tint = Color(0xFFFF4D4F)
//                        )
//                        Text("审核不通过", color = Color(0xFFFF4D4F))
//                    }
//                }
//                Spacer(Modifier.width(16.dp))
//                Button(
//                    {}, modifier = Modifier
//                        .weight(1f)
//                        .height(50.dp)
//                        .clip(RoundedCornerShape(12.dp)),
//                    shape = RoundedCornerShape(12.dp)
//                ) {
//                    Row(verticalAlignment = Alignment.CenterVertically) {
//                        Icon(
//                            painter = painterResource(R.drawable.job_finish),
//                            contentDescription = null,
//                            modifier = Modifier
//                                .padding(end = 5.dp)
//                                .size(16.dp),
//                            tint = Color.White
//                        )
//                        Text("审核通过", color = Color.White)
//                    }
//                }
//            }
        }
    }

    /**
     * 作业的基本信息
     */
    @OptIn(ExperimentalLayoutApi::class)
    @Composable
    fun JobInfo(vm: VMDetailJob) {
        val state by vm.state.collectAsState()
        CardBox(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Column(Modifier.padding(16.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        painterResource(R.drawable.jobs),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .size(20.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Text("作业信息", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = Text)
                }
                // 分割线
                Spacer(
                    modifier = Modifier
                        .padding(vertical = 10.dp)
                        .fillMaxWidth()
                        .height(1.dp)
                        .background(Color.Black.copy(alpha = 0.1f))
                )
                FlowRow(verticalArrangement = Arrangement.Center) {
                    // 作业编号
                    JobInfoItem(R.drawable.number, "作业编号", state.job.orderNo)
                    // 作业负责人
                    JobInfoItem(R.drawable.user, "作业发起人", state.job.initiatorName)
                    // 作业紧急程度
                    JobInfoItem(R.drawable.job_warning, "紧急程度", state.job.getLevelNameAndColor().first)
                    // 作业状态
                    JobInfoItem(R.drawable.target, "作业状态", state.job.getJobStatusName())
                    // 车间岗位
                    // JobInfoItem(R.drawable.location,"车间A区")
                    // 作业类型
                    JobInfoItem(R.drawable.category, "作业类型", state.job.typeName.ifEmpty { "--" })
                    // 作业模板
                    JobInfoItem(R.drawable.template, "作业模板", state.job.designName)
                    // 作业创建时间
                    JobInfoItem(R.drawable.job_todo, "创建时间", state.job.createTime.getShowDateOrTime())
                    // 作业内容/描述
                    if (state.job.description.isNotEmpty()) JobInfoItem(R.drawable.content, "作业内容", state.job.description)
                }
            }
        }
    }

    /**
     * 作业信息item
     *
     * @param fraction  item占比宽度
     */
    @Composable
    fun JobInfoItem(@DrawableRes icon: Int, title: String, value: String, fraction: Float = 1f) {
        Row(
            modifier = Modifier
                .fillMaxWidth(fraction)
                .padding(bottom = 5.dp),
            verticalAlignment = Alignment.Top
        ) {
            Icon(
                painterResource(icon),
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier
                    .padding(end = 3.dp)
                    .size(18.dp)
                    .padding(1.dp)
                    .offset(y = 4.dp)
            )
            Text(
                title,
                fontSize = 14.sp,
                color = Text,
                modifier = Modifier
                    .width(75.dp)
                    .heightIn(min = 18.dp)
                    .alignBy(FirstBaseline)
            )
            Text(
                value,
                fontSize = 14.sp,
                color = Text.copy(alpha = 0.6f),
                modifier = Modifier
                    .weight(1f)
                    .heightIn(min = 18.dp)
                    .alignBy(FirstBaseline)
            )
        }
    }

    /**
     * 任务的当前进度
     */
    @Composable
    fun JobProgress(vm: VMDetailJob) {
        val state by vm.state.collectAsState()
        CardBox(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
                .offset(y = (-16).dp)
        ) {
            Column(Modifier.padding(16.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        painterResource(R.drawable.progress),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .size(20.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Text("作业进度", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = Text)
                    Spacer(modifier = Modifier.weight(1f))
                    // 只有待发布的时候不显示
                    if (state.job.status != "unreleased") Text(
                        "查看详情",
                        modifier = Modifier
                            .height(26.dp)
                            .clip(RoundedCornerShape(4.dp))
                            .clickable { openPageEditStep(state.job.id) }
                            .background(Color(0xFF1E90FF))
                            .padding(horizontal = 6.dp),
                        fontSize = 14.sp,
                        lineHeight = 26.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.White,
                        textAlign = TextAlign.Center
                    )
                }
                // 分割线
                Spacer(
                    modifier = Modifier
                        .padding(vertical = 10.dp)
                        .fillMaxWidth()
                        .height(1.dp)
                        .background(Color.Black.copy(alpha = 0.1f))
                )
                // 做当前节点和下一个节点显示
                Row {
                    Row(
                        verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                            .padding(vertical = 5.dp)
                            .weight(1f)
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.job_ing),
                            contentDescription = null,
                            modifier = Modifier.size(32.dp),
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Column(modifier = Modifier.padding(horizontal = 10.dp)) {
                            Text("当前执行", fontSize = 15.sp, lineHeight = 15.sp, color = Text)
                            Text(state.currentNodeName, fontSize = 14.sp, lineHeight = 14.sp, color = Text.copy(alpha = 0.6f))
                        }
                    }
                    if (state.nextNodeName.isNotEmpty()) Row(
                        verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                            .padding(vertical = 5.dp)
                            .weight(1f)
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.job_todo),
                            contentDescription = null,
                            modifier = Modifier.size(32.dp),
                            tint = Color.Gray
                        )
                        Column(modifier = Modifier.padding(horizontal = 10.dp)) {
                            Text("即将执行", fontSize = 15.sp, lineHeight = 15.sp, color = Text)
                            Text(state.nextNodeName, fontSize = 14.sp, lineHeight = 14.sp, color = Text.copy(alpha = 0.6f))
                        }
                    }
                }
            }
        }
    }
}