<template>
    <el-dialog v-model="isShow" :title="title" width="47rem" class="hc-modal-border" draggable destroy-on-close @closed="cancelReportClick">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-width="auto" size="large">
            <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="formModel.taskName" disabled/>
            </el-form-item>
            <el-form-item label="审批内容" v-if="isDatas && reportDatas.length > 0">
                <div class="task-tag-data-box">
                    <template v-for="(item,index) in reportDatas" :key="item.id">
                        <el-tag type="info" size="default" closable @close="taskTagClose(index)">{{item.name}}</el-tag>
                    </template>
                </div>
            </el-form-item>
            <el-form-item label="任务描述" prop="taskContent">
                <el-input type="textarea" v-model="formModel.taskContent" placeholder="请输入任务描述" :autosize="{ minRows: 3, maxRows: 5 }"/>
            </el-form-item>
            <el-form-item label="任务流程" prop="fixedFlowId">
                <el-select v-model="formModel.fixedFlowId" block @change="handleProcessValue">
                    <el-option v-for="item in processData" :label="item.fixedFlowName" :disabled="item.disabled" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="任务人" prop="userTasks" v-if="diyProcessUser">
                <HcTasksUser ui="w-full" :projectId="projectId" :contractId="contractId" :type="type" :typeData="typeData" @change="diyProcessUserChange"/>
            </el-form-item>
            <el-form-item label="任务人" v-else>
                <div class="form-item-div">{{linkUserJoinString}}</div>
            </el-form-item>
            <el-form-item label="上报批次">
                <HcCounter v-model:value="formModel.batch" @update:modelValue="batchUpdateValue"/>
            </el-form-item>
            <el-form-item label="限定审批时间">
                <HcCounter v-model:value="formModel.restrictDay" text="(天)" @update:modelValue="restrictDayUpdateValue"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="cancelReportClick">取消</el-button>
                <el-button type="primary" hc-btn :loading="formReportLoading" @click="formReportClick">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import {ref,watch,onMounted} from "vue";
import tasksFlowApi from '~api/tasks/flow';
import {ApprovalApi,queryFixedFlow} from '~api/other';
import {getArrValue,getIndex,formValidate} from "vue-utils-plus"
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: '上报审批'
    },
    taskName: {
        type: String,
        default: ''
    },
    ids: {
        type: String,
        default: null
    },
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    url: {
        type: [String,Number],
        default: ''
    },
    datas: {
        type: Array,
        default: () => ([])
    },
    isDatas: {
        type: Boolean,
        default: false
    },
    addition: {
        type: Object,
        default: () => ({})
    },
    type: { //first,log,wbs
        type: [String,Number],
        default: ''
    },
    typeData: {
        type: [String, Number, Array, Object],
        default: ''
    },
})

//变量
const isShow = ref(props.show)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const ApiUrl = ref(props.url)
const isTypes = ref(props.type)
const typeDatas = ref(props.typeData)
const reportDatas = ref(props.datas)

//表单
const formRef = ref(null)
const processData = ref([])
const formModel = ref({
    projectId: projectId.value, contractId: contractId.value, ids: props.ids, userTasks: null,
    taskName: props.taskName, taskContent: '', fixedFlowId: '', batch: 1, restrictDay: 1,
    ...props.addition
})
const formRules = ref({
    taskContent: {
        required: true,
        trigger: "blur",
        message: "请输入任务描述"
    },
    fixedFlowId: {
        required: true,
        trigger: "blur",
        message: "请选择任务流程"
    },
    userTasks: {
        required: true,
        trigger: "blur",
        message: "请选择任务人"
    }
})

//监听
watch(() => [
    props.show,
    props.projectId,
    props.contractId,
    props.taskName,
    props.ids,
    props.url,
    props.addition,
    props.type,
    props.typeData,
    props.datas
], ([val,pid,cid,name,ids,url,addition, type, typeData, datas]) => {
    isShow.value = val
    projectId.value = pid
    contractId.value = cid
    ApiUrl.value = url
    //更新到表单数据
    formModel.value = {
        projectId: pid, contractId: cid, ids: ids, taskName: name,
        taskContent: '', fixedFlowId: '', batch: 1, restrictDay: 1,
        ...addition
    }
    isTypes.value = type
    typeDatas.value = typeData
    reportDatas.value = datas
    if (val) {
        getProcessDatasApi()
    }
})

//渲染完成
onMounted(() => {
    getProcessDatasApi()
})

const processDefaultData = [{ id: 0, fixedFlowName: '自定义流程', disabled: false}]
const getProcessDatasApi = () => {
    if (isShow.value) {
        const type = isTypes.value
        if (type === 'first' || type === 'log' || type === 'wbs') {
            queryFixedFlowApi(type, typeDatas.value)
        } else {
            getProcessData()
        }
    }
}

//获取流程数据
const linkUserJoinString = ref('')
const getProcessData = async () => {
    linkUserJoinString.value = ''
    const { error, code, data } = await tasksFlowApi.getPageData({
        projectId: projectId.value,
        contractId: contractId.value,
        current: 1, size: 100
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        processData.value = [...processDefaultData, ...arr]
    } else {
        processData.value = processDefaultData
    }
}

//获取符合条件的预设流程（三大填报页、日志列表的批量上报、首件列表的批量上报）
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 = ''
    const { error, code, data } = await queryFixedFlow({
        projectId: projectId.value,
        contractId: contractId.value,
        ...flowJson
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        processData.value = [...processDefaultData, ...arr]
    } else {
        processData.value = processDefaultData
    }
}

//流程数据切换
const diyProcessUser = ref(false)
const handleProcessValue = (val) => {
    if (val > 0) {
        diyProcessUser.value = false
        const list = processData.value
        const index = getIndex(list, 'id', val)
        linkUserJoinString.value = list[index]?.linkUserJoinString
    } else {
        linkUserJoinString.value = ''
        diyProcessUser.value = true
    }
}

//自定义流程任务人选择完毕
const diyProcessUserChange = (user) => {
    formModel.value.userTasks = user
}

//上报批次改变
const batchUpdateValue = (val) => {
    formModel.value.batch = val
}

//上报批次改变
const restrictDayUpdateValue = (val) => {
    formModel.value.restrictDay = val
}

const emit = defineEmits(['hide','finish', 'tagClose'])

//审批内容的标签移除
const taskTagClose = (index) => {
    reportDatas.value.splice(index, 1)
    emit('tagClose', index)
    if (reportDatas.value.length <= 0) {
        window.$message?.warning('请重新选择要上报的内容')
        cancelReportClick()
    }
}

//取消
const cancelReportClick = () => {
    linkUserJoinString.value = ''
    isShow.value = false
    emit('hide', false)
}
//上报
const formReportClick = async () => {
    const res = await formValidate(formRef.value)
    if (res) await batchApprovalApi()
}

//上报请求
const formReportLoading = ref(false)
const batchApprovalApi = async () => {
    formReportLoading.value = true
    //发起请求
    const { error, code, data } = await ApprovalApi(ApiUrl.value, {
        projectId: projectId.value,
        contractId: contractId.value,
        ...formModel.value
    })
    linkUserJoinString.value = ''
    formReportLoading.value = false
    if (!error && code === 200) {
        isShow.value = false
        window.$message?.success('上报成功')
        emit('hide', false)
        emit('finish', data)
    } else {
        processData.value = []
    }
}
</script>

<style lang="scss" >
.task-tag-data-box {
    position: relative;
    border: 1px solid #e0e0e6;
    border-radius: 4px;
    padding: 5px;
    min-height: 40px;
    display: flex;
    align-items: center;
    flex-flow: row wrap;
    width: 100%;
    .el-tag {
        margin: 5px;
    }
}
</style>
