<template>
    <hc-new-dialog widths="600px" bg-color="#fff" :show="isShow" title="流程上报" @save="modalSave" @close="modalClose">
        <el-form ref="formRef" class="p-4" :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="任务描述">
                <el-input v-model="formModel.taskDesc" :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="taskUserIds">
                <hc-tasks-user ui="w-full" :project-id="projectId" :contract-id="contractId" @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="上报批次">
                <hc-counter v-model="formModel.batch" />
            </el-form-item>
            <el-form-item label="限定审批时间">
                <hc-counter v-model="formModel.restrictDay" text="(天)" />
            </el-form-item>
        </el-form>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { arrIndex, arrToKey, formValidate, getArrValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import mainApi from '~api/tasks/flow'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['finish', 'close'])

//项目合同段
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

defineOptions({
    name: 'HcReportDialog',
})

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//任务数据
const reportInfo = ref(props.info)
watch(() => props.info, (obj) => {
    reportInfo.value = obj
}, { deep: true })

//监听
watch(isShow, (val) => {
    if (val) {
        getProcessData()
        getReportTaskName()
    }
})

//获取任务名称
const getReportTaskName = async () => {
    const { periodId, type } = reportInfo.value
    const { data } = await mainApi.reportTaskName({
        projectId: projectId.value,
        contractId: contractId.value,
        id: periodId,
        type,
    })
    formModel.value.taskName = data ?? ''
}

//任务流程
const processData = ref([])
const processDefaultData = [
    { id: 0, fixedFlowName: '自定义流程', disabled: false },
]

//获取流程数据
const linkUserJoinString = ref('')
const getProcessData = async () => {
    linkUserJoinString.value = ''
    const { error, code, data } = await mainApi.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 formRef = ref(null)
const formModel = ref({ batch: 1, restrictDay: 1 })
const formRules = ref({
    fixedFlowId: {
        required: true,
        trigger: 'blur',
        message: '请选择任务流程',
    },
    taskUserIds: {
        required: true,
        trigger: 'blur',
        message: '请选择任务人',
    },
})

//流程数据切换
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.taskUserIds = arrToKey(user, 'userId', ',')
}

//保存
const formReportLoading = ref(false)
const modalSave = async () => {
    const res = await formValidate(formRef.value)
    if (!res) return
    formReportLoading.value = true
    //发起请求
    const { error, code, msg } = await mainApi.reportTaskForm({
        ...formModel.value,
        ...reportInfo.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    formReportLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('上报成功')
        emit('finish')
        modalClose()
    } else {
        window.$message.error(msg ?? '上报失败')
    }
}

//关闭弹窗
const modalClose = () => {
    isShow.value = false
    formModel.value = { batch: 1, restrictDay: 1 }
    linkUserJoinString.value = ''
    emit('close')
}
</script>
