<template>
    <hc-new-dialog :show="isShow" :title="title" widths="47rem" @close="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 v-if="isDatas && reportDatas.length > 0" label="审批内容">
                <div class="task-tag-data-box">
                    <template v-for="(item, index) in reportDatas" :key="item.id">
                        <el-tag closable size="default" type="info" @close="taskTagClose(index)">{{ item.name }}</el-tag>
                    </template>
                </div>
            </el-form-item>
            <el-form-item label="任务描述" prop="taskContent">
                <el-input v-model="formModel.taskContent" :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请输入任务描述" type="textarea" />
            </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" :key="item.id" :disabled="item.disabled" :value="item.id" :label="item.fixedFlowName">
                        <el-tooltip
                            v-if="item.tips && item.disabled"
                            class="box-item"
                            effect="light"
                            :content="item.tips "
                            placement="right-end"
                        >
                            {{ item.fixedFlowName }}
                        </el-tooltip>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="diyProcessUser" label="任务人" prop="userTasks">
                <HcTasksUser
                    :contract-id="contractId" :project-id="projectId" :type="type" :type-data="typeData"
                    ui="w-full" :classify-type="classifyType" :table-owner="tableOwner" :node-id="formModel.ids ? formModel.ids : nodeId "
                    :info-ids="infoIds" :data="dataInfo" @change="diyProcessUserChange"
                />
            </el-form-item>
            <el-form-item v-else label="任务人">
                <div class="form-item-div">{{ linkUserJoinString }}</div>
            </el-form-item>
            <el-form-item label="上报批次">
                <HcCounter v-model="formModel.batch" />
            </el-form-item>
            <el-form-item label="限定审批时间">
                <HcCounter v-model="formModel.restrictDay" text="(天)" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer text-center">
                <el-button size="large" @click="cancelReportClick">取消</el-button>
                <el-button :loading="formReportLoading" hc-btn type="primary" @click="formReportClick">提交</el-button>
            </div>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
//import tasksFlowApi from '~api/tasks/flow'
import { ApprovalApi, queryFixedFlow, queryFixedFlow1, queryFixedFlow3 } from '~api/other'
import { arrIndex, arrToId, formValidate, getArrValue, isNullES } from 'js-fast-way'
import { useAppStore } from '~src/store'
const useAppState = useAppStore()
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: '',
    },
    flowContractId: {
        type: [String, Number],
        default: '',
    },
    classifyType: {
        type: [String, Number],
        default: '',
    },
    tableOwner: {
        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: '',
    },
    trialSelfInspectionRecordId: {
        type: [String, Number],
        default: '',
    },
    nodeId:{
        type: [String, Number],
        default: '',
    },
    reportArr: {
        type: Array,
        default: () => ([]),
    },
})

const emit = defineEmits(['hide', 'finish', 'tagClose'])
//变量
const isShow = ref(props.show)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const flowContractId = ref(props.flowContractId)
const classifyType = ref(props.classifyType)
const tableOwner = ref(props.tableOwner)
const ApiUrl = ref(props.url)
const isTypes = ref(props.type)
const typeDatas = ref(props.typeData)
const reportDatas = ref(props.datas)
const nodeId = ref(props.nodeId)
const dataInfo = ref({
    projectId:props.projectId,
    contractId:props.contractId,
})
const contractId1 = ref(useAppState.contractId)
//表单
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,
    trialSelfInspectionRecordId: props.trialSelfInspectionRecordId,
    ...props.addition,
})
const formRules = ref({
    taskContent: {
        required: false,
        trigger: 'blur',
        message: '请输入任务描述',
    },
    fixedFlowId: {
        required: true,
        trigger: 'blur',
        message: '请选择任务流程',
    },
    userTasks: {
        required: true,
        trigger: 'blur',
        message: '请选择任务人',
    },
})

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

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

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

//获取资料查询获取流程数据
const infoIds = ref('')
const linkUserJoinString = ref('')
const getProcessData = async (type, datas) => {
    linkUserJoinString.value = ''
    let flowJson = {}
    if (type === 'first') {
        flowJson['firstId'] = datas
    } else if (type === 'log') {
        flowJson['theLogPrimaryKeyId'] = datas
    } else if (type === 'wbs' || type === 'query') {
        flowJson['privatePKeyId'] = datas
    }

    infoIds.value = arrToId(reportDatas.value)
    const cid = isNullES(flowContractId.value) ? contractId.value : flowContractId.value
    const { error, code, data } = await queryFixedFlow1({
        projectId: projectId.value,
        contractId: contractId.value,
        contractIdRelation:flowContractId.value,
        nodeId:nodeId.value,
        classifyType:classifyType.value,
        tableOwner:tableOwner.value,
        infoIds:infoIds.value,
        ...flowJson,
    })
    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 cid = isNullES(flowContractId.value) ? contractId.value : flowContractId.value
 
    const { error, code, data, msg } = await queryFixedFlow({
        projectId: projectId.value,
        // contractId: cid,
        contractId: contractId1.value,
        contractIdRelation:flowContractId.value,
        ...flowJson,
        nodeId:formModel.value.ids,
        classifyType:classifyType.value,
        tableOwner:tableOwner.value,
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        processData.value = [...processDefaultData, ...arr]
    } else {
        window.$message.error(msg)
        processData.value = processDefaultData
    }
}
//日志填报获取流程数据
const queryFixedFlowApi3 = async (type, datas) => {
    let flowJson = {}
    if (type === 'first') {
        flowJson['firstId'] = datas
    } else if (type === 'log') {
        // flowJson['theLogPrimaryKeyId'] = datas
        flowJson['theLogPrimaryKeyId'] = formModel.value.ids
    } else if (type === 'wbs') {
        flowJson['privatePKeyId'] = datas
    }
    //请求数据
    linkUserJoinString.value = ''
    const cid = isNullES(flowContractId.value) ? contractId.value : flowContractId.value
 
    const { error, code, data, msg } = await queryFixedFlow3({
        projectId: projectId.value,
        contractId: contractId.value,
        contractIdRelation:flowContractId.value,
        ...flowJson,
        // nodeId:formModel.value.ids,
        classifyType:classifyType.value,
        tableOwner:tableOwner.value,
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        processData.value = [...processDefaultData, ...arr]
    } else {
        window.$message.error(msg)
        processData.value = processDefaultData
    }
}
//流程数据切换
const diyProcessUser = ref(false)
const handleProcessValue = (val) => {
    if (val > 0) {
        diyProcessUser.value = false
        const list = processData.value
        const index = arrIndex(list, 'id', val)
        linkUserJoinString.value = list[index]?.linkUserJoinString
    } else {
        linkUserJoinString.value = ''
        diyProcessUser.value = true
    }
}

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

//审批内容的标签移除
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>
