<template>
    <div>
        <div id="DepartProcessListConter">
            <!-- 选项卡 -->
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane v-for="item in switchList" :label="item.name" :key="item.id" :name="item.name">
                    <div v-if="item.id == 1">
                        <div style="padding: 10px;display:flex">
                            <div style="flex: 1;">
                                <!-- <el-input placeholder="操作人" v-model="searchText" clearable
                                    style="width: 200px;display: inline-block;"></el-input> -->
                                <el-input placeholder="流程名称" v-model="loadData.search_Name" clearable
                                    style="width: 200px;display: inline-block;"></el-input>
                                <el-button type="primary" @click="Search">筛选</el-button>
                                <el-checkbox style="padding: 10px;" @change="lvSort">加急排序</el-checkbox>
                            </div>
                            <div style="flex: 1; text-align: right;">
                                <el-button type="primary" @click="add">新增</el-button>
                            </div>
                        </div>
                        <el-table class="table_list" border :data="tableData" style="width: 100%" :row-key="expandid" :expand-row-keys="expandRows" @expand-change="expandRowschande">
                            <el-table-column type="expand">
                                <template slot-scope="props">
                                    <div style="padding: 5px 20px;">
                                        <!-- <div>
                                            <el-steps :active="props.row.stepInfo.active" align-center>
                                                <el-step v-for="stepItem in props.row.stepInfo.steps"
                                                    :key="stepItem.name" icon="el-icon-edit">
                                                    <template slot="icon">
                                                        <div class="step_icon">
                                                            {{ stepItem.name }}
                                                        </div>
                                                    </template>
</el-step>
</el-steps>
</div>
<div v-if="props.row.stepInfo.extraStep.length > 0">
    <div style="padding: 5px;">
        额外任务
    </div>
    <el-steps active="1" space="10%" align-center>
        <el-step v-for="stepItem in props.row.stepInfo.extraStep" :key="stepItem.name" icon="el-icon-edit">
            <template slot="icon">
                                                        <div class="step_icon">
                                                            {{ stepItem.name }}
                                                        </div>
                                                    </template>
        </el-step>
    </el-steps>
</div> -->
                                        <div class="toppx" style="display: flex;flex-wrap: wrap;">
                                            <div class="step_icon">主要任务：</div>
                                            <div v-for="(stepItem, index) in props.row.stepInfo.steps" :key="index">
                                                <div
                                                    :style="{ 'color': index < props.row.stepInfo.active - 1 ? '#67c23a' : props.row.stepInfo.active - 1 == index ? 'black' : '#c0c4cc' }">
                                                    <!-- props.row.stepInfo.active - 1 == index -->
                                                    <span class="step_icon"
                                                        @click="showdialog(true, stepItem.id, props.row.id, props.row.isReview, props.row.stepInfo.active - 1 == index,props.row.stepInfo.active,index)">
                                                        {{
                                                            stepItem.name
                                                        }}
                                                    </span>
                                                    <span v-if="props.row.stepInfo.steps.length - 1 != index"
                                                        style="padding:0px 10px;margin:0px 5px; display: inline-block; width: 20px; height: 2px; background-color: currentColor; vertical-align: middle;">
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        <div v-if="props.row.stepInfo.extraStep.length > 0">
                                            <br />
                                            <div class="toppx" style="display: flex;flex-wrap: wrap;">
                                                <div class="step_icon">额外任务：</div>
                                                <div v-for="(stepItem, index) in props.row.stepInfo.extraStep" :key="index">
                                                    <div
                                                        :style="{ 'color': stepItem.approved == 1 ? '#67c23a' : 'black' }">
                                                        <span
                                                            @click="showdialog(true, stepItem.id, props.row.id, props.row.isReview, props.row.stepInfo.active - 1 == index)"
                                                            class="step_icon"> {{ stepItem.name }}</span>
                                                        <span v-if="props.row.stepInfo.extraStep.length - 1 != index"
                                                            style="padding:0px 10px;margin:0px 5px; display: inline-block; width: 20px; height: 2px; background-color: currentColor; vertical-align: middle;">
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="工单名称" prop="taskName">
                            </el-table-column>
                            <el-table-column label="工单开始时间" prop="startTime">
                            </el-table-column>
                            <el-table-column label="加急任务数量" prop="urgentCount">
                            </el-table-column>
                            <el-table-column label="所属团组" prop="team">
                            </el-table-column>
                            <el-table-column label="指派给谁" prop="assignee">
                            </el-table-column>
                            <el-table-column label="外办选项" prop="externalOption">
                            </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.isReview == 1">
                                        <el-button type="primary" size="mini"
                                            @click="handleEdit(scope.row)">编辑</el-button>
                                        <el-button type="danger" size="mini"
                                            @click="DeleteWorkOrder(scope.row.id)">删除</el-button>
                                    </div>
                                    <div v-else>
                                        <el-button type="primary" size="mini"
                                            @click="viewDetails(scope.row)">查看详情</el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- 分页 -->
                        <div style="text-align: center;padding: 20px 0;">
                            <el-pagination :total="pagination.total" :page-size="pagination.pageSize"
                                :current-page="pagination.pageIndex" :page-sizes="[10, 20, 5, 8]"
                                @current-change="handleCurrentChange" @size-change="handleSizeChange">
                            </el-pagination>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <div id="dialog">
            <el-dialog title="回执信息" :visible.sync="dialogVisible" width="30%">
                <el-card class="form-card" v-for="item in historyForm" :key="item.id">
                    <div style="margin: 0px auto; width: 90%;">
                        <el-form :model="item" label-width="130px">
                            <h4>
                                审核状态:&nbsp;&nbsp;<span v-if="item.isApproved == 1" style="color: #67C23A;">已审核</span>
                                <span v-else-if="item.isApproved == 0" style="color: #E6A23C;">未审核</span>
                                <span v-else style="color: #F56C6C;">已驳回</span>
                            </h4>
                            <el-form-item label="是否已完成该任务？">
                                <el-radio-group v-model="item.isCompleted" disabled>
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="相关内容提交：">
                                <div class="over_input">
                                    <el-input width="70%" type="textarea" v-model="item.content" disabled>

                                    </el-input>
                                </div>
                            </el-form-item>
                            <el-form-item label="驳回原因：" v-if="item.rejectReason">
                                <div class="over_input">
                                    <el-input width="70%" type="textarea" v-model="item.rejectReason" disabled>

                                    </el-input>
                                </div>
                            </el-form-item>
                            <!-- <el-form-item label="特殊说明："  v-if="isReview">
                                <div class="over_input">
                                    <el-input width="70%" type="textarea" v-model="item.remark">
                                    </el-input>
                                </div>
                            </el-form-item> -->
                            <div v-if="item.files.length > 0">
                                <h4>相关文件</h4>
                                <div v-for="(file, index) in item.files" :key="index" style="display: flex;text-align: center;">
                                    <div style="flex: 1;">
                                        {{ file.fileName }}
                                    </div>
                                    <div style="flex: 1;">
                                        <a :href="file.url" target="_blank">下载</a>
                                    </div>
                                </div> 
                            </div>
                        </el-form>
                    </div>
                    <div v-if="isReview && item.isApproved == 0"
                        style="text-align: center;padding: 12px 0; display:flex">
                        <div style="flex: 1;">
                            <el-button type="primary" size="mini" @click="handleApproval(item)">通过</el-button>
                        </div>
                        <!-- <div style="flex: 1;">
                            <el-button type="primary" size="mini" @click="SetWorkTaskReceiptRemark(item)">保存备注</el-button>
                        </div> -->
                        <div style="flex: 1;">
                            <el-button type="danger" size="mini" @click="handleReject(item)">驳回</el-button>
                        </div>
                    </div>
                </el-card>
                <div style="text-align: center;" v-if="historyForm.length == 0">
                    <h4>暂无历史提交信息</h4>
                </div>
                <el-card class="form-card" v-if="!isReview">
                    <div style="margin: 0px auto; width: 90%;">
                        <el-form ref="form" :model="form">
                            <el-form-item label="是否已完成该任务？">
                                <el-radio-group v-model="form.isCompleted">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="相关内容提交：">
                                <div class="over_input">
                                    <el-input width="70%" type="textarea" v-model="form.content">

                                    </el-input>
                                </div>
                            </el-form-item>
                            <!-- 修改文件上传组件 -->
                            <el-form-item label="相关文件上传：">
                                <el-upload class="avatar-uploader" action="#" :multiple="true" :show-file-list="true"
                                    :http-request="handleFileUpload" :on-change="handleFileChange"
                                    :file-list="form.fileList">
                                    <el-button size="small" type="primary">点击选择文件</el-button>
                                    <!-- <div slot="tip" class="el-upload__tip">可选择多个文件</div> -->
                                </el-upload>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
                <span slot="footer" class="dialog-footer">
                    <div>
                        <el-button type="primary" v-if="isReview" @click="SubmitWorkTaskNotRecord">无记录通过</el-button>
                    </div>
                    <div>
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submitForm(isReview)">确 定</el-button>
                    </div>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            token: '',
            userId: '',
            tableData: [],
            activeName: '商邀任务',
            switchList: [
                {
                    id: 1,
                    name: '商邀任务'
                },
                {
                    id: 2,
                    name: '测试任务'
                }
            ],
            dialogVisible: false,
            form: {
                isCompleted: 1,
                content: '',
                fileList: [],
                workOrderId: 0,
                workTaskId: 0,
            },
            loadData: {
                "userId": 0,
                "typeId": 1453,
                "search_Name": "",
                "seach_StartTime": "",
                "seach_EndTime": ""
            },
            pagination: {
                total: 0,
                pageSize: 10,
                pageIndex: 1,
            },
            historyForm: [],
            isReview: false,
            isSubmit: true,
            expandRows: [],
        }
    },
    methods: {
        expandRowschande(row, expandedRows){
            this.expandRows=[];
            for (let index = 0; index < expandedRows.length; index++) {
                this.expandRows.push(expandedRows[index].id)
            }
        },
        expandid(row){
           return row.id
        },
        Search() {
            this.load();
        },
        handleClick(tab, event) {
            console.log(tab, event);
        },
        add() {
            this.$router.push({
                path: '/home/DepartProcessAdd',
            })
        },

        // 新增文件处理方法
        handleFileChange(file, fileList) {
            this.form.fileList = fileList;
        },
        handleFileUpload(option) {
            const { file } = option;
            return new Promise((resolve) => resolve());
        },
        //无记录通过
        SubmitWorkTaskNotRecord(){
            this.$axios({
                method: 'post',
                url: '/api/Task/SubmitWorkTaskNotRecord',
                data: {
                    userId:this.userId,
                    workOrderId:this.form.workOrderId,
                    workTaskId:this.form.workTaskId,
                },
            }).then(response => {
                if (response.data.code == 200) {
                    this.$message({
                        message: '任务通过',
                        type: 'success'
                    });
                } else {
                    this.$message({
                        message: response.data.msg || '任务通过失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            }).finally(() => {
                this.dialogVisible = false;
                // 重置表单
                this.form = {
                    isCompleted: 1,
                    content: '',
                    fileList: [],
                    workOrderId: 0,
                    workTaskId: 0,
                }
                this.load();
            });
        },
        // 提交表单和文件
        submitForm() {

            if (this.isReview) {
                this.dialogVisible = false;
                return;
            }

            const formData = new FormData();
            formData.append('isCompleted', this.form.isCompleted);
            formData.append('content', this.form.content);
            formData.append('workOrderId', this.form.workOrderId);
            formData.append('workTaskId', this.form.workTaskId);
            formData.append('userId', this.userId);
            this.form.fileList.forEach(fileObj => {
                if (fileObj.raw) {
                    formData.append('files', fileObj.raw);
                }
            });

            this.$axios({
                method: 'post',
                url: '/api/Task/SubmitWorkTaskReceipt',
                data: formData,
            }).then(response => {
                if (response.data.code == 200) {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });
                } else {
                    this.$message({
                        message: response.data.msg || '添加失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            }).finally(() => {
                this.dialogVisible = false;
                // 重置表单
                this.form = {
                    isCompleted: 1,
                    content: '',
                    fileList: [],
                    workOrderId: 0,
                    workTaskId: 0,
                }
            });
        },
        load() {
            this.loadData.userId = this.userId;
            if (!this.loadData.isLv) {
                this.loadData.isLv = 0;
            }
            console.log(this.loadData, "this.loadData");
            this.$axios({
                method: 'post',
                url: '/api/Task/GetTaskList',
                data: {
                    ...this.loadData,
                    pageSize: this.pagination.pageSize,
                    pageIndex: this.pagination.pageIndex,
                },
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (response.data.code == 200) {
                    this.tableData = response.data.data;
                    this.pagination.total = response.data.count;
                } else {
                    this.$message({
                        message: response.data.msg || '获取任务列表失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            });
        },
        handleEdit(row) {
            this.$router.push({
                path: '/home/DepartProcessAdd',
                query: {
                    id: row.id,  // 假设row对象有id字段
                    edit: true   // 标识是编辑模式
                }
            });
        },
        //保存备注
        SetWorkTaskReceiptRemark(item) {              
            var url = "/api/Task/SetWorkTaskReceiptRemark"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    receiptId: item.id,
                    remark: item.remark,
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    
                }else {
                    that.$message({
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        handleCurrentChange(val) {
            this.pagination.pageIndex = val;
            this.load(); // 重新加载数据
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val;
            this.pagination.pageIndex = 1; // 重置到第一页
            this.load(); // 重新加载数据
        },
        showdialog(flag, workTaskId, workOrderId, isReview, isSubmit,active,indexs) {
            if (active<indexs+1&&active!==undefined&&indexs!==undefined) {
                return;
            }
            this.dialogVisible = flag;
            this.form.workTaskId = workTaskId;
            this.form.workOrderId = workOrderId;
            this.isReview = isReview;
            this.isSubmit = isSubmit;
            console.log(isReview, "isReview");
            this.GethistorySubmit();
        },
        GethistorySubmit() {
            var data = {
                taskId: this.form.workTaskId,
                orderId: this.form.workOrderId,
            };
            console.log(data);
            this.$axios({
                method: 'post',
                url: '/api/Task/GetWorkTaskReceipt',
                data: data,
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (response.data.code == 200) {
                    this.historyForm = response.data.data;
                } else {
                    this.$message({
                        message: response.data.msg || '获取任务列表失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            });
        },
        DeleteWorkOrder(workOrderId) {
            var data = {
                "workOrderId": 0,
                "userId": 0
            };
            data.userId = this.userId;
            data.workOrderId = workOrderId;
            this.$axios({
                method: 'post',
                url: '/api/Task/SoftDeleteWorkOrder',
                data: data,
            }).then(response => {
                if (response.data.code == 200) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    // 重新加载数据
                    this.load();
                } else {
                    this.$message({
                        message: response.data.msg || '删除失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            });
        },
        handleReject(item) {
            // 添加一个文本域用于输入驳回原因
            this.$prompt('请输入驳回原因', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /.+/, // 要求输入非空
                inputErrorMessage: '驳回原因不能为空',
                inputType: 'textarea', // 改为文本域
                inputValidator: (value) => {
                    if (!value || value.trim() === '') {
                        return '驳回原因不能为空';
                    }
                    return true;
                }
            }).then(({ value }) => {
                //console.log('驳回原因:', value);
                this.AuditWorkTaskReceipt(item.id, -1, value);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消驳回'
                });
            });
        },
        handleApproval(item) {
            //一个简单的确定弹窗
            this.$confirm('确定通过吗？,通过后将开始下一个任务', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 用户点击确定后执行的逻辑
                console.log('通过');
                this.AuditWorkTaskReceipt(item.id, 1, '');
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消通过'
                });
            });
        },
        AuditWorkTaskReceipt(receiptId, approve, rejectReason) {
            var data = {
                "receiptId": receiptId,
                "approverId": this.userId,
                "approve": approve,
                "rejectReason": rejectReason
            };
            this.$axios({
                method: 'post',
                url: '/api/Task/AuditWorkTaskReceipt',
                data: data,
            }).then(response => {
                if (response.data.code == 200) {
                    this.$message({
                        message: '审核成功',
                        type: 'success'
                    });
                    var history = this.historyForm.filter(item => item.id == receiptId);
                    history[0].isApproved = approve;
                    history[0].rejectReason = rejectReason;

                    // 重新加载数据
                    this.load();
                } else {
                    this.$message({
                        message: response.data.msg || '审核失败',
                        type: 'warning'
                    });
                }
            }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message({
                    message: '请求失败，请检查网络连接',
                    type: 'error'
                });
            });
        },
        lvSort(value) {
            if (value) {
                this.loadData.isLv = 1;
            } else {
                this.loadData.isLv = 0;
            }
            this.load();
        },
        viewDetails(row) {
            this.$router.push({
                path: '/home/DepartProcessAdd',
                query: {
                    id: row.id,
                    edit: false,
                    view: true
                }
            });
        }
    },
    mounted() {
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.load();
    }
}

</script>

<style>
#DepartProcessListConter {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    min-height: 830px;
}

.step_icon {
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: white;
    font-size: 12px;
    font-family: "\5FAE\8F6F\96C5\9ED1";
}

#DepartProcessListConter .el-table .el-table__expanded-cell[class*=cell] {
    background-color: #fff;
}

.step_icon:hover {
    /* ransform: scale(1.1); */
}

.czbtn {
    width: 70px;
}

.form-card {
    margin: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.over_input .el-textarea {
    width: 100%;
}

.toppx>div {
    margin-top: 5px;
}
.dialog-footer{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>