<template>
    <el-dialog
        v-model="isShow" title="批量上报" class="hc-modal-border" destroy-on-close draggable width="47rem"
        append-to-body @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="任务描述" 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">
                    <template v-for="item in processData" :key="item.id">
                        <el-option :disabled="item.disabled" :label="item.fixedFlowName" :value="item.id" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item v-if="diyProcessUser" label="任务人" prop="userIds">
                <HcTasksUserVue class="w-full" @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">
                <el-button size="large" @click="cancelReportClick">
                    取消
                </el-button>
                <el-button :loading="formReportLoading" hc-btn type="primary" @click="formReportClick">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import tasksFlowApi from '~api/tasks/flow'
import { arrIndex, arrToId, arrToKey, formValidate } from 'js-fast-way'
import HcTasksUserVue from './hc-tasks-user/index.vue'
import { useAppStore } from '~src/store'

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    data: {
        type: Array,
        default: () => ([]),
    },
})

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

//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const isShow = ref(props.show)

const formModel = ref({ batch: 1, restrictDay: 1 })

//监听
watch(() => [
    props.projectId,
    props.contractId,

], ([pid, cid]) => {
    projectId.value = pid
    contractId.value = cid
  
  
    
})

//监听
watch(() => props.show, (val) => {
    isShow.value = val
    setReportData(val)
})


//表单
const formRef = ref(null)

const formRules = ref({
    taskContent: {
        required: false,
        trigger: 'blur',
        message: '请输入任务描述',
    },
    fixedFlowId: {
        required: true,
        trigger: 'blur',
        message: '请选择任务流程',
    },
    userIds: {
        required: true,
        trigger: 'blur',
        message: '请选择任务人',
    },
})

//处理上报数据
const setReportData = (show) => {
    if (!show) return false
    let taskName = '', ids = ''
    for (let i = 0; i < props.data.length; i++) {
        const item = props.data[i]
        ids = ids ? `${ids},${item.id}` : item.id
        taskName = taskName ? `${taskName},${item.fileName}` : item.fileName
    }
    formModel.value.dataIds = ids
    formModel.value.taskName = taskName
    //获取任务流程
    processData.value = []
    getProcessDatasApi()
}

//获取流程数据
const processDefaultData = [{ id: 0, fixedFlowName: '自定义流程', disabled: false }]
const processData = ref([])
const linkUserJoinString = ref('')
const getProcessDatasApi = () => {
    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) => {
    let userArr = user
    formModel.value.userIds = arrToKey(userArr, 'userId', ',')
}

//取消
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 tasksFlowApi.batchReportTaskArchive( {
        ...formModel.value,
        contractId:contractId.value,
        projectId:projectId.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 = []
    }
    emit('hide', false)
    emit('finish')
}
</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>
