<template>
    <div>
        <a-table :columns="columns" :data-source="data" :pagination="false" :loading="loading">
            <span slot="prepay" slot-scope="text, record, index">
                <a-switch checked-children="是" un-checked-children="否" :checked="record.prepay"
                    @change="changePrepay(record)" />
            </span>
            <span slot="isVip" slot-scope="text, record, index">
                <a-switch checked-children="是" un-checked-children="否" :checked="record.isVip" />
            </span>
            <span slot="action" slot-scope="text, record">
                <a @click="handleEdit(record)">编辑</a>

                <a-divider type="vertical" />
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                </a-popconfirm>
            </span>
        </a-table>
        <a-form-model layout="inline" ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-form-model-item label="价格名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" placeholder="请输入房价名称"></a-input>
            </a-form-model-item>
            <a-form-model-item label="原价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="oprice">
                <a-input-number style="width:100%;" v-model="model.oprice" :min="1" placeholder="请填写原价"
                    @change="formVipOpriceChange" />
            </a-form-model-item>
            <a-form-model-item label="现价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="price">
                <a-input-number style="width:100%;" v-model="model.price" :min="1" placeholder="请填写现价" />
            </a-form-model-item>
            <a-form-model-item label="预付" prop="prepay">
                <a-radio-group v-model="model.prepay">
                    <a-radio-button :value="1">
                        是
                    </a-radio-button>
                    <a-radio-button :value="0">
                        否
                    </a-radio-button>
                </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="积分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="integral">
                <a-input-number style="width:100%;" v-model="model.integral" placeholder="请填写积分" />
            </a-form-model-item>
            <a-form-model-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="num">
                <a-input-number style="width:100%;" v-model="model.num" placeholder="请填写数量" />
            </a-form-model-item>
            <a-form-model-item label="会员折扣" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isVip">
                <a-radio-group v-model="model.isVip" @change="onVipChange">
                    <a-radio-button :value="1">
                        是
                    </a-radio-button>
                    <a-radio-button :value="0">
                        否
                    </a-radio-button>
                </a-radio-group>
            </a-form-model-item>
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-button :disabled="submitLoading" :loading="submitLoading" @click="submitForm"
                    type="primary">保存</a-button>
            </a-form-model-item>
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-button :disabled="submitLoading" :loading="submitLoading" @click="clearForm"
                        type="primary">清空</a-button>
            </a-form-model-item>
        </a-form-model>

        <div class="vip-config" v-if="model.isVip">
            <div class="config-heads h-title">
                <div class="head-item">会员等级</div>
                <div class="head-item">原价</div>
                <div class="head-item">折扣（%）</div>
                <div class="head-item">现价</div>
            </div>
            <div class="config-heads" v-for="item in vipLevels" :key="item.id">
                <div class="head-item">[{{ item.name }}]</div>
                <div class="head-item">
                    <a-input-number style="width:80%;" v-model="model.oprice" :min="0" placeholder="请填写原价"
                        @change="vipOpriceChange($event, item)" />
                </div>
                <div class="head-item">
                    <a-input-number style="width:80%;" v-model="item.discount" :min="0" placeholder="请填写折扣"
                        @change="vipDiscountChange($event, item)" />
                </div>
                <div class="head-item">
                    <a-input-number style="width:80%;" :value="item.price" :min="0" placeholder="请填写现价"
                        @change="vipPriceChange($event, item)" />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { list, modify, create, getLayoutpriceLevels } from '@/api/roomLayoutPrice'
import { httpAction, getAction } from "@/api/manage";
import * as api from '@/api/api'
import { find } from 'lodash';
import json5 from 'json5';
const columns = [
    {
        title: '房价名称',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '原价',
        dataIndex: 'oprice',
        key: 'oprice',
    },
    {
        title: '现价',
        dataIndex: 'price',
        key: 'price',
    },
    {
        title: '预付',
        key: 'prepay',
        dataIndex: 'prepay',
        scopedSlots: { customRender: 'prepay' },
    },
    {
        title: '积分',
        dataIndex: 'integral',
        key: 'integral',
    },
    {
        title: '数量',
        dataIndex: 'num',
        key: 'num',
    },
    {
        title: '使用会员折扣',
        dataIndex: 'isVip',
        key: 'isVip',
        scopedSlots: { customRender: 'isVip' },
    },
    {
        title: '操作',
        key: 'action',
        scopedSlots: { customRender: 'action' },
    },
];
let hotelItem = JSON.parse(window.localStorage.getItem('storeInfo'))
export default {
    props: {
        layoutId: null
    },
    data() {
        return {
            submitLoading: false,
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
            loading: false,
            data: [],
            columns,
            searchType: 1,
            validatorRules: {
                name: [{ required: true, message: "请输入房价名称!" }],
                oprice: [{ required: true, message: "请填写原价价!" }],
                price: [{ required: true, message: "请填写现价!" }],
                integral: [{ required: true, message: "请填写积分!" }],
                lunchNum: [{ required: true, message: "请填写中餐数量!" }],
                dinnerNum: [{ required: true, message: "请填写晚餐数量!" }],
            },
            model: {
                id: '',
                name: '',
                oprice: null,
                price: null,
                prepay: 0,
                integral: 0,
                num: 0,
                isVip: 0
            },
            vipLevels: [],
            origiVipLevels: []
        };
    },

    mounted() {
        this.getData()
        this.getVipLevels()

    },
    methods: {
        clearForm() {
            this.model = {
                id: '',
                name: '',
                oprice: null,
                price: null,
                prepay: 0,
                integral: 0,
                num: 0,
                isVip: 0
            }
            this.vipLevels = JSON.parse(JSON.stringify(this.origiVipLevels))
        },
        vipPriceChange(e, item) {
            if (this.model.oprice) {
                item.discount = ((e / this.model.oprice) * 100).toFixed(2)
            }
            item.price = e
        },
        vipDiscountChange(e, item) {
            if (this.model.oprice) {
                item.price = (this.model.oprice * (e / 100)).toFixed(2)
            }
            item.discount = e
        },
        vipOpriceChange(e, item) {
            if (item.discount) {
                item.price = (this.model.oprice * (item.discount / 100)).toFixed(2)
            }
            this.model.oprice = e
        },
        formVipOpriceChange(e) {
            (this.vipLevels || []).forEach(item => {
                if (item.discount) {
                    item.price = (this.model.oprice * (item.discount / 100)).toFixed(2)
                }
            })
            this.model.oprice = e
        },
        getVipLevels() {
            api.getVipLevels({
                pageNo: 1,
                pageSize: 999,
                hotelId: hotelItem.id
            }).then(res => {
                if (res.result && res.result.records) {

                    res.result.records.forEach(s => {
                        s['price'] = 0
                        // 保存原有折扣率
                        s['ldiscount'] = s.discount
                        if (!s.discount) {
                            s.discount = 100
                        }


                    })
                    this.origiVipLevels = res.result.records
                    this.vipLevels = JSON.parse(JSON.stringify(res.result.records))
                }
            })
        },
        changePrepay(record) {

        },
        onVipChange(e) {
            if (this.model.isVip) {

            }
        },
        handleEdit(record) {
            this.getRelationLevels(record.id, (rLevels) => {

                let cpData = JSON.parse(JSON.stringify(record))
                cpData.isVip = record.isVip ? 1 : 0
                cpData.prepay = record.prepay ? 1 : 0
                this.model = cpData
                let nowLvs = JSON.parse(JSON.stringify(this.origiVipLevels))
                if (this.model.oprice) {
                    nowLvs.forEach(s => {
                        if (rLevels) {
                            let findIndex = rLevels.findIndex(q => q.levelId == s.id)
                            if (findIndex > -1) {
                                s.discount = rLevels[findIndex].discount
                                s['memberPriceId'] = rLevels[findIndex].id
                            } else {
                                s['memberPriceId'] = ''
                            }
                        }
                        s.price = (this.model.oprice * (s.discount / 100)).toFixed(2)
                    })
                }
                this.vipLevels = nowLvs
            })


        },
        getRelationLevels(pid, callback) {
            getLayoutpriceLevels({
                parentId: pid
            }).then(res => {
                // 关联折扣等级
                let rLevels = []
                if (res.code == 200 && res.result.length > 0) {
                    rLevels = res.result
                }
                callback(rLevels)
            })
        },
        getData() {
            this.loading = true
            list({
                type: this.searchType,
                // hotelId: hotelItem.id,
                roomLayoutId: this.layoutId,
                pageNo: 1,
                pageSize: 999
            }).then(res => {
                this.loading = false
                console.log(res)
                this.data = res.result.records
            }).catch(res => {
                this.loading = false
            })
        },
        handleDelete(id) {

        },
        submitForm() {
            const that = this;
            // 触发表单验证
            this.$refs.form.validate((valid) => {
                if (valid) {
                    that.confirmLoading = true;
                    if (this.model.id && this.model.id != '') {
                        this.doModify()
                    } else {
                        this.doCreate()
                    }
                }
            });
        },
        doModify() {
            let model = JSON.parse(JSON.stringify(this.model))
            model['hotelId'] = hotelItem.id
            model['layoutId'] = this.layoutId
            model['type'] = 1

            let memberPriceEntities = [];
            if (model.isVip) {
                (this.vipLevels || []).forEach(s => {
                    let item = {
                        id: s.memberPriceId,
                        levelId: s.id,
                        discount: parseFloat(s.discount || 100),
                        ldiscount: parseFloat(s.ldiscount || 100),
                    }
                    memberPriceEntities.push(item)
                })
            }

            model['memberPriceEntities'] = memberPriceEntities

            this.submitLoading = true
            modify(model).then(s => {
                if (s.code == 200) {
                    this.$message.success("保存成功")
                    this.clearForm()
                    this.getData()
                }
            }).catch(err => {
                this.$message.error("保存失败")
            }).finally(_ => {
                this.submitLoading = false
            })
        },
        doCreate() {

            let model = JSON.parse(JSON.stringify(this.model))
            model['hotelId'] = hotelItem.id
            model['layoutId'] = this.layoutId
            model['type'] = 1
            let memberPriceEntities = [];
            if (model.isVip) {
                (this.vipLevels || []).forEach(s => {
                    let item = {
                        levelId: s.id,
                        hotelId: hotelItem.id,
                        discount: parseFloat(s.discount || 100),
                        ldiscount: parseFloat(s.ldiscount || 100),
                    }
                    memberPriceEntities.push(item)
                })
            }

            model['memberPriceEntities'] = memberPriceEntities
            this.submitLoading = true
            create(model).then(s => {
                if (s.code == 200) {
                    this.$message.success("保存成功")
                    this.clearForm()
                    this.getData()
                }
            }).catch(err => {
                this.$message.error("保存失败")
            }).finally(_ => {

                this.submitLoading = false
            })
        }

    },
};
</script>

<style lang="css" scoped>
.vip-config {
    width: 50%;
    height: 200px;
    overflow-y: auto;
    margin-top: 20px;
}

.config-heads {
    display: flex;
}

.config-heads .head-item {
    flex: 1;
    text-align: left;
}

.h-title {
    font-weight: 600;
}
</style>