<template>
	<button
            v-for="item in transitions"
            :key="item.id"
            :type="item.attribute_type === 2 ? 'warn' : 'primary'"
            :loading="isSaveing"
            :disabled="isSaveing"
            @click="handleTransition(item)"
            size="mini"
        >{{ item.name }}</button>
</template>
<script setup>
import { ref, reactive, onMounted, defineEmits, watch } from 'vue'
import API from '@/utils/api';

const props = defineProps({
    workflow_key: {type: String, default: null, required: false},
    ticket_: {type: Object, default: null, required: false},
    t_id: {type: String, default: null, required: true},
    title: {type: String, default: null, required: false},
    submit_b_func: {type: Function, default: null, required: false},
    ticket_data: {type: Object, default: null, required: false},
})

const workflow = ref(null);
const transitions = ref([]);
const currentUser = ref(uni.getStorageSync("userInfo").id);
onMounted(async () => {
	setTimeout(()=>{init()}, 1000)
	// await init();
	// watch(
	//   () => props.ticket_,
	//   async (newVal) => {
	//     if (newVal && Object.keys(newVal).length > 0) {
	// 		await init();
	//     }
	//   },
	//   { deep: true }
	// )
})
const suggestion = ref("")
const isOwn = ref(false)
const ticketId = ref(null)
const init = async () => {
	transitions.value = [];
    if (props.ticket_ && props.ticket_.id) {
		isOwn.value = props.ticket_.create_by === currentUser.value;
        ticketId.value = props.ticket_.id;
        const isParticipant =
        (props.ticket_.participant_type === 1 && props.ticket_.participant === currentUser.value) ||
        (props.ticket_.participant_type === 2 && props.ticket_.participant.includes(currentUser.value))
        if (isParticipant) {
			transitions.value = await API.getTransition(props.ticket_.id);
        }
    }else if (props.workflow_key) {
        let res = await API.workflowInitkey(props.workflow_key);
        transitions.value = res.transitions;
        workflow.value = res.workflow
    }else{
		uni.showToast({
			icon:"error",
			title:"缺少workflow_key或ticketId"
		})
    }
}

const isSaveing = ref(false);

const emit = defineEmits(["success"]);
const submit = async (transition_id) => {
    isSaveing.value = true;
	if (props.submit_b_func) {
	    try{
	        await props.submit_b_func();
	    }catch (e) {
            console.log(e)
	        isSaveing.value = false;
	        return;
	    }
	}
    if (ticketId.value) {
		console.log('props.ticket_data',props.ticket_data)
        let params = new Object();
        params.transition = transition_id;
		params.suggestion = suggestion.value;
        if (props.ticket_data) {
            params.ticket_data = props.ticket_data;
        }else{
            params.ticket_data = {};
        }
        try{
            let res = await API.ticketHandle(props.ticket_.id, params);
            isSaveing.value = false;
            uni.showToast({
                title: '提交成功',
                icon: 'success'
            });
            emit("success", props.ticket_.id)
        } catch (e) {
            isSaveing.value = false;
            return;
        }
    } else {
        let ticket = {};
        ticket.title = props.title;
        ticket.workflow = workflow.value;
        if (props.t_id != null && props.t_id != undefined) {
            ticket.ticket_data = {
                t_id: props.t_id,
            };
        } else {
            uni.showToast({
                title: '缺少t_id',
                icon: 'error'
            });
            isSaveing.value = false;
            return;
        }
        
        try {
            let res = await API.ticketCreate(ticket);
            ticketId.value = res.id;
            try{
                await API.ticketHandle(ticketId.value, {transition: transition_id, ticket_data: props.ticket_data?props.ticket_data:{}});
                isSaveing.value = false;
                uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                });
                emit("success", res.id)
            }catch (e) {
                isSaveing.value = false;
                return;
            }
        } catch (e) {
            isSaveing.value = false;
            return;
        }
    }
};
// const handleRetreat = async () =>{
// 	await API.ticketRetreat(props.ticket_.id, {"suggestion": suggestion.value});
// }
const handleTransition = async (item) =>{
	if (item.attribute_type != 1) {
		uni.showModal({
			title: "处理意见",
			editable: true,
			success(res) {
				if(res.confirm){
					suggestion.value = res.content?res.content:"";
					submit(item.id);
				}
			}	
		})
	} else {
		submit(item.id);
	}
}
</script>