<template>
    <div class="affairbackward-all" v-loading="affairbackwardloading">
        <div class="affairbackward-hade">
            <el-form style="display: flex;justify-content: space-between;align-items: center;" :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item>
                    <el-select filterable @change="ConferenceProceduresInit" v-model="diid" placeholder="团组名称" style="width: 250px;">
                        <el-option :style="item.hasChildData?'color: #66b1ff;':''" v-for="(item, index) in AuditStatus" :key="index" :label="item.teamName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <div>
                    <el-form-item label="团队名称:">
                        {{ formInline.name }}
                    </el-form-item>
                    <el-form-item label="客户:">
                        {{ formInline.clientName }}
                    </el-form-item>
                    <el-form-item label="出访国家:">
                        {{ formInline.CountriesVisited }}
                    </el-form-item>
                    <el-form-item label="起止日期:">
                        {{ formInline.StartTime }}
                    </el-form-item>
                    <el-form-item label="天数/人数:">
                        {{ formInline.Days }}天 / {{ formInline.Number }}人
                    </el-form-item>
                </div>
                <div>
                    <el-button @click="ConferenceProceduresSave" type="primary">保存</el-button>
                    <el-button @click="ConferenceProceduresFileDown" type="primary">下载</el-button>
                </div>
            </el-form>    
        </div>
        <div style="margin-top: 20px;font-size: 15px;font-weight: 600;color: red;">PS:插入行与删除行并未进行保存操作，需要保存请点击保存按钮！！！</div>
        <el-table :data="tableDatass" :span-method="objectSpanMethod" border style="width: 100%; ">
            <el-table-column prop="title" label="项目" width="180">
                <template slot-scope="scope">
                    <el-input @focus="huodejiaodian(scope.row.title)" @input="titleinput" v-model="scope.row.title" placeholder="请输入内容"></el-input>
                    <el-button style="margin-top: 10px" size="mini" @click="pushxiangmu(scope.row.title)" type="primary">插入项目↓</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="date" label="时间"  width="180">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.dataDetails" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="content" label="内容">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.details" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
             <el-table-column prop="remark" label="操作" width="150">
                <template slot-scope="scope">
                    <el-button style="width:80px;" class="czbtn" size="mini" type="primary" @click="insertTaskAbove(scope.$index,scope.row)">插入行↑</el-button>
                    <br />
                    <el-button style="margin: 10px 0;width:80px;" size="mini" @click="deleterow(scope.$index,scope.row)" type="danger">删 除</el-button>
                    <br />
                    <el-button style="width:80px;" size="mini" @click="insertTaskBelow(scope.$index,scope.row)" type="primary">插入行↓</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
<script>
export default {
    data() {
        return {
            tableData: [],
            tableDatas:[
                {
                    title:'1',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'1',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'2',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'2',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'2',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'3',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'3',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'3',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'3',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
                {
                    title:'4',
                    date:'提前45天',
                    content:'初筛邀请对象，结合客户需求，梳理邀请名单',
                    Remark:'实际根据项目启动时间，倒推时间是否足够'
                },
            ],
            tableDatass:[],
            rowarr:[],
            spanArr: [], // 存储每个项目对应的行数
            position: 0,   // 存储spanArr的索引位置
            diid:'',
            AuditStatus:[],
            formInline: {
                name: '美国团',
                clientName: '张三',
                CountriesVisited: '美国',
                StartTime: '2023-10-01至2023-10-10',
                Days: 10,
                Number: 8,
                Status: '',
            },
            token:'',
            userId:'',
            affairbackwardloading:false,
            porojectname:[],
            porojectindex:[],
            num:0,
        }
    },
    created() {
        // this.getSpanArr();
        // this.flattenData();
    },
    methods:{
        // 将嵌套的数据结构转换为扁平结构
        flattenData() {
            this.tableDatass = [];
            this.tableData.forEach(item => {
                item.itmes.forEach(child => {
                    this.tableDatass.push({
                        id:child.id,
                        title: item.title,
                        dataDetails: child.dataDetails,
                        identification:item.title,
                        details: child.details,
                        remark: child.remark
                    });
                });
            });
        },
        // 将扁平结构转换为嵌套的数据结构
        unflattenData() {
            let result = [];
            let currentTitle = null;
            let currentItem = null;
            this.tableDatass.forEach(row => {
                if (row.title !== currentTitle) {
                    if (currentItem) {
                        result.push(currentItem);
                    }
                    currentTitle =row.title;
                    currentItem = {
                        title: currentTitle,
                        itmes: []
                    };
                }
                currentItem.itmes.push({
                    id:row.id,
                    dataDetails: row.dataDetails,
                    details: row.details,
                    remark: row.remark,
                    identification:row.identification,
                });
            });
            if (currentItem) {
                result.push(currentItem);
            }
            this.tableData = result;
        },
        // 计算每个项目对应的行数
        getSpanArr() {
            this.spanArr = [];
            this.position = 0;
            
            this.tableData.forEach(item => {
                this.spanArr.push(item.itmes.length);
            });
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                let currentRowTitle = row.title;
                let spanCount = 0;
                let pos = 0;

                // 找到当前项目在spanArr中的位置
                for (let i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].title === currentRowTitle) {
                        spanCount = this.spanArr[i];
                        break;
                    }
                    pos += this.spanArr[i];
                }
                // 如果是当前项目的第一个行，返回合并行数
                if (rowIndex === pos) {
                    return {
                        rowspan: spanCount,
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
        //数据初始化
        ConferenceProceduresInit(){
            this.affairbackwardloading=true;
            this.AuditStatus=[];
            var url = "/api/Groups/ConferenceProceduresInit"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer '
                },
                data:{
                    groupId:that.diid==''?0:that.diid,
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.AuditStatus=res.data.data.groupList;
                    if (that.diid==='') {
                        that.diid=res.data.data.groupInfo.id;
                    }
                    that.formInline.name = res.data.data.groupInfo.teamName;
                    that.formInline.clientName = res.data.data.groupInfo.clientName;
                    that.formInline.CountriesVisited = res.data.data.groupInfo.visitCountry;
                    that.formInline.StartTime = res.data.data.groupInfo.visitStartDate.split(' ')[0]+'~'+res.data.data.groupInfo.visitEndDate.split(' ')[0];
                    that.formInline.Days = res.data.data.groupInfo.visitDays;
                    that.formInline.Number = res.data.data.groupInfo.visitPNumber;
                    that.tableData=res.data.data.conferenceProceduresGroupByTitle;
                    that.getSpanArr();
                    that.flattenData(); 
                    that.affairbackwardloading=false;
                }else{
                    that.affairbackwardloading=false;
                    that.$message.error(res.data.msg);
                }
            })
        },
        //插入行
        insertTaskAbove(index,row) {
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].title === row.title) {
                    this.tableData[i].itmes.splice(index - this.position, 0, {
                        "id":0,
                        "dataDetails":"",
                        "details": "",
                        "remark": "",
                    });
                    this.getSpanArr();
                    this.flattenData(); 
                    break;
                }
                this.position += this.spanArr[i];
            }
        },
        //插入行
        insertTaskBelow(index,row) {
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].title === row.title) {
                    this.tableData[i].itmes.splice((index+1) - this.position, 0, {
                        "id":0,
                        "dataDetails":"",
                        "details": "",
                        "remark": "",
                    });
                    this.getSpanArr();
                    this.flattenData(); 
                    break;
                }
                this.position += this.spanArr[i];
            }
        },
        //删除行
        deleterow(index,row) {
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].title === row.title) {
                    this.tableData[i].itmes.splice(index - this.position, 1);
                    this.getSpanArr();
                    this.flattenData(); 
                    break;
                }
                this.position += this.spanArr[i];
            }
        },
        //保存
        ConferenceProceduresSave(){
            this.affairbackwardloading=true;
            this.unflattenData();
            var url = "/api/Groups/ConferenceProceduresSave"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ',
                },
                data:{
                    groupId:that.diid,
                    userId: that.userId,
                    conferenceProceduresSaveItem:that.tableData,
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    that.ConferenceProceduresInit();
                }else{
                    that.$message.error(res.data.msg);
                    that.progressloading=false;
                }
            })
        },
        //下载
        ConferenceProceduresFileDown(){
            // this.unflattenData();
            var url = "/api/Groups/ConferenceProceduresFileDown"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ',
                },
                data:{
                    groupId:that.diid,
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    window.open(res.data.data);
                }else{
                    that.$message.error(res.data.msg);
                }
            })
        },
        //标题输入
        titleinput(val){
            for (let b = 0; b < this.tableDatass.length; b++) {
                if(this.tableDatass[b].identification==this.porojectindex){
                    this.tableDatass[b].title=val;
                }
            }
            this.porojectindex=val;
            // for (let b = 0; b < this.porojectindex.length; b++) {
            //     // this.tableDatass.splice( this.porojectindex,1)
            //     for (let m = 0; m < this.porojectname.length; m++) {
            //         this.porojectname[m].title=val;
            //         this.tableDatass.splice(this.porojectindex[b],1,this.porojectname[m])
            //     }
            // }
            // this.tableDatass=this.porojectname.concat(this.tableDatass);
            this.unflattenData();
            console.log(this.tableData);
            
            this.flattenData();
            this.getSpanArr();
        },
        //插入项目
        pushxiangmu(val){
            this.unflattenData();
            console.log(this.tableData);
            console.log(val);
            this.num++;
            for (let k = 0; k < this.tableData.length; k++) {
                if(this.tableData[k].title==val){
                    this.tableData.splice(k+1, 0, 
                        {
                            title: '新项目'+this.num,
                            itmes: [{
                                id: 0,
                                dataDetails: '',
                                details: '',
                                remark: '',
                                identification: '新项目'+this.num,
                            }]
                        }
                    );
                    this.getSpanArr();
                    this.flattenData(); 
                    break;
                }
            }
            // this.unflattenData();
            // console.log(this.tableData);
            // var obj={
            //     title:'新项目',
            //     itmes:[{
            //         id:0,
            //         dataDetails:'',
            //         details:'',
            //         remark:'',
            //         identification:'新项目',
            //     }]
            // }
            // this.tableData.push(obj);
            // this.flattenData();
            // this.getSpanArr();
        },
        //获得焦点
        huodejiaodian(val){
            this.porojectname=[];
            this.porojectindex=val;
             for (let y = 0; y < this.tableDatass.length; y++) {
                if (this.tableDatass[y].title==val) {
                    this.porojectname.push(this.tableDatass[y])
                    // this.porojectindex.push(y)
                }
            }
        }
    },
    mounted(){
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.ConferenceProceduresInit();
    }
}
</script>
<style>
    .affairbackward-all {
        background-color: #fff;
        padding: 10px;
        box-shadow: 0 0 5px #0005;
        border-radius: 10px;
        min-height: 830px;
        
    }
    .affairbackward-hade .el-form-item{
        margin-bottom: 0;
    }
</style>
  