<template>
    <view class="container">
        <task-tree :showAuxiliaryLine="false" :border="true" labelKey="name" valueKey="task_id" ref="treeRef"
            :uiStatus="uiShow.ui_status" :foldAll="true" @operator="operatorTask" @setProgress="setProgress"
            :draft="draft" :isFirstLoad="isFirstLoad" funcMode="edit" pageTop="45px" :treeData="tasks" uiMode="page"
            titleColor="#5d5959">
            <template #empty>
                <view class="empty">
                    <image :src="emptySrc" class="empty-image"> </image>
                    <text class="empty-text">暂无项目计划</text>
                </view>
            </template>
            <template #topBar>
                <view
                    style="display: flex;align-items: center; justify-content: space-between;padding:0 20rpx 10rpx 20rpx">
                    <div style="flex:1;align-items: center;display: flex;">
                        <div style="flex: 0 0 32px; line-height: 32px;" v-if="draft">
                            <uni-icons :size="20" color="#323233" type="undo"
                                @click="handlerDraftChanged(false)"></uni-icons>
                        </div>
                        <div style="flex: 1 1 auto;">
                            <div v-if="draft" style="text-align: center; font-weight: bold; font-size: 16px;">
                                计划草稿
                            </div>
                        </div>
                    </div>
                    <div v-if="works.length > 0 || uiShow.ui_status?.alter" style="display: flex;">
                        <button v-if="uiShow.ui_status?.alter" size="default" @click="handlerDraftChanged(true)"
                            class="task-btn" hover-class="is-hover">计划草稿</button>
                        <button class="task-btn" size="default" v-for="item in works" :key="item.id"
                            hover-class="is-hover" @click="showProcessWorks(item)"> {{ item.name }}</button>
                    </div>
                </view>
            </template>
            <template #fixedBottomBar>
                <custom-button width="100%" color="#007aff" :radius="['5px']" ripple
                    v-if="editable(uiShow.ui_status?.name)" @click="handlerAddPTask()">添加任务</custom-button>
            </template>
        </task-tree>
        <ProcessWork ref="processWorkRef" />
    </view>
</template>
<script setup lang="ts">
import { getPlanTaskList, removePlanTask } from '@/api/project-center/plan-task';
import taskTree from '@/components/task-tree/index.vue'
import ProcessWork from '@/components/process-work/index.vue'
import { OperateTypeItem } from '@/enums/api';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { TaskListReqParams, UiStatus } from '@/types/plan-task';
import { OverviewProjectResParams } from '@/types/project';

interface Tasks {
    task_id: string
    name?: string
    pid?: string
    progress?: number
    status?: number
    handler_id?: string
    handler_name?: string
    begin_at?: string
    end_at?: string
    children?: Tasks[]
    sub_tasks?: Tasks[]
    isLeaf?: boolean
    layer?: number
    works?: { id: string, name: string }[]
}



const props = defineProps({
    prj: {
        type: Object as PropType<OverviewProjectResParams>,
        required: true
    },
    accountList: {
        type: Array as PropType<{ id: string; name: string }[]>,
    },
    pDraft: {
        type: Boolean,
        required: true,
        default: () => {
            return false
        }
    }
})

const emptySrc = ref('data:image/png;base64, ')

const treeRef = ref()
const processWorkRef = ref<any>(null)
const uiShow = reactive<{ ui_status?: UiStatus }>({
    ui_status: {
        alter: true
    }
})

const { emitter } = useEmitt()
const isFirstLoad = ref(true);
const draft = ref()
const tasks = ref<Tasks[]>()
const works = ref<{ id: string; name: string }[]>([])



/**
 * 是否是编辑
 * @param type
 */
const editable = (type?: string) => {
    return type === OperateTypeItem.RW || type === OperateTypeItem.W
}

const operatorTask = (params: { task: Tasks, itemList: string[] }) => {
    const { task, itemList } = params
    startOperatorTask(task, itemList)
}

const setProgress = (task: Tasks) => {
    if (!editable(uiShow.ui_status?.progress) || !task.isLeaf) {
        return
    }
    uni.navigateTo({ url: `/pages/project/plan-task-list/set-plan-progress?task_id=${task.task_id}&task_pname=${task.name}&progress=${task.progress}` })
}


const startOperatorTask = async (task: Tasks, itemList: string[]) => {
    if (itemList.length > 0) {
        uni.showActionSheet({
            title: task.name,
            itemList: itemList,
            success: async (res: UniApp.ShowActionSheetRes) => {
                const { tapIndex } = res;
                switch (itemList[tapIndex]) {
                    case '添加':
                        console.log('跳转到添加页面')
                        uni.navigateTo({ url: `/pages/project/plan-task-list/add-plan-task?id=${props.prj.id}&task_pid=${task.task_id}&task_pname=${task.name}&draft=${draft.value}` })
                        break
                    case '修改':
                        const ui = {
                            name: uiShow.ui_status?.name,
                            handler_name: uiShow.ui_status?.handler_name,
                            begin_at: uiShow.ui_status?.begin_at,
                            end_at: uiShow.ui_status?.end_at
                        }
                        const rw_list = Object.values(ui) as string[]
                        console.log('跳转修改页面')
                        uni.navigateTo({ url: `/pages/project/plan-task-list/edit-plan-task?task_id=${task.task_id}&draft=${draft.value}&rw=${rw_list.join(',')}` })
                        break
                    case '详情':
                        console.log('跳转详情页面')
                        emitter.emit('redirectTaskDetailPage', { id: task.task_id, draft: draft.value })
                        break
                    case '删除':
                        console.log('删除')
                        handlerRemoveTask(task.task_id, task.name!)
                        break
                    default:
                        const work = task.works?.find(item => item.name === itemList[tapIndex])
                        console.log('处理work')
                        console.log(work)
                        processWorkRef.value?.showWorkModal(work!.id)
                        break
                }
            }
        });
    }


}

// 切换到草稿模式
const handlerDraftChanged = async (isDraft: boolean) => {
    tasks.value = []
    draft.value = isDraft
    isFirstLoad.value = false
    await getTaskTree()
}

/**
 * 递归获取tree需要的结构体
 * @param task 接口返回的树状数组
 * @param layer 层级
 */
const getNodesTree = (task: Tasks, layer?: number): Tasks => {
    task.layer = (layer || 0) + 1 // 添加layer参数
    task.children = task.sub_tasks // 添加children参数
    if (task.children && task.children.length > 0) {
        task.children.map(res => getNodesTree(res, task.layer))
    } else {
        task.children = []
        task.isLeaf = true
    }
    return task
}

const getTaskTree = async () => {
    const params: TaskListReqParams = {
        prj_id: props.prj.id,
        draft: draft.value
    }
    const {
        tasks: list,
        ui_status: uiStatus,
        works: tWorks
    } = await getPlanTaskList(params)
    tasks.value = list.map(task => {
        return getNodesTree(task)
    })
    uiShow.ui_status = uiStatus
    works.value = tWorks || []
}

// 添加父级任务
const handlerAddPTask = () => {
    uni.navigateTo({ url: `/pages/project/plan-task-list/add-plan-task?id=${props.prj.id}&draft=${draft.value}` })
    return
}

/**
 * 删除任务
 * @param task_id 
 * @param task_name 
 */
const handlerRemoveTask = (task_id: string, task_name: string) => {
    uni.showModal({
        title: '删除任务',
        content: `确认删除任务：${task_name}`,
        success: async (res: { confirm: boolean }) => {
            const { confirm } = res;
            if (confirm) {
                await removePlanTask({ draft: draft.value, task_id })
                uni.showToast({
                    icon: 'success',
                    title: '删除成功'
                })
                setTimeout(() => getTaskTree(), 1500)
            }
        }
    })
    return
}

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
    name: 'get_task_list',
    callback: () => {
        getTaskTree()
    }
})

// 监听子组件
useEmitt({
  name: 'switch_draft_page',
  callback: (isDraft: boolean) => {
    console.log('switch_draft_page')
    console.log(isDraft)
    handlerDraftChanged(isDraft)
  }
})

// 开始处理计划work
const showProcessWorks = (item: { id: string, name: string }) => {
    processWorkRef.value?.showWorkModal(item.id)
}

onMounted(async () => {
    draft.value = props.pDraft
    await getTaskTree()
})

</script>
<style scoped>

.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
}

.empty-text {
  font-size: 28rpx;
  margin-top: 10rpx;
  padding: 0rpx 20rpx;
  color: #aaaaaa;
}


.arco-btn+.arco-btn {
    margin-left: 8px
}

.task-btn {
    padding-right: 16rpx;
    padding-left: 16rpx;
    color: #ffffff !important;
    background-color: #007aff;
    border-color: #007aff !important;
    font-size: 24rpx !important;
    -webkit-tap-highlight-color: transparent;
    border-radius: 5px;
    box-sizing: border-box;
    cursor: pointer;
    display: block;
    line-height: 2.55555556;
    margin-left: 5rpx;
    margin-right: auto;
    overflow: hidden;
    position: relative;
    text-align: center;
    text-decoration: none;
    height: auto;
}
</style>