<template>
    <div>
        <div class="received-all">
            <div class="received-head">
                <div class="received-head-li">
                    <label>团组名称:</label>
                    <el-select style="width:250px" @change="changediid()" v-model="value" filterable :filter-method="advancedFilter" placeholder="请选择">
                        <el-option v-for="item in filteredOptions" :key="item.id" :label="item.groupName" :value="item.id">
                            <span v-if="item.isNull=='false'" style="color:#409EFF">{{ item.groupName }}</span>
                            <span v-else style="color:gray">{{ item.groupName }}</span>
                        </el-option>
                    </el-select>
                    <!-- <el-select style="width: 250px;" @change="changediid()" v-model="value" filterable placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.groupName"
                        :value="item.id">
                        </el-option>
                    </el-select> -->
                </div>
                <div class="received-head-li">
                    <el-button @click="ysSaveition()" type="primary">保存数据</el-button>
                </div>
            </div>
            <div class="received-info">
                <div class="received-info-li">
                    <label>团 号：</label>
                    <span>{{groupInfo.tourCode}}</span>

                </div>
                <div class="received-info-li">
                    <label>客 户：</label>
                    <span>{{groupInfo.clientName}}</span>
                </div>
                <div class="received-info-li">
                    <label>出访国家：</label>
                    <span>{{groupInfo.visitCountry}}</span>
                </div>
                <div class="received-info-li">
                    <label>起止日期：</label>
                    <span>{{groupInfo.visitStartDate|filter_time}}~{{groupInfo.visitEndDate|filter_time}}</span>
                </div>
                <div class="received-info-li">
                    <label>天数/人数：</label>
                    <span>{{groupInfo.visitDays+'天/'+groupInfo.visitPNumber+'人'}}</span>
                </div>
            </div>
            <div class="received-checked">
                <div class="received-checked-label">已收款项</div>
                <el-button size="mini" @click="addUnassignedData()" type="primary">添加一行</el-button>
            </div>
            <div class="received-form">
                <el-table
                :border="true"
                ref="multipleTable"
                :data="UnassignedData"
                tooltip-effect="dark"
                style="width: 100%"
                >
                    <!-- <el-table-column
                    label="付款时间"
                    width="165">
                        <template slot-scope="scope">
                            <el-date-picker
                            style="width: 100%;"
                            v-model="scope.row.sectionTime"
                            type="date"
                            placeholder="选择日期">
                            </el-date-picker>
                           
                        </template>
                    </el-table-column> -->
                    <el-table-column
                        label="付款方信息"
                        >
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.client"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="付款方电话"
                        width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.customerTel"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="已收金额"
                        width="150">
                        <template slot-scope="scope">
                            <el-input-number :controls="false" :precision="2" v-model="scope.row.price"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="到款时间"
                        width="165">
                        <template slot-scope="scope">
                            <el-date-picker
                            style="width: 100%;"
                            v-model="scope.row.sectionTime"
                            type="date"
                            placeholder="选择日期">
                            </el-date-picker>
                            <!-- <el-input v-model="scope.row.customerName"></el-input> -->
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="币种"
                        width="100">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.currency">
                                <el-option
                                        v-for="item in currencyoptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="收款类型"
                        width="140">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.receivablesType">
                                <el-option
                                        v-for="item in typeoptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="备注"
                        width="260">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.remark"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        width="80">
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            type="danger"
                            @click="yshandleDelete(scope.$index, scope.row,UnassignedData)"><i class="el-icon-delete"></i></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            userid:'',
            value:'',
            options:[],
            filteredOptions: [],
            searchMode: 'character', // 'character': 字符匹配, 'fuzzy': 模糊匹配
            currencyoptions:[],
            UnassignedData:[
                // {
                //     id: 0,
                //     sectionTime: "",//费用名称
                //     price: 0,//费用
                //     currency:836,//币种
                //     receivablesType:72,//收款类型
                //     client:'',//收款单位
                //     customerName:'',//收款单位 负责人 姓名
                //     customerTel:'',//收款单位 负责人 电话号码
                //     remark:""//备注
                // }
            ],
            typeoptions:[],
            groupInfo:{
                // clientName:'',
                // id:'',
                // tourCode:'',
                // visitCountry:'',
                // visitDays:'',
                // visitEndDate:'',
                // visitPNumber:'',
                // visitStartDate:'',
            },
        }
    },
    methods:{
        advancedFilter(query) {
            if (!query || query.trim() === '') {
                this.filteredOptions = [...this.options];
                return;
            }

            const trimmedQuery = query.trim();

            if (this.searchMode === 'character') {
                // 字符匹配模式：每个字都必须包含
                this.characterMatchFilter(trimmedQuery);
            } else {
                // 模糊匹配模式（默认的filterable行为）
                this.fuzzyMatchFilter(trimmedQuery);
            }
        },
        /*** 严格的字符匹配 - 每个查询字符都必须出现*/
        characterMatchFilter(query) {
            const queryChars = query.split('').filter(char => char.trim() !== '');

            this.filteredOptions = this.options.filter(item => {
                const groupName = item.groupName || '';
                return queryChars.every(char => groupName.includes(char));
            });
        },
        /*** 模糊匹配 - 包含整个查询字符串即可*/
        fuzzyMatchFilter(query) {
            const lowerQuery = query.toLowerCase();
            this.filteredOptions = this.options.filter(item => {
                const groupName = (item.groupName || '').toLowerCase();
                return groupName.includes(lowerQuery);
            });
        },


        //获取团组
        GetForeignReceivablesDataSources(){
            var url = "/api/Financial/GetForeignReceivablesDataSources"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userid
                },
                data:{
                    currUserId:that.userid
                }
            }).then(function (res) {
                console.log(res)
                if(res.data.code==200){
                    that.options=res.data.data.groupNameData;
                    that.filteredOptions = that.options;
                    that.currencyoptions=res.data.data.currencyData;
                    that.typeoptions=res.data.data.remittanceMethodData;
                    that.value=res.data.data.groupNameData[0].id;
                    that.PostAmountReceived();
                }
            })
        },
        //获取账单详情
        PostAmountReceived(){
            var url = "/api/Financial/PostAmountReceived"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userid
                },
                data:{
                    portType: 1,
                    diId: that.value
                }
            }).then(function (res) {
                console.log(res)
                that.UnassignedData=res.data.data
                that.groupInfo=res.data.data.groupInfo
                that.PostShareGroupInfo();
            })
        },
        //获取团组详情
        PostShareGroupInfo(){
            console.log(this.value)
            var url = "/api/Business/PostShareGroupInfo"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userid
                },
                data:{
                    portType: 1,
                    id: that.value
                }
            }).then(function (res) {
                console.log(res)
                // that.UnassignedData=res.data.data
                that.groupInfo=res.data.data
                console.log(that.groupInfo)
            })
        },
        //切换团组
        changediid(){
            this.PostAmountReceived()
        },
        //已收款项删除
        yshandleDelete(index, row,rows) {
            this.$confirm('此操作将删除此条数据，是否确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if(row.id==0){
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    rows.splice(index, 1);
                    return
                }
                var url = "/api/Financial/PostAmountReceived_Del"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                    data:{
                        userId:that.userid,
                        id:row.id
                    }
                }).then(function (res) {
                    if(res.data.code==200){
                        that.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                        rows.splice(index, 1);
                    }else{
                        that.$message.error(res.data.msg);
                    }
                })
            })
        },
        //添加一行
        addUnassignedData(){
            var newinif={
                id: 0,
                sectionTime: "",//费用名称
                price: 0,//费用
                currency:836,//币种
                receivablesType:72,//收款类型
                client:'',//收款单位
                customerName:'',//收款单位 负责人 姓名
                customerTel:'',//收款单位 负责人 电话号码
                remark:""//备注
            }
            this.UnassignedData.push(newinif)
            // var url = "/api/Financial/PostAmountReceivedAddOrEdit"
            // var that = this
            // this.$axios({
            //     method: 'post',
            //     url: url,
            //     headers: {
            //         Authorization: 'Bearer ' + this.token
            //     },
            //     data:{
            //         portType: 1,
            //         diId: that.value,
            //         userId:that.userid,
            //         _ProceedsReceivedInfos:[newinif]
            //     }
            // }).then(function (res) {
            //     if(res.data.code==200){
            //         that.$message({
            //             message: res.data.msg,
            //             type: 'success'
            //         });
            //         console.log(res)
            //         that.PostAmountReceived()
            //     }else{
            //         that.$message.error('添加失败!数据异常');
            //     }
            // })
        },
        //处理日期
        datetime(val){
            var date=new Date(val);
            var y=date.getFullYear();
            var m=date.getMonth()+1>=10?date.getMonth()+1:'0'+(date.getMonth()+1).toString();
            var d=date.getDate()>=10?date.getDate():'0'+(date.getDate()).toString();
            return y+'-'+m+'-'+d
        },
        //保存已收款项
        ysSaveition(){
            console.log(this.UnassignedData)
            //提取参数
            var arrnew = this.UnassignedData.map((item,index) => {
                return Object.assign({},{
                    'id':item.id,
                    'sectionTime':this.datetime(item.sectionTime),
                    'price':item.price,
                    'currency':item.currency,
                    'receivablesType':item.receivablesType,
                    'client':item.client,
                    'customerName':item.customerName,
                    'customerTel':item.customerTel,
                    'remark':item.remark,
                })
            })
            console.log(arrnew)
            var Savedecides=true
            for(let g=0;g<arrnew.length;g++){
                if(arrnew[g].count==""||arrnew[g].currency==""||arrnew[g].itemSumPrice==""||arrnew[g].price==""||arrnew[g].priceName==""||arrnew[g].rate==""||arrnew[g].unit==""){
                    Savedecides=false
                    break
                }
            }
            if(Savedecides==true){
                var url = "/api/Financial/PostAmountReceivedAddOrEdit"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                    data:{
                        portType: 1,
                        diId: that.value,
                        userId:that.userid,
                        _ProceedsReceivedInfos:arrnew
                    }
                }).then(function (res) {
                    if(res.data.code==200){
                        that.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                        console.log(res)
                        that.PostAmountReceived()
                    }else{
                        that.$message.error('保存失败!数据异常');
                    }
                })
            }else{
                this.$message.error('请检查数据是否完整！');
            }
        },
    },
    mounted(){
        this.userid=JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.GetForeignReceivablesDataSources()
    },
    filters:{
        filter_time(value){
            if(value){
                return value.split(' ')[0];
            }
            return value
            
        },
        filter_city(value){
            return value
        }
    },
}
</script>
<style>
.received-all{
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    height: 100%;
    min-height: 830px;
}
.received-head-li label{
    color: #606266;
    font-size: 15px;
    font-weight: 600;
}
.received-head{
    display: flex;
    justify-content: space-between;
}
.received-info{
    display: flex;
    margin-top: 10px;
}
.received-info-li{
    margin-right: 30px;
}
.received-info-li label{
    color: #606266;
    font-size: 15px;
    font-weight: 600;
}
.received-info-li span{
    color: #606266;
    font-size: 14px;
}
.received-all .el-input-number{
    width: 100%;
}
.received-checked{
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.received-checked-label{
    font-size: 17px;
    
}
.received-form{
    margin-top: 10px;
}
</style>