<template>
    <hc-sys class="hc-report-page" :isNavBar="false">
        <uni-card class="" :is-shadow="false" is-full>
            <text class="text-black text-df">{{formData.taskName ?? ''}}</text>
        </uni-card>

        <uni-section class="mt-2" title="上报审批表单" type="line">
            <view class="p-2">
                <uni-forms ref="formRef" :rules="formRules" :modelValue="formData" label-width="190rpx">
                    <uni-forms-item label="上报说明" required name="taskContent">
                        <uni-easyinput type="textarea" v-model="formData.taskContent" placeholder="请输入上报说明" />
                    </uni-forms-item>
                    <uni-forms-item label="上报流程" required name="fixedFlowId">
                        <uni-data-select v-model="formData.fixedFlowId" :localdata="fixedFlowData" @change="fixedFlowChange"/>
                    </uni-forms-item>
                    <uni-forms-item class="hc-form-item" label="任务人" required name="userTasks" v-if="diyProcessUser">
                        <view class="tasks-user-box" @click="userTasksClick">
                            <view class="tag-user-list" v-if="formData.userTasks && formData.userTasks.length > 0">
                                <template v-for="(item, index) in formData.userTasks">
                                    <uni-tag :text="item.userName" type="primary"/>
                                    <text class="i-ri-arrow-right-line arrow-icon-tag" v-if="(formData.userTasks.length - 1) > index"/>
                                </template>
                            </view>
                            <view v-else class="tasks-placeholder">点击这里选择任务人</view>
                        </view>
                    </uni-forms-item>
                    <uni-forms-item class="hc-form-item" label="任务人" v-else>
                        <view class="form-item-div">{{ linkUserJoinString }}</view>
                    </uni-forms-item>
                    <uni-forms-item class="hc-form-item" label="上报批次">
                        <uni-number-box v-model="formData.batch" :min="1"/>
                    </uni-forms-item>
                    <uni-forms-item class="hc-form-item" label="限定审批时间">
                        <uni-number-box v-model="formData.restrictDay" :min="1"/>
                        <text class="text ml-4">(天)</text>
                    </uni-forms-item>
                </uni-forms>
            </view>
        </uni-section>

        <!--底部操作栏-->
        <HcTabbarBlock :height="77"/>
        <hc-tabbars>
            <button type="primary" class="action-bar-btn" @click="submitClick">确认上报</button>
        </hc-tabbars>
    </hc-sys>
</template>

<script setup>
import {ref, nextTick, getCurrentInstance} from "vue";
import {onLoad} from '@dcloudio/uni-app'
import {ApprovalApi, queryFixedFlow} from '~api/other/index'
import {arrIndex, getArrValue, getObjValue} from "js-fast-way";
import {errorToast, successToast, formValidate} from "@/utils/tools";
import flowApi from '~api/tasks/flow'

//页面传参数据
const instance = getCurrentInstance().proxy
const props = ref({})

//渲染完成
onLoad(async () => {
    await getEventChannel();
    getFixedFlowDataApi().then();
    // 设置自定义表单校验规则，必须在节点渲染完毕后执行
    formRef.value?.setRules(formRules)
})

//页面传参数据
let eventChannel = null;
const getEventChannel = async () => {
    await nextTick();
    eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('reportProps', (data) => {
        const res = getObjValue(data);
        const addition = getObjValue(res.addition)
        props.value = res
        //初始表单
        formData.value = {
            ids: res.ids,
            userTasks: [],
            taskName: res.taskName,
            taskContent: '',
            fixedFlowId: '',
            batch: 1,
            restrictDay: 1,
            trialSelfInspectionRecordId: res.trialSelfInspectionRecordId ?? '',
            ...addition,
        }
    })
}

//获取流程数据
const fixedFlowData = ref([])
const linkUserJoinString = ref('')
const fixedFlowDefault = [{
    value: 0, text: '自定义流程', disable: false, linkUserJoinString: null
}]
const getFixedFlowDataApi = async () => {
    uni.showLoading({title: '获取数据中...', mask: true});
    const { type, typeData } = props.value
    if (type === 'first' || type === 'log' || type === 'wbs') {
        await queryFixedFlowApi(type, typeData)
    } else {
        await getProcessData()
    }
    uni.hideLoading();
}

//获取流程数据
const getProcessData = async () => {
    linkUserJoinString.value = ''
    fixedFlowData.value = fixedFlowDefault
    const { projectId, contractId } = props.value
    const { error, code, data } = await flowApi.getPageData({
        projectId: projectId,
        contractId: contractId,
        current: 1, size: 100,
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        for (let i = 0; i < arr.length; i++) {
            fixedFlowData.value.push({
                value: arr[i].id,
                text: arr[i].fixedFlowName,
                disable: arr[i].disabled,
                linkUserJoinString: arr[i].linkUserJoinString
            })
        }
    }
}

//获取符合条件的预设流程（三大填报页、日志列表的批量上报、首件列表的批量上报）
const queryFixedFlowApi = async (type, datas) => {
    let flowJson = {}
    if (type === 'first') {
        flowJson['firstId'] = datas
    } else if (type === 'log') {
        flowJson['theLogPrimaryKeyId'] = datas
    } else if (type === 'wbs') {
        flowJson['privatePKeyId'] = datas
    }
    //请求数据
    linkUserJoinString.value = ''
    fixedFlowData.value = fixedFlowDefault
    const { projectId, contractId } = props.value
    const { error, code, data } = await queryFixedFlow({
        projectId: projectId,
        contractId: contractId,
        ...flowJson,
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        for (let i = 0; i < arr.length; i++) {
            fixedFlowData.value.push({
                value: arr[i].id,
                text: arr[i].fixedFlowName,
                disable: arr[i].disabled,
                linkUserJoinString: arr[i].linkUserJoinString
            })
        }
    }
}

//任务流程
const diyProcessUser = ref(false)
const fixedFlowChange = (val) => {
    if (val > 0) {
        diyProcessUser.value = false
        const list = fixedFlowData.value
        const index = arrIndex(list, 'value', val)
        linkUserJoinString.value = list[index]?.linkUserJoinString
        formData.value.userTasks = []
    } else {
        linkUserJoinString.value = ''
        formData.value.userTasks = []
        diyProcessUser.value = true
    }
}

//表单数据
const formRef = ref(null)
const formData = ref({
    userTasks: [],
})
const formRules = {
    taskContent: {
        rules: [{
            required: true,
            errorMessage: '上报说明不能为空'
        }]
    },
    fixedFlowId: {
        rules: [{
            required: true,
            errorMessage: '上报流程不能为空'
        }]
    },
    userTasks: {
        rules: [{
            required: true,
            errorMessage: '任务人不能为空'
        }]
    },
}

//选择任务人
const userTasksClick = () => {
    uni.navigateTo({
        url: '/pages/report/tasks-user',
        events:{
            flowUserList: function(data) {
                formData.value.userTasks = data
            }
        },
        success: function(res){
            const { type, typeData, projectId, contractId } = props.value
            const {userTasks} = formData.value
            res.eventChannel.emit('flowUserData', {
                type: type,
                typeData: typeData,
                projectId: projectId,
                contractId: contractId,
                selectedData: userTasks
            })
        }
    });
}

//确认提交
const submitClick = async () => {
    const res = await formValidate(formRef.value)
    if (!res) return false;
    //发起请求
    uni.showLoading({title: '上报审批中...', mask: true});
    const { projectId, contractId, url } = props.value
    const { error, code, msg } = await ApprovalApi(url, {
        projectId: projectId,
        contractId: contractId,
        ...formData.value,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('上报成功', 3000);
        //eventChannel.emit('finish');
        setTimeout(() => {
            //跳转到任务列表
            uni.switchTab({
                url: '/pages/task/index'
            });
            //uni.navigateBack();
        }, 3000)
    } else {
        errorToast(msg);
    }
}
</script>

<style lang="scss">
@import "@/style/report/report.scss";
</style>
