<template>
    <div class="entryquotation-all" v-loading.fullscreen.lock="entryquotationLoading">
        <div class="entryquotation-head">
            <el-select style="width:300px" @change="EnterExitCostQuoteEntryExitCosts" v-model="value" filterable placeholder="请选择">
                <el-option
                    v-for="item in tameoptions"
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id">
                </el-option>
            </el-select>
            <div>
                <el-button @click="EnterExitCostQuoteOp()" type="primary">保存</el-button>
                <el-button @click="EnterExitCostQuoteExcelExport()" type="primary">导出</el-button>
            </div>
        </div>
        <div class="entryquotation-title">
            <el-input style="width:300px;" v-model="entryquotationname" placeholder="请输入内容"></el-input>
        </div>
        <div class="exchangerate-box">
            <div style="font-size: 17px;font-weight: 600;">汇率：</div>
            <div class="exchangerate-box-li" v-for="(itemrate,index) in options" :key="index">
                <div>{{itemrate.currencyName+'('+itemrate.currencyCode+')：'}}</div>
                <div>
                    <el-input-number 
                    style="width:110px" 
                    size="small" 
                    :precision="4" 
                    :controls="false" 
                    v-model="itemrate.rate" 
                    @change="recalculateAllRates"
                    ></el-input-number>
                </div>
            </div>
        </div>
        <div class="total-box">
            费用总计(CNY)：{{ townum(entryquotationtotal) }}
        </div>
        <div class="entryquotation-form">
            <div class="entryquotation-form-li" v-for="(item, index) in tabledata" :key="index">
                <div v-html="formattedText(item.itemName)" class="entryquotation-form-title"></div>
                <div class="entryquotation-form-content">
                    <div class="entryquotation-form-addbtn">
                        <el-button v-if="!item.isOnlyRemark" size="small" @click="appenditems(item)" type="primary">新增</el-button>
                    </div>
                    <div v-for="(items, subIndex) in item.infos" :key="subIndex">
                        <div v-if="item.isOnlyRemark">
                            <el-input style="width:100%;" autosize type="textarea" :rows="2" v-model="items.remark"></el-input>
                        </div>
                        <div class="entryquotation-content" v-else>
                            <div class="entryquotation-content-box">
                                <label>描述:</label>
                                <el-input style="width:235px" autosize type="textarea" v-model="items.feeName"></el-input>
                            </div>
                            <div class="entryquotation-content-box">
                                <label>单价:</label>
                                <el-input-number style="width:110px" size="small" :precision="2" :controls="false"
                                    v-model="items.unitPrice" @change="calculateSubtotal(items,item)"></el-input-number>
                            </div>
                            <div class="entryquotation-content-box">
                                <label>币种:</label>
                                <el-select style="width:110px" size="small" v-model="items.currency" filterable
                                    placeholder="请选择" @change="calculateSubtotal(items,item)">
                                    <el-option v-for="opt in options" :key="opt.currencyCode" :label="opt.currencyCode"
                                        :value="opt.currencyCode"></el-option>
                                </el-select>
                            </div>
                            <div class="entryquotation-content-box">
                                <label>数量:</label>
                                <el-input-number style="width:110px" size="small" :precision="2" :controls="false"
                                    v-model="items.quantity" @change="calculateSubtotal(items,item)"></el-input-number>
                            </div>
                            <div class="entryquotation-content-box">
                                <label>人数:</label>
                                <el-input-number style="width:110px" size="small" :precision="2" :controls="false"
                                    v-model="items.pplNum" @change="calculateSubtotal(items,item)"></el-input-number>
                            </div>
                            <div class="entryquotation-content-box">
                                <label>小计:</label>
                                <el-input-number style="width:110px" size="small" :precision="2" :controls="false"
                                    v-model="items.totalAmt" disabled></el-input-number>
                            </div>
                            <el-button size="small" type="danger" @click="removeItem(item.infos, subIndex,item)">移除</el-button>
                        </div>
                    </div>
                </div>
                <div class="entryquotation-form-totalprice">
                    <div class="entryquotation-content-box">
                        <label>总计:</label>
                        <el-input-number size="small" :precision="2" :controls="false" v-model="item.totalAmt"
                            disabled></el-input-number>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            datainfo:{},//
            tabledata: [], // 表格数据
            tameoptions: [], // 币种汇率数据
            value:'',
            options:[],
            token:'',
            userId:'',
            entryquotationLoading:false,
            entryquotationname:'',
            entryquotationtotal:0,
            documentId:0,
        };
    },
    methods: {
        //保留两位小数
        townum(val){
            val=Number(val);
            return val.toFixed(2);
        },
        formattedText(val) {
            var sparr=val.split('\\n')
            var spatext=''
            for (let i = 0; i < sparr.length; i++) {
                spatext+=sparr[i]+'<br><br>'
            }
            return spatext.slice(0,spatext.length - 8)
        },
        // 获取初始数据
        EnterExitCostQuoteEntryExitCosts() {
            this.entryquotationLoading=true;
            var url = "/api/Groups/EnterExitCostQuoteEntryExitCosts";
            var that = this;
            this.$axios({
                method: "post",
                url: url,
                headers: { Authorization: "Bearer" },
                data: { portType: 1, diId: that.value, currUserId: that.userId },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.datainfo=res.data.data;
                    that.options = that.datainfo.rates; // 存储币种汇率
                    that.tabledata = that.datainfo.feeItems; // 存储表格数据
                    that.entryquotationname= that.datainfo.name;
                    that.documentId=that.datainfo.id;
                    that.entryquotationLoading=false;
                    that.calculateItemTotalAll(that.tabledata);
                } else {
                    that.$message.error(res.data.msg);
                    that.entryquotationLoading=false;
                }
            });
        },
        //获取团组
        GetEnterExitCostDataSource() {
            var url = "/api/Groups/GetEnterExitCostDataSource";
            var that = this;
            this.$axios({
                method: "post",
                url: url,
                headers: { Authorization: "Bearer" },
                data: { portType: 1 },
            }).then(function (res) {
                var Costinfo={}
                if (res.data.code == 200) {
                    Costinfo=res.data.data;
                    that.tameoptions=Costinfo.groupNameData;
                    that.value=that.tameoptions[0].id;
                    that.EnterExitCostQuoteEntryExitCosts();
                } else {
                    that.$message.error(res.data.msg);
                }
            });
        },
        //保存
        EnterExitCostQuoteOp() {
            this.datainfo.currUserId=this.userId;
            var url = "/api/Groups/EnterExitCostQuoteOp";
            var that = this;
            this.$axios({
                method: "post",
                url: url,
                headers: { Authorization: "Bearer" },
                data:that.datainfo,
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    that.EnterExitCostQuoteEntryExitCosts()
                    // that.EnterExitCostQuoteEntryExitCosts();
                } else {
                    that.$message.error(res.data.msg);
                }
            });
        },
        //下载
        EnterExitCostQuoteExcelExport() {
            var url = "/api/Groups/EnterExitCostQuoteExcelExport";
            var that = this;
            this.$axios({
                method: "post",
                url: url,
                headers: { Authorization: "Bearer" },
                data:{
                    portType:1,
                    currUserId:that.userId,
                    id:that.documentId,
                }
            }).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);
                }
            });
        },
        // 新增一行
        appenditems(item) {
            item.infos.push({
                currency: '',
                id: 0,
                itemId: item.itemId,
                feeName: "",
                unitPrice: 0,
                currency: "",
                quantity: 1,
                pplNum: 1, // 默认人数为1
                totalAmt: 0,
                remark: '',
            });
        },

        // 移除一行
        removeItem(infos, index,item) {
            infos.splice(index, 1);
            this.calculateItemTotal(item); // 重新计算总价
            this.calculateItemTotalAll(this.tabledata)
        },

        // 汇率变化时重新计算所有
        recalculateAllRates() {
            this.tabledata.forEach(item => {
                if (!item.isOnlyRemark) {
                    item.infos.forEach(info => {
                        const rate = this.getCurrencyRate(info.currency);
                        info.totalAmt = info.unitPrice * info.quantity * (info.pplNum || 1) * rate;
                    });
                    this.calculateItemTotal(item);
                }
            });
            this.calculateItemTotalAll(this.tabledata);
        },

       // 计算小计（包含人数）
        calculateSubtotal(items, item) {
            const rate = this.getCurrencyRate(items.currency);
            items.totalAmt = items.unitPrice * items.quantity * (items.pplNum || 1) * rate;
            this.calculateItemTotal(item);
            this.calculateItemTotalAll(this.tabledata);
        },

        // 获取币种汇率
        getCurrencyRate(currencyCode) {
            const currency = this.options.find((opt) => opt.currencyCode === currencyCode);
            return currency ? currency.rate : 1; // 如果未找到汇率，默认为 1
        },

        // 计算项总价
        calculateItemTotal(item) {
            item.totalAmt = item.infos.reduce((sum, info) => sum + info.totalAmt, 0);
        },
        // 计算总价
        calculateItemTotalAll(item) {
            var zongjia=item.reduce((sum, info) => sum + info.totalAmt, 0);
            this.entryquotationtotal=zongjia;
            // item.totalAmt = item.infos.reduce((sum, info) => sum + info.totalAmt, 0);
        },
    },
    mounted() {
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.GetEnterExitCostDataSource(); // 初始化数据
    },
};
</script>

<style scoped>
.entryquotation-all {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    min-height: 830px;
    min-width: 1582px;
}
.entryquotation-head{
    display: flex;
    justify-content: space-between;
}
.entryquotation-title {
    text-align: center;
    font-size: 17px;
    font-weight: 600;
}

.entryquotation-form {
    border: 1px solid #ebeef5;
    margin-top: 10px;
}

.entryquotation-form-li {
    display: flex;
}

.entryquotation-form-title {
    padding: 10px;
    width: 13%;
    border-bottom: 1px solid #ebeef5;
    border-right: 1px solid #ebeef5;
    display: flex;
    align-items: center;
}

.entryquotation-form-content {
    width: 75%;
    border-bottom: 1px solid #ebeef5;
    border-right: 1px solid #ebeef5;
    padding: 10px;
}

.entryquotation-form-totalprice {
    width: 12%;
    border-bottom: 1px solid #ebeef5;
    padding: 10px;
    display: flex;
    align-items: center;
}

.entryquotation-content {
    display: flex;
    align-items: center;
    margin: 5px 0;
}

.entryquotation-content-box {
    display: flex;
    align-items: center;
    margin-right: 15px;
    padding: 5px 0;
}

.entryquotation-content-box label {
    margin-right: 5px;
}

.entryquotation-form-addbtn {
    text-align: right;
}
.entryquotation-title .el-input__inner{
    font-size: 22px;
    text-align: center;
}
.total-box{
    font-size: 17px;
    font-weight: 600;
    text-align: right;
    color: #409EFF;
}
.exchangerate-box{
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.exchangerate-box-li{
    margin-right: 15px;
    display: flex;
    align-items: center;
}
</style>