<template>
    <div class="car_add">
        <div>
            <div class="communal-title">
                <div>{{ title }}</div>
            </div>
        </div>
        <div style="display: flex;">
            <div style="text-align:left;font-size: 17px;font-weight: 600;color: #555;">
                团组成本预算 - 机票的预算:
            </div>
            <div style="margin-left:20px;color: #555;" v-if="airGroupCostParameter != null">
                经济舱: {{ airGroupCostParameter.jjccb }}元/人 {{ airGroupCostParameter.jjcrs }}人
                共:{{ airGroupCostParameter.jjccb * airGroupCostParameter.jjcrs
                }}元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                公务舱: {{ airGroupCostParameter.gwccb }}元/人 {{ airGroupCostParameter.gwcrs }}人
                共:{{ airGroupCostParameter.gwccb * airGroupCostParameter.gwcrs
                }}元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </div>
            <div style="margin-left:20px;" v-else>
                团组成本暂未开放此团数据!
            </div>
        </div>
        <hr style='background-color:#5555; height:1px; border:none;margin: 10px 0;' />
        <div>
            <el-form :model="delegationInfo" label-width="100px" class="demo-ruleForm">
                <div style="display: flex;">
                    <div style="width: 25%;">
                        <el-form-item label="团组名称:" label-width="160px">
                            <el-select v-model="DiId" clearable filterable placeholder="团组选择"
                                @change="AirTicketResChange" :disabled="isShow" style="width: 100%;">
                                <el-option v-for="item in DelegationSelect" :key="item.id" :label="item.groupName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div style="width: 25%;">
                        <el-form-item label="团 号:" prop="tourCode" label-width="160px">
                            <el-input placeholder="团号" v-model="delegationInfo.tourCode" :disabled="true">
                            </el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 25%;">
                        <el-form-item label="客户:" prop="clientName" label-width="160px">
                            <el-input placeholder="客户" v-model="delegationInfo.clientName" :disabled="true">
                            </el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 25%;">
                        <el-form-item label="出访国家:" prop="visitCountry" label-width="160px">
                            <el-input placeholder="出访国家" v-model="delegationInfo.visitCountry" :disabled="true">
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <el-form :model="OpTicketBlackCodeData" :rules="OpTicketBlackCodeRules" ref="OpTicketBlackCodeData"
                label-width="100px" class="demo-ruleForm">
                <div>
                    <el-form-item label="标题:" prop="title" label-width="160px">
                        <el-input placeholder="标题" v-model="OpTicketBlackCodeData.title">
                        </el-input>
                    </el-form-item>
                </div>
                <div>
                    <span style="color: red; padding-left: 100px;">
                        请严格遵守此格式!!! 1.KL1723 SU06DEC AMSBRU 0925 1010 -- -- ERJ190 45M (是中转情况下末尾添加[中转])
                    </span>
                </div>
                <div style="display: flex;">
                    <div style="width: 60%;">
                        <el-form-item label="黑屏代码:" prop="blackCode" label-width="160px">
                            <el-input @input="parseAirData" type="textarea" :rows="14"
                                placeholder="请严格遵守此格式!!! 1. EK363 R1 WE08MAR CANDXB HK7 0015 0515 SEAME 2 3 (注意空格以及多条数据换行)"
                                v-model="OpTicketBlackCodeData.blackCode"></el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 40%;">
                        <el-form-item label="公务舱现价:" label-width="160px">
                            <el-input placeholder="公务舱现价" v-model="OpTicketBlackCodeData.nowPrice">
                            </el-input>
                            <!-- <el-input type="textarea" :rows="3" placeholder="全价说明"
                                v-model="OpTicketBlackCodeData.price"></el-input> -->
                        </el-form-item>
                        <el-form-item label="经济舱现价:" label-width="160px">
                            <!-- <el-input type="textarea" :rows="3" placeholder="现价说明"
                                v-model="OpTicketBlackCodeData.nowPrice"></el-input> -->
                            <el-input placeholder="经济舱现价" v-model="OpTicketBlackCodeData.price">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="公务舱全价:" label-width="160px">
                            <el-input placeholder="公务舱全价" v-model="OpTicketBlackCodeData.bcPrice">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="经济舱全价:" label-width="160px">
                            <el-input placeholder="经济舱全价" v-model="OpTicketBlackCodeData.ecPrice">
                            </el-input>
                        </el-form-item>
                        <el-form-item>

                        </el-form-item>
                    </div>
                </div>
                <div style="display: flex;">
                    <div style="width: 60%;">
                        <el-form-item label="备注:" prop="remark" label-width="160px">
                            <el-input type="textarea" :rows="3" placeholder="备注"
                                v-model="OpTicketBlackCodeData.remark"></el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 40%;text-align:right;margin-top: 2%;">
                        <div>
                            <el-button type="primary" @click="addBtn">保存</el-button>
                            <el-button @click="back()">取消</el-button>
                        </div>

                    </div>
                </div>
            </el-form>

        </div>
        <div id="testTable">
            <el-table border :data="tableData" style="width: 100%">
                <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                    :width="column.width">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row[column.prop]" :disabled="column.prop === 'id'"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            title: "新增机票行程代码录入",
            token: '',
            userId: 0,
            id: '',
            DiId: '',
            isShow: false,
            delegationInfo: {},
            DelegationSelect: [],//团组下拉框
            airGroupCostParameter: {},//机票成本预算
            OpTicketBlackCodeData: {
                status: 0,
                id: 0,
                diId: 0,
                blackCode: '',
                price: '',
                nowPrice: '',
                bcPrice: '',
                ecPrice: '',
                createUserId: 0,
                remark: '',
                title: ''
            },
            OpTicketBlackCodeRules: {
                blackCode: [
                    { required: true, message: '该信息为必填信息', trigger: ['blur', 'change'] },
                ],
                price: [
                    { required: true, message: '该信息为必填信息', trigger: ['blur', 'change'] },
                ],
                nowPrice: [
                    { required: true, message: '该信息为必填信息', trigger: ['blur', 'change'] },
                ],
                bcPrice: [
                    { required: true, message: '请输入机票单价', trigger: ['blur', 'change'] },
                    { pattern: /^(([1-9]?\d{0,8}(\.\d{1,2})?)|999999999|999999999\.(0){1,2})$/, message: '请输入正确的金额(最多2位小数)' }
                ],
                ecPrice: [
                    { required: true, message: '请输入机票单价', trigger: ['blur', 'change'] },
                    { pattern: /^(([1-9]?\d{0,8}(\.\d{1,2})?)|999999999|999999999\.(0){1,2})$/, message: '请输入正确的金额(最多2位小数)' }
                ],
                title: [
                    { required: true, message: '该信息为必填信息', trigger: ['blur', 'change'] },
                ],
            },
            //-------------------------
            flightData: [
                {
                    type: "经济现价",
                    prices: {

                    },
                    total: 0
                },
                {
                    type: "经济全价",
                    prices: {

                    },
                    total: 0
                },
                {
                    type: "公务现价",
                    prices: {

                    },
                    total: 0
                },
                {
                    type: "公务全价",
                    prices: {

                    },
                    total: 0
                },
                {
                    type: "头等现价",
                    prices: {

                    },
                    total: 0
                },
                {
                    type: "头等全价",
                    prices: {

                    },
                    total: 0
                }
            ],
            tableData: [],
            columns: [

            ],
            PushColumns: [],
            fiexedColumns: [{ prop: 'type', label: '票价类型', width: 180 },
            { prop: 'total', label: '合计', width: 180 }],
            settingValue: {
                "经济现价": "price",
                "经济全价": "ecPrice",
                "公务现价": "nowPrice",
                "公务全价": "bcPrice",
                "头等现价": "fcNowPrice",
                "头等全价": "fcPrice"
            }
        }
    },
    methods: {
        //团组下拉框
        DelegationSelectFun() {
            var url = "/api/Business/GetGroupNameList"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    "portType": 1,
                    "pageIndex": 0,
                    "pageSize": 0
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.DelegationSelect = res.data.data;
                }
            })
        },
        QueryTicketBlackCodeById() {
            var url = "/api/Resource/QueryTicketBlackCodeById"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    Id: that.id,
                    DiId: that.DiId
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.delegationInfo = res.data.data.delegationInfo;
                    that.airGroupCostParameter = res.data.data.groupCostParameter;
                    if (res.data.data.ticketBlackCode) {
                        var TicketBlackCode = res.data.data.ticketBlackCode;
                        that.OpTicketBlackCodeData.id = TicketBlackCode.id
                        that.OpTicketBlackCodeData.diId = TicketBlackCode.diId
                        that.OpTicketBlackCodeData.blackCode = TicketBlackCode.blackCode
                        that.OpTicketBlackCodeData.price = TicketBlackCode.price
                        that.OpTicketBlackCodeData.nowPrice = TicketBlackCode.nowPrice
                        that.OpTicketBlackCodeData.bcPrice = TicketBlackCode.bcPrice
                        that.OpTicketBlackCodeData.ecPrice = TicketBlackCode.ecPrice
                        that.OpTicketBlackCodeData.remark = TicketBlackCode.remark
                        that.OpTicketBlackCodeData.title = TicketBlackCode.title;

                        for (var key in that.settingValue) {
                            that.flightData.filter(item => item.type == key)[0].total = TicketBlackCode[that.settingValue[key]];
                        }
                    }
                }
                that.parseAirData();
            })
        },
        //跳转
        back() {
            this.$router.push({
                path: "/home/TicketBlackCode",
                query: {
                    DiId: this.DiId,
                }
            })
        },
        //团组下拉框选择事件
        AirTicketResChange() {
            this.QueryTicketBlackCodeById()
        },
        //点击保存事件
        addBtn() {
            if (!this.DiId) {
                this.$message.error("请选择团组名称");
                return;
            }
            const that = this;
            that.$refs.OpTicketBlackCodeData.validate((valid) => {
                if (valid) {

                    that.parseAirData();
                    var url = "/api/Resource/OpTicketBlackCode"
                    that.OpTicketBlackCodeData.createUserId = that.userId;
                    that.OpTicketBlackCodeData.diId = that.DiId
                    that.OpTicketBlackCodeData.price = that.OpTicketBlackCodeData.price.toString();
                    that.OpTicketBlackCodeData.nowPrice = that.OpTicketBlackCodeData.nowPrice.toString();

                    that.$axios({
                        method: 'post',
                        url: url,
                        headers: {
                            Authorization: 'Bearer ' + that.token
                        },
                        data: that.OpTicketBlackCodeData
                    }).then(function (res) {

                        if (res.data.code == 200) {
                            that.$message({
                                message: res.data.msg,
                                type: 'success'
                            });
                            setTimeout(() => {
                                that.back();
                                // that.$router.push('/home/TicketBlackCode')
                            }, 1000);
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
                } else {
                    this.$message.error('请完善信息在保存!');
                    return false;
                }
            })
        },
        parseAirData() {
            var data = this.OpTicketBlackCodeData.blackCode;
            // 按行分割数据
            const lines = data.trim().split('\n');

            // 提取航司的函数
            function extractAirline(line) {
                // 使用正则表达式匹配航司代码(两个大写字母或一个大写字母加一个数字)
                const match = line.match(/[A-Z]{2}|[A-Z]\d/);
                return match ? match[0] : null;
            }

            // 解析每一行并提取航司
            var flightNumbers = lines.map(line => {
                // 使用正则表达式匹配航班号(假设航班号是字母+数字的组合)
                const match = line.match(/[A-Z]{2}\d+/);
                console.log(match, "match ");
                return match ? match[0] : null;
            });

            flightNumbers = flightNumbers.filter(item => item);

            //console.log(flightNumbers, "flightNumbers ");

            this.PushColumns = flightNumbers.map(flightNumber => {
                return {
                    prop: flightNumber,
                    label: flightNumber,
                    width: 100
                }
            })

            // {
            //         type: "公务全价",
            //         prices: {
            //             FM: 55320,
            //             EK: 22883,
            //             "3U": 33608
            //         },
            //         total: 111811
            //     }

            var that = this;

            //console.log(this.tableData, "this.tableData ");

            this.tableData.forEach(item => {
                that.flightData.forEach(flight => {
                    if (flight.type == item.type) {
                        var columns = that.PushColumns.map(x => x.prop);
                        for (var i = 0; i < columns.length; i++) {
                            flight.prices[columns[i]] = item[columns[i]];
                        }
                    }
                })

                for (var key in that.settingValue) {
                    if (item.type == key) {
                        that.OpTicketBlackCodeData[that.settingValue[key]] = Number(item.total);
                        break;
                    }
                }
            })

            this.flightData.forEach(item => {
                //遍历item.prices
                for (var key in item.prices) {
                    //判断key是否存在that.PushColumns中
                    var isExist = false;
                    for (var i = 0; i < that.PushColumns.length; i++) {
                        if (that.PushColumns[i].prop == key) {
                            isExist = true;
                            break;
                        }
                    }
                    //不存在就删除item.prices中的key
                    if (!isExist) {
                        delete item.prices[key];
                    }
                }

                that.PushColumns.forEach(column => {
                    //判断item.prices中是否存在column.prop
                    if (item.prices[column.prop]) {
                        return;
                    } else {
                        item.prices[column.prop] = 0;
                    }
                })
            })

            console.log(this.flightData, "this.flightData ");
            console.log(this.columns, "this.columns ");
            this.transformData();
        },
        //----------------------
        transformData() {

            this.columns = [];
            this.columns.push(...this.fiexedColumns);
            this.columns.splice(1, 0, ...this.PushColumns);
            this.tableData = [];
            this.tableData = this.flightData.map(item => {
                const tableItem = { type: item.type, total: item.total };
                for (let column of this.columns) {
                    if (column.prop !== 'type' && column.prop !== 'total') {
                        tableItem[column.prop] = item.prices[column.prop];
                    }
                }
                return tableItem;
            });
        },
    },

    mounted() {

        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId

        this.id = this.$route.query.id
        this.DiId = parseInt(this.$route.query.DiId)
        this.DelegationSelectFun()

        var that = this
        if (that.DiId && that.id) {
            that.OpTicketBlackCodeData.status = 2;
            that.isShow = true
        } else {
            that.isShow = false
            that.OpTicketBlackCodeData.status = 1;
        }

        that.QueryTicketBlackCodeById();
        //-------
        //this.transformData();
    }
}
</script>
<style>
.communal-list {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
}

.car_add .communal-title {
    display: flex;
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-bottom: 20px;
    justify-content: space-between;
    align-items: center;
}

.appraise-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 50px 0;
}

.appraise-box>div {
    width: 30%;
}

.communal-box {
    display: flex;
}

.communal-box>button {
    margin-left: 10px;
    padding: 8px 20px;
}

.car_add {
    background-color: #fff;
    padding: 20px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
}

@media screen and (max-width: 1700px) {
    .appraise-box>div {
        width: 48%;
    }

    .appraise-box>div el-form-item__content {
        width: 260px !important;
    }
}
</style>