<template>
    <div style="background-color: white;">
        <!-- 加上load效果 -->
        <div class="form_center" v-loading="loading">
            <el-form :model="form" :rules="rules" ref="form" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="工单名称" prop="name">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="工单开始时间" prop="startTime">
                            <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
                                format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属团组" prop="groupId">
                            <el-select filterable v-model="form.groupId" placeholder="请选择">
                                <el-option v-for="item in initResp.groupList" :key="item.id" :label="item.teamName"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <!-- 添加筛选 -->
                        <el-form-item label="指派用户" prop="assignedUserId">
                            <el-select @change="userChange" filterable v-model="form.assignedUserId" placeholder="请选择">
                                <el-option v-for="item in initResp.users" :key="item.id" :label="item.cnName"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="外办选项" prop="foreignOptionId">
                            <el-select v-model="form.foreignOptionId" placeholder="请选择">
                                <el-option v-for="item in initResp.foreignLv" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">

                    </el-col>
                </el-row>
                <div class="form_detail">
                    <el-collapse v-model="activeNames">
                        <el-collapse-item title="主要任务" name="1">
                            <el-table :data="mainTasks" style="width: 100%" border>
                                <el-table-column type="index" label="序号" width="80"></el-table-column>
                                <el-table-column prop="name" label="单项任务名称" width="300">
                                    <template slot-scope="scope">
                                        <el-input :disabled="scope.$index + 1 <= form.action - 1" height="70"
                                            type="textarea" v-model="scope.row.name" size="mini"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="priorityId" label="优先级" width="100">
                                    <template slot-scope="scope">
                                        <el-select :disabled="scope.$index + 1 <= form.action - 1"
                                            v-model="scope.row.priorityId" size="mini" placeholder="请选择">
                                            <el-option v-for="item in initResp.taskLv" :key="item.id" :label="item.name"
                                                :value="item.id"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="isUrgent" label="是否加急" width="100">
                                    <template slot-scope="scope">
                                        <el-switch :disabled="scope.$index + 1 <= form.action - 1"
                                            v-model="scope.row.isUrgent" active-color="#13ce66"
                                            inactive-color="#ff4949">
                                        </el-switch>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="assignedUserId" label="指派给谁" width="120">
                                    <template slot-scope="scope">
                                        <el-select :disabled="scope.$index + 1 <= form.action - 1"
                                            v-model="scope.row.assignedUserId" size="mini" placeholder="请选择">
                                            <el-option v-for="item in initResp.users" :key="item.id"
                                                :label="item.cnName" :value="item.id"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="timeRange" label="任务时间（起止）">
                                    <template slot-scope="scope">
                                        <el-date-picker :disabled="scope.$index + 1 <= form.action - 1"
                                            v-model="scope.row.timeRange" type="datetimerange" range-separator="至"
                                            start-placeholder="开始日期" end-placeholder="结束日期" size="mini"
                                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                                            @change="onTimeRangeChange(scope.$index)">
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="durationHours" label="任务默认完成小时数" width="160">
                                    <template slot-scope="scope">
                                        <el-input-number :disabled="scope.$index + 1 <= form.action - 1"
                                            v-model="scope.row.durationHours" size="mini" :min="0"
                                            :step="1"></el-input-number>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column prop="requiredFieldsValue" label="必填项设置" width="120">
                                    <template slot-scope="scope">
                                        <el-checkbox-group v-model="scope.row.requiredFieldsValue"
                                            @change="handleCheckedCitiesChange">
                                            <div v-for="requiredFieldsItem in requiredFieldsItems">
                                                <el-checkbox :label="requiredFieldsItem.id"
                                                    :key="requiredFieldsItem.id">{{
                                                        requiredFieldsItem.name
                                                    }}
                                                </el-checkbox>
                                            </div>
                                        </el-checkbox-group>
                                    </template>
                                </el-table-column> -->
                                <el-table-column label="操作" width="120">
                                    <template slot-scope="scope">
                                        <div v-if="!(scope.$index + 1 <= form.action - 1)">
                                            <el-button class="czbtn" size="mini" type="primary"
                                                @click="insertTaskAbove(scope.$index)">插入行↑</el-button>
                                            <br />
                                            <!-- 删除图标加在文字后方 -->
                                            <el-button class="czbtn" style="margin: 10px 0;" size="mini" type="danger"
                                                @click="deleteTask(scope.$index)">删除
                                                <i class="el-icon-delete"></i></el-button>
                                            <br />
                                            <el-button class="czbtn" size="mini" type="primary"
                                                @click="insertTaskBelow(scope.$index)">插入行↓</el-button>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div style="margin-top: 10px;text-align: center;">
                                <el-button size="small" type="primary" @click="addTask">新增任务</el-button>
                            </div>
                        </el-collapse-item>
                        <el-collapse-item title="临时额外任务" name="2">
                            <div>临时额外任务内容区域</div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
                <br />
                <div style="text-align: right;">

                    <el-form-item>
                        <el-button type="primary" @click="submitForm">提交</el-button>
                        <el-button @click="resetForm">返回</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>


export default {
    data() {
        return {
            token: '',
            userId: '',
            typeId: 1453,
            activeNames: ['1'], // 只展开主要任务
            mainTasks: [
            ],
            form: {
                id: 0,
                name: '',
                startTime: '',
                groupId: '',
                assignedUserId: '',
                foreignOptionId: '',
                action: 1
            },
            rules: {
                name: [
                    { required: true, message: '请输入工单名称', trigger: 'blur' }
                ],
                startTime: [
                    { required: true, message: '请选择工单开始时间', trigger: 'change' }
                ],
                groupId: [
                    { required: true, message: '请输入所属团组ID', trigger: 'blur' }
                ],
                assignedUserId: [
                    { required: true, message: '请输入指派用户ID', trigger: 'blur' }
                ],
                foreignOptionId: [
                    { required: true, message: '请选择外办选项ID', trigger: 'change' }
                ]
            },
            requiredFieldsItems: [
                { name: "文本描述", id: 1 },
                { name: "相关文件", id: 2 }
            ],
            initResp: {
                groupList: [],
                taskLv: [],
                foreignLv: [],
                users: [],
            },
            loading: true,
        }
    },
    mounted() {

        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;

        //获取$router中的query
        this.form.id = this.$route.query.id;
        if (this.$route.query.edit) {
            this.getDetail();
        } else {
            this.init();
        }
    },
    methods: {
        // 计算两个时间之间的小时数
        calculateHours(startTime, endTime) {
            if (!startTime || !endTime) return 0;

            const start = new Date(startTime);
            const end = new Date(endTime);

            // 计算时间差（毫秒）
            const diff = end - start;

            // 转换为小时数
            const hours = diff / (1000 * 60 * 60);

            // 保留一位小数
            return Math.round(hours * 10) / 10;
        },

        // 当时间范围改变时更新默认小时数
        onTimeRangeChange(index) {
            const task = this.mainTasks[index];
            if (task.timeRange && task.timeRange.length === 2) {
                task.durationHours = this.calcWorkHoursExact(task.timeRange[0], task.timeRange[1]);
            } else {
                task.durationHours = 0;
            }
        },

        addTask() {
            this.mainTasks.push({
                "id": 0,
                "name": "",
                "priorityId": 1456,
                "isUrgent": false,
                "assignedUserId": this.form.assignedUserId || '',
                "durationHours": 0,
                "workOrderId": 0,
                "sort": this.mainTasks.length + 1,
                "timeRange": [],
                "requiredFieldsValue": []
            });
        },
        insertTaskAbove(index) {
            // 在指定位置上方插入新行
            this.mainTasks.splice(index, 0, {
                "id": 0,
                "name": "",
                "priorityId": 1456,
                "isUrgent": false,
                "assignedUserId": this.form.assignedUserId || '',
                "durationHours": 0,
                "workOrderId": 0,
                "sort": this.mainTasks.length + 1,
                "timeRange": [],
                "requiredFieldsValue": []
            });
        },
        insertTaskBelow(index) {
            // 在指定位置下方插入新行
            this.mainTasks.splice(index + 1, 0, {
                "id": 0,
                "name": "",
                "priorityId": 1456,
                "isUrgent": false,
                "assignedUserId": this.form.assignedUserId || '',
                "durationHours": 0,
                "workOrderId": 0,
                "sort": this.mainTasks.length + 1,
                "timeRange": [],
                "requiredFieldsValue": []
            });
        },
        deleteTask(index) {
            this.mainTasks.splice(index, 1);
        },
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.save();
                } else {
                    // 表单验证失败
                    this.$message({
                        message: '请检查填写内容',
                        type: 'warning'
                    });
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.form.resetFields();
            this.$router.back();
        },
        /**
         * 计算两个时间之间的工作小时数
         * 工作时间：周一至周五，上午9:00-12:00，下午13:30-18:00
         * @param {string} startStr "yyyy-mm-dd HH:mm"
         * @param {string} endStr "yyyy-mm-dd HH:mm"
         * @returns {number} 工作小时数
         */
        calcWorkHoursExact(startStr, endStr) {
            console.log(startStr, endStr);
            const start = new Date(startStr);
            const end = new Date(endStr);
            if (end <= start) return 0;

            const workPeriods = [
                { start: 9 * 60, end: 12 * 60 },    // 上午 9:00-12:00
                { start: 13.5 * 60, end: 18 * 60 }  // 下午 13:30-18:00
            ];

            let totalMinutes = 0;
            let current = new Date(start);

            while (current < end) {
                const day = current.getDay();
                if (day >= 1 && day <= 5) { // 工作日
                    for (const period of workPeriods) {
                        const periodStart = new Date(current);
                        periodStart.setHours(Math.floor(period.start / 60), period.start % 60, 0, 0);

                        const periodEnd = new Date(current);
                        periodEnd.setHours(Math.floor(period.end / 60), period.end % 60, 0, 0);

                        // 每天的有效区间
                        const effectiveStart = periodStart > current ? periodStart : current;
                        const effectiveEnd = periodEnd < end ? periodEnd : end;

                        if (effectiveEnd > effectiveStart) {
                            totalMinutes += (effectiveEnd - effectiveStart) / 60000;
                        }
                    }
                }
                // 下一天
                current.setDate(current.getDate() + 1);
                current.setHours(0, 0, 0, 0);
            }

            return (totalMinutes / 60).toFixed(2);

        },
        init() {
            this.$axios({
                method: 'post',
                url: '/api/Task/TaskInit',
                data: {
                    typeId: 1453,
                }
            }).then(response => {
                // 处理响应数据
                if (response.data.code == 200) {
                    this.initResp = response.data.data;
                    var maintasks = response.data.data.defaultTask;
                    maintasks.forEach(item => {
                        item.timeRange = [item.startTime, item.endTime];
                        item.requiredFieldsValue = [];
                    })
                    this.mainTasks = maintasks;
                    this.form.startTime = response.data.data.startTime;
                    console.log(this.mainTasks);
                } else {
                    this.$message({
                        message: response.data.msg,
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
            }).finally(() => {
                this.loading = false;
            });
        },
        handleCheckedCitiesChange(val) {
            console.log(val);
        },
        save() {
            var tasks = this.mainTasks;
            var i = 1;
            // 将forEach改为for循环
            for (let j = 0; j < tasks.length; j++) {
                const item = tasks[j];
                item.startTime = item.timeRange[0];
                item.endTime = item.timeRange[1];
                item.sort = i;
                i = i + 1;
                if (!item.name) {
                    this.$message({
                        message: '请填写任务名称',
                        type: 'warning'
                    });
                    return false;
                }
                if (!item.assignedUserId) {
                    this.$message({
                        message: '请选择任务负责人',
                        type: 'warning'
                    });
                    return false;
                }
                if (!item.timeRange[0] || !item.timeRange[1]) {
                    this.$message({
                        message: '请选择任务时间',
                        type: 'warning'
                    });
                    return false;
                }
            }

            var form = this.form;
            form.createUserId = this.userId;
            form.typeId = this.typeId;
            form.tasks = tasks;

            this.$axios({
                method: 'post',
                url: '/api/Task/TaskOperation',
                data: form
            }).then(response => {
                // 处理响应数据
                if (response.data.code == 200) {
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    });
                    this.$router.back();
                } else {
                    this.$message({
                        message: response.data.msg,
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
            });
        },
        userChange() {
            this.mainTasks.forEach(item => {
                item.assignedUserId = this.form.assignedUserId;
            })
        },
        getDetail() {
            this.$axios({
                method: 'post',
                url: '/api/Task/TaskDetail',
                data: {
                    id: this.form.id
                }
            }).then(response => {
                // 处理响应数据
                if (response.data.code == 200) {
                    this.initResp = response.data.data;
                    var maintasks = response.data.data.workTask;
                    maintasks.forEach(item => {
                        item.timeRange = [item.startTime, item.endTime];
                        item.requiredFieldsValue = [];
                    })
                    this.mainTasks = maintasks;
                    this.form = response.data.data.workOrder;
                } else {
                    this.$message({
                        message: response.data.msg,
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
            }).finally(() => {
                this.loading = false;
            });
        },
    }
}
</script>

<style scoped>
.form_center {
    max-width: 100%;
    /* 限制最大宽度 */
    width: 100%;
    margin: 20px auto;
    padding: 20px;
    box-sizing: border-box;
}
</style>