<template>
    <div v-loading.fullscreen.lock="fullscreenLoading">
        <div class="lncomingbill-all">
            <div class="lncomingbill-head">
                <div class="lncomingbill-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="lncomingbill-head-li">
                    <el-button @click="Saveition()" type="primary">保存数据</el-button>
                    <el-select style="width:200px" v-model="valuelist" placeholder="请选择">
                        <el-option v-for="item in DownloadInitlist" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-button @click="PostReceivablesFeilDownload" type="primary">下 载</el-button>
                </div>
            </div>
            <div class="lncomingbill-info">
                <div class="lncomingbill-info-li">
                    <label>团 号：</label>
                    <span>{{ groupInfo.tourCode }}</span>
                </div>
                <div class="lncomingbill-info-li">
                    <label>客 户：</label>
                    <span>{{ groupInfo.clientName }}</span>
                </div>
                <div class="lncomingbill-info-li">
                    <label>出访国家：</label>
                    <span>{{ groupInfo.visitCountry | filter_city }}</span>
                </div>
                <div class="lncomingbill-info-li">
                    <label>起止日期：</label>
                    <span>{{ filter_time(groupInfo.visitStartDate)}}~{{ filter_time(groupInfo.visitEndDate) }}</span>
                </div>
                <div class="lncomingbill-info-li">
                    <label>天数/人数：</label>
                    <span>{{ groupInfo.visitDays }}天/{{ groupInfo.visitPNumber }}人</span>
                </div>
            </div>
            <div class="lncomingbill-checked">
                <div class="checked-label">收款账单</div>
                <div>
                    <el-button @click="PostReceivablesImportFee" type="primary">导入三公费用</el-button>
                    <el-button @click="addition" type="primary">添加一行</el-button>
                </div>
            </div>
            <div class="lncomingbill-form">
                <el-table :border="true" ref="multipleTable" :data="tableData" style="width: 100%;"
                    :row-style="TableRowStyle">
                    <el-table-column label="增加方式" width="150">
                        <template slot-scope="scope">
                            <el-select filterable v-model="scope.row.addingWay">
                                <el-option label="实际报价" :value=2></el-option>
                                <el-option label="账单模块" :value=0></el-option>
                                <el-option label="成本预算模块" :value=1></el-option>
                                <el-option label="超支费用" :value=3></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="时间" width="210">
                        <template slot-scope="scope">
                            <el-date-picker value-format="yyyy-MM-dd" style="width: 100%;"
                                v-model="scope.row.createTime" type="datetime" format="yyyy-MM-dd HH:mm"
                                placeholder="选择日期">
                            </el-date-picker>
                        </template>
                    </el-table-column>
                    <el-table-column label="单位或其他名称" width="240">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.priceName"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="单 价" width="140">
                        <template slot-scope="scope">
                            <el-input-number :controls="false" :precision="2" class="editNum"
                                v-model="scope.row.price"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="数 量" width="80">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.count"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="单 位" width="90">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.unit"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="币 种" width="100">
                        <template slot-scope="scope">
                            <el-select filterable 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="100">
                        <template slot-scope="scope">
                            <el-input-number :controls="false" :precision="2"
                                v-model="scope.row.rate"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="应收金额" width="200">
                        <template slot-scope="scope">
                            <div class="sub-box">
                                {{ scope.row.itemSumPrice=(scope.row.price * scope.row.count *
                                scope.row.rate).toFixed(2) }}
                            </div>
                        </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="name" label="操 作" width="140">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.status == 1" size="mini" type="success" title="已确认">
                                <i class="el-icon-check"></i></el-button>
                            <el-button
                                v-if="scope.row.addingModeName == '实际报价' && scope.row.status != 1 ? jurisdiction : false"
                                size="mini" type="primary" @click="PostReceivablesAudit(scope.row.id)">
                                <i class="el-icon-check"></i></el-button>
                            <el-button size="mini" type="danger"
                                @click="handleDelete(scope.$index, scope.row, tableData)"><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: "",
            valuelist: '',
            options: [],
            filteredOptions: [],
            searchMode: 'character', // 'character': 字符匹配, 'fuzzy': 模糊匹配
            DownloadInitlist: [],
            tableData: [
                // {
                //     addingModeName:"",
                //     createTime:"",
                //     priceName:"",
                //     price:"",
                //     count:"",
                //     unit:"",
                //     currency:"",
                //     rate:"",
                //     itemSumPrice:"",
                //     remark:"",
                // }
            ],
            currencyoptions: [],
            groupInfo: {},
            fullscreenLoading: false,
            jurisdiction: false
        }
    },
    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);
            });
        },


        filter_time(value) {
            if (value!=undefined) {
                return value.split(' ')[0];
            }
        },
        //获取团组
        GetForeignReceivablesDataSources() {
            var url = "/api/Financial/PostGroupReceivablesDataSource"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userid
                },
                data: {
                    currUserId: that.userid
                }
            }).then(function (res) {
                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.PostGroupReceivablesInfoByDiId();
            })
        },
        //获取收款账单详情
        PostGroupReceivablesInfoByDiId() {
            this.tableData = [];
            this.fullscreenLoading = true;
            var url = "/api/Financial/PostGroupReceivablesInfoByDiId"
            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)
                if (res.data.code) {
                    that.tableData = res.data.data.groupCollectionStatementData;
                    that.groupInfo = res.data.data.groupInfo;
                    setTimeout(function () { that.fullscreenLoading = false; }, 0)
                } else {
                    setTimeout(function () { that.fullscreenLoading = false; }, 0)
                }

            })
        },
        //切换团组
        changediid() {
            this.PostGroupReceivablesInfoByDiId()
        },
        PostReceivablesFeilDownload() {
            var url = "/api/Financial/PostReceivablesFeilDownload"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    diId: that.value,
                    fileType: that.valuelist,
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    console.log(res)
                    window.open(res.data.data.url)
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //审核
        PostReceivablesAudit(val) {
            var url = "/api/Financial/PostReceivablesAudit"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data: {
                    portType: 1,
                    userId: that.userid,
                    id: val,
                    status: 1,
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    that.PostGroupReceivablesInfoByDiId();
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //获取公司账单列表
        PostReceivablesFeilDownloadInit() {
            var url = "/api/Financial/PostReceivablesFeilDownloadInit"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    // that.$message({
                    //     message: res.data.msg,
                    //     type: 'success'
                    // });
                    console.log(res)
                    that.DownloadInitlist = res.data.data;
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //添加一行
        addition() {
            var newinif = {
                id: 0,
                createTime: new Date(),//时间
                priceName: "",//费用名称
                price: 0,//费用
                count: 0,//数量
                unit: '',//单位
                itemSumPrice: 0,// 单项总和
                rate: 1,// 汇率
                currency: 836,//币种
                addingWay: 2,//添加方式
                remark: ""//备注
            }
            this.tableData.push(newinif)
            // var url = "/api/Financial/PostReceivablesSave"
            // var that = this
            // this.$axios({
            //     method: 'post',
            //     url: url,
            //     headers: {
            //         Authorization: 'Bearer ' + this.token
            //     },
            //     data:{
            //         portType: 1,
            //         diId: that.value,
            //         userId:that.userid,
            //         foreignReceivablesInfos:[newinif]
            //     }
            // }).then(function (res) {
            //     if(res.data.code==200){
            //         that.$message({
            //             message: res.data.msg,
            //             type: 'success'
            //         });
            //         console.log(res)
            //         that.PostGroupReceivablesInfoByDiId()
            //     }else{
            //         that.$message.error('添加失败!数据异常');
            //     }
            // })
        },
        //对外收款账单删除
        handleDelete(index, row, rows) {
            this.$confirm('此操作将删除此条数据，是否确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log(index, row, rows)
                if (row.id == 0) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    rows.splice(index, 1);
                    return
                }
                var url = "/api/Financial/PostGroupReceivablesDel"
                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);
                    }
                })
            })
        },
        //导入三公费用
        PostReceivablesImportFee() {
            this.fullscreenLoading = true;
            var url = "/api/Financial/PostReceivablesImportFee?groupId=" + this.value
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.fullscreenLoading = false;
                    let dataarr = res.data.data;
                    for (let i = 0; i < dataarr.length; i++) {
                        that.tableData.push(dataarr[i]);
                    }
                } else {
                    that.fullscreenLoading = false;
                    that.$message.error(res.data.msg);
                }
            })
        },
        //保存收款单
        Saveition() {
            console.log(this.tableData)
            //提取参数
            var arrnew = this.tableData.map((item, index) => {
                return Object.assign({}, {
                    'id': item.id,
                    'priceName': item.priceName,
                    'price': item.price,
                    'count': item.count,
                    'unit': item.unit,
                    'itemSumPrice': item.itemSumPrice,
                    'rate': item.rate,
                    'currency': item.currency,
                    'addingWay': item.addingWay,
                    'remark': item.remark,
                })
            })
            console.log(arrnew)
            var Savedecides = true
            for (let g = 0; g < arrnew.length; g++) {
                if (arrnew[g].currency == "" || arrnew[g].itemSumPrice == "" || arrnew[g].priceName == "" || arrnew[g].unit == "") {
                    Savedecides = false
                    break
                }
            }
            if (Savedecides == true) {
                var url = "/api/Financial/PostReceivablesSave"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                    data: {
                        portType: 1,
                        diId: that.value,
                        userId: that.userid,
                        foreignReceivablesInfos: arrnew
                    }
                }).then(function (res) {
                    if (res.data.code == 200) {
                        that.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                        that.PostGroupReceivablesInfoByDiId();
                    } else {
                        that.$message.error('保存失败!数据异常');
                    }
                })
            } else {
                this.$message.error('请检查数据是否完整！');
            }
        },
        //判断id
        judgmentId(val) {
            if (val == 233 || val == 21 || val == 22) {
                return true
            }
        },
        //不同换色
        TableRowStyle({ row, rowIndex }) {
            // 注意，这里返回的是一个对象
            let rowBackground = {};
            if (row.status == 1) {
                rowBackground.background = "#f0f9ff";
                return rowBackground;
            } else {
                rowBackground.background = "#FFFFFF";
                return rowBackground;
            }
        },
    },
    created() {
        this.PostReceivablesFeilDownloadInit();
    },
    mounted() {
        this.userid = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.jurisdiction = this.judgmentId(this.userid)
        this.GetForeignReceivablesDataSources();

    },
    filters: {
        
        filter_city(value) {
            return value
        }
    },
}
</script>
<style>
.lncomingbill-all {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    height: 100%;
    min-height: 830px;
}

.lncomingbill-all .sub-box {
    -ms-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
    font-family: "微软雅黑";
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    width: 100%;
}

.lncomingbill-head-li label {
    color: #606266;
    font-size: 15px;
    font-weight: 600;
}

.lncomingbill-head {
    display: flex;
    justify-content: space-between;
}

.lncomingbill-info {
    display: flex;
    margin-top: 10px;
}

.lncomingbill-info-li {
    margin-right: 30px;
}

.lncomingbill-info-li label {
    color: #606266;
    font-size: 15px;
    font-weight: 600;
}

.lncomingbill-info-li span {
    color: #606266;
    font-size: 14px;
}

.lncomingbill-all .el-input-number {
    width: 100%;
}

.lncomingbill-checked {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.lncomingbill-form {
    margin-top: 10px;
}
</style>