<!-- 新建任务 -->
<template>
    <el-dialog :title="`${ editType == 'add' ? '新建' : '编辑' }任务`" v-model="visible" width="850px" destroy-on-close>
        <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="任务时间：" prop="taskBeginTime">
                <el-date-picker
                    v-model="form.taskBeginTime"
                    type="datetime"
                    placeholder="请选择任务时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled-date='disabledDates'
                    :disabled-hours="disabledHours"
                    :disabled-minutes="disabledMinutes"
			        :disabled-seconds="disabledSeconds"
                />
            </el-form-item>
            <el-form-item label="任务主题：" prop="taskContent">
                <el-input v-model="form.taskContent" placeholder="请输入任务主题"/>
            </el-form-item>
            <el-form-item label="任务目的：" prop="objectiveValue">
                <SelectDict v-model="form.objectiveValue" placeholder="选择任务目的"
                            dictCode="objective_value"></SelectDict>
            </el-form-item>
            <el-form-item label="紧要程度：" prop="priorityGrade">
                <SelectDict type="radio" :selectedFirst="editType == 'add'" v-model="form.priorityGrade" dictCode="task_priority_grade"></SelectDict>
            </el-form-item>
            <el-form-item label="关联业务：" class="business-item" v-if="isCorrelation" prop="resourceType">
                <resourceSelect
                    v-model="form.resourceType"
                    v-model:resourceTypeId="form.resourceTypeId"
                    :resourceName="openData?.resourceName"
                />
            </el-form-item>
            <el-form-item label="任务人员：" prop="ownerBy">
                <SelectUser v-model="form.ownerBy" ></SelectUser>
            </el-form-item>
            <el-form-item label="抄送人员：" prop="cooperateBy">
                <SelectUser  multiple v-model="form.cooperateBy"></SelectUser>
            </el-form-item>
            <el-form-item label="任务标记：">
                <SelectDict type="custom" v-model="form.markTag" :selectedFirst="editType == 'add'" dictCode="task_mark_tag">
                    <template #default="data">
                        <div class="sign-div flex-center">
                            <div
                                class="sign flex"
                                v-for="item in data.data"
                                :key="item.value"
                                :style="{ background: item.value }"
                                @click="form.markTag = item.value"
                            >
                                <i-ep-check color="#FFF" v-if="form.markTag == item.value" />
                            </div>
                        </div>
                    </template>
                </SelectDict>
            </el-form-item>
            <el-form-item label="任务提醒：" prop="remindType">
                <SelectDict v-model="form.remindType" placeholder="请选择任务提醒" dictCode="task_remind_type"></SelectDict>
            </el-form-item>
            <el-form-item label="提醒方式：">
                <SelectDict
                    type="checkbox"
                    disabledItem="site"
                    :selectedFirst="editType == 'add'"
                    v-model="form.remindModels"
                    dictCode="task_remind_mode"
                ></SelectDict>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { addTask } from '@/api/task';
    import { TaskQuery, TaskForm } from '@/api/task/types';
    import { useDictCache } from '@/hooks/web/useDict'
    import useUserStore from '@/store/modules/user';
    import { noticeEventStore } from '@/store/modules/noticeEvent'
    import resourceSelect from './resourceSelect.vue';
    import moment from 'moment'
    const userNoticeEventStore = noticeEventStore()
    const { queryDictDetailByCodes } = useDictCache(['task_remind_type', 'task_priority_grade', 'task_mark_tag', 'task_remind_mode','objective_value'])
    queryDictDetailByCodes()

    const props = defineProps({
        isCorrelation: { // 是否有关联业务选择
            type: Boolean,
            default: true
        },
        isList: { // 是否是任务列表进来的
            type: Boolean,
            default: false
        }
    })
    const emits = defineEmits(['refresh'])

    const disabledDates = (time:Date) => {
        // 选择今天以及今天之后的日期
        return time.getTime() < Date.now() - 8.64e7// 如果没有后面的-8.64e7就是不可以选择今天
    }
    const date = new Date();
    const disabledHours = () => {
        return Array.from({ length: date.getHours() }, (_, i) => i);
    }
    const disabledMinutes = (selectedHour: number) => {
        if (selectedHour === date.getHours()) {
            return Array.from({ length: date.getMinutes() }, (_, i) => i);
        }
        return [];
    }
    const disabledSeconds = (selectedHour: number, selectedMinute: number) => {
        if (selectedHour === date.getHours() && selectedMinute === date.getMinutes()) {
            return Array.from({ length: date.getSeconds() }, (_, i) => i);
        }
        return [];
    }
    const visible = ref(false)
    const buttonLoading = ref(false)

    const taskFormRef = ref<ElFormInstance>();
    const userStore = useUserStore();
    const initFormData: TaskForm = {
        id: undefined,
        taskBeginTime: undefined,
        taskContent: undefined,
        resourceType: undefined,
        resourceTypeId: undefined,
        resourceTypeIdls: undefined,
        cooperateBy: undefined,
        priorityGrade: undefined,
        markTag: undefined,
        taskStatus: 0,
        operatorBy: undefined,
        operatorTime: undefined,
        remark: undefined,
        remindType: '30',
        remindModels: undefined,
        remindTime: undefined,
        ownerBy: (userStore.userId as any) || (userStore.userInfo as any)?.id,
        isDelete: undefined,
        sort: undefined,
        enabled: undefined,
        isCreateTask: true,
        objectiveValue: undefined,
    }

    const validator = (rule: any, value: any, callback: any) => {
        if(props.isList && !form.value.resourceTypeId) {
            callback(new Error('请选择具体的业务数据'))
        }
        callback()
    }

    const data = reactive<PageData<TaskForm, TaskQuery>>({
        form: { ...initFormData },
        rules: {
            taskBeginTime: [
                { required: true, message: "任务时间不能为空", trigger: "change" }
            ],
            objectiveValue: [
                { required: true, message: "请选择任务目的", trigger: "change" }
            ],
            taskContent: [
                { required: true, message: "任务主题不能为空", trigger: "blur" }
            ],
            remindType: [
                { required: true, message: "任务提醒不能为空", trigger: "change" }
            ],
            ownerBy: [
                { required: true, message: "任务人员不能为空", trigger: "change" }
            ],
            resourceType: [
                { required: props.isList, message: "关联业务不能为空", trigger: "change" },
                { validator: validator, trigger: "change" }
            ]
        }
    });

    const { form, rules } = toRefs(data);

    const editType = ref('')
    const openData = ref()
    const open = ({ type, obj }: { type: string, obj: any }) => {
        reset();
        editType.value = type
        if(obj) {
            openData.value = JSON.parse(JSON.stringify(obj))
            if(type == 'edit') {
                openData.value.cooperateBy = openData.value.cooperateBy?.split(",")
                openData.value.priorityGrade = String(openData.value.priorityGrade)
                openData.value.remindType = String(openData.value.remindType)
            }
            nextTick(() => {
                Object.assign(form.value, openData.value)
            })
        }
        if(type == 'add') {
            form.value.taskBeginTime = moment().format('YYYY-MM-DD HH:mm:ss')
        }
        visible.value = true
    }

    const submitForm = () => {
        taskFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                let params = JSON.parse(JSON.stringify(form.value))
                params.cooperateBy = params.cooperateBy?.join(",")
                buttonLoading.value = true;
                await addTask(params).finally(() => buttonLoading.value = false);
                ElMessage.success((editType.value == 'add' ? '新增' : '编辑') + "成功");
                reset()
                visible.value = false
                userNoticeEventStore.noticTaskEvent()
                emits('refresh')
            }
        });
    }

    const cancel = () => {
        reset();
        visible.value = false
    }

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        taskFormRef.value?.resetFields();
    }

    defineExpose({
        open
    })
</script>

<style lang="scss" scoped>
    .business-item{
        :deep(.el-form-item__content){
            display: flex;
            column-gap: 8px;
            .el-select{
                flex: 1
            }
        }
    }
    .el-form-item{
        :deep(.el-date-editor){
            width: 100%;
            .el-input__wrapper{
                width: 100%;
            }
        }
        .el-row{
            width: 100%;
        }
    }

</style>
