<template>
    <view class="wxyj-container">
        <!-- 基础信息 -->
        <view class="card">
            <view class="form-row">
                <text class="label">所在地区</text>
                <picker @change="bindPickerChange" :value="index" :range="array">
                    <view class="picker">{{ array[index] }}</view>
                </picker>
            </view>
            <view class="form-row">
                <text class="label">税前月收入</text>
                <!-- 使用 v-model 改善输入体验 -->
                <input class="number-input" type="number" :value="inputValue" @blur="bindKeyInput" :focus="focus" placeholder="请输入税前月收入" />
            </view>
            <view class="tips">基数范围：{{ baseMin }} - {{ baseMax }}</view>
            <view class="actions">
                <button class="btn primary" size="mini" :plain="false" @tap="startCount">开始计算</button>
                <button class="btn" size="mini" :plain="false" @tap="resetData">重新计算</button>
            </view>
        </view>

        <!-- 明细表 -->
        <view class="card">
            <view class="table header">
                <text class="col name">缴费项目</text>
                <text class="col rate">个人比例(%)</text>
                <text class="col rate">单位比例(%)</text>
                <text class="col amt">个人金额</text>
                <text class="col amt">单位金额</text>
            </view>

            <view v-for="(item, idx) in insurance" :key="idx" class="table row">
                <text class="col name">{{ item.category }}</text>
                <input class="col rate rate-input" type="number" :value="item.private_percentage" @input="onRateChange(idx, 'private_percentage', $event)" />
                <input class="col rate rate-input" type="number" :value="item.company_percentage" @input="onRateChange(idx, 'company_percentage', $event)" />
                <text class="col amt">{{ formatAmount(salary * toNumber(item.private_percentage) / 100) }}</text>
                <text class="col amt">{{ formatAmount(salary * toNumber(item.company_percentage) / 100) }}</text>
            </view>

            <view class="table total">
                <text class="col name">合计</text>
                <text class="col rate">{{ private_total }}%</text>
                <text class="col rate">{{ company_total }}%</text>
                <text class="col amt highlight">{{ formatAmount(salary * private_total / 100) }}</text>
                <text class="col amt highlight">{{ formatAmount(salary * company_total / 100) }}</text>
            </view>
        </view>
    </view>
</template>

<script>
//index.js
//获取应用实例
var app = getApp();
export default {
    data() {
        return {
            motto: 'Hello World',
            inputValue: '',
            userInfo: {},
            focus: false,
            index: 1,
            salary: 0,
            array: ['上海', '北京', '广州', '深圳'],
            // 城市基数范围（可根据最新政策调整）
            cityBaseRange: {
                上海: { min: 2014, max: 17814 },
                北京: { min: 2320, max: 21258 },
                广州: { min: 2300, max: 19707 },
                深圳: { min: 2480, max: 22986 }
            },
            // 当前展示的基数范围
            baseMin: 0,
            baseMax: 0,

            insurance: [
                {
                    category: '养老',
                    private_percentage: '8',
                    company_percentage: '22'
                },
                {
                    category: '医疗',
                    private_percentage: '2',
                    company_percentage: '12'
                },
                {
                    category: '失业',
                    private_percentage: '1',
                    company_percentage: '1.7'
                },
                {
                    category: '工伤',
                    private_percentage: '0',
                    company_percentage: '0.5'
                },
                {
                    category: '生育',
                    private_percentage: '0',
                    company_percentage: '0.8'
                },
                {
                    category: '公积金',
                    private_percentage: '7',
                    company_percentage: '7'
                }
            ],
            private_total: 0,
            company_total: 0
        };
    },
    onLoad: function () {
        console.log('onLoad', this);
        var that = this;
        this.total();
        this.updateBaseRange();
        //调用应用实例的方法获取全局数据
        // app.getUserInfo(function(userInfo){
        //   //更新数据
        //   that.setData({
        //     userInfo:userInfo
        //   })
        //
    },
    methods: {
        //事件处理函数
        bindViewTap: function () {
            uni.navigateTo({
                url: '../logs/logs'
            });
        },

        bindPickerChange: function (e) {
            console.log('picker发送选择改变，携带值为', e.detail.value);
            this.setData({ index: e.detail.value });
            // 切换城市时提示基数范围
            const city = this.array[e.detail.value];
            const range = this.cityBaseRange[city] || { min: 0, max: 0 };
            this.modalView(`当前城市基数范围：${range.min} - ${range.max}`);
            this.updateBaseRange();
        },

        updateBaseRange: function () {
            const city = this.array[this.index];
            const range = this.cityBaseRange[city] || { min: 0, max: 0 };
            this.setData({ baseMin: range.min, baseMax: range.max });
        },

        total: function () {
            const insurance = this.insurance;
            console.log(insurance);
            let private_total = 0;
            let company_total = 0;
            if (insurance) {
                insurance.forEach((t, i) => {
                    private_total += this.toNumber(t.private_percentage);
                    company_total += this.toNumber(t.company_percentage);
                });
            }
            this.setData({
                private_total,
                company_total
            });
        },

        bindKeyInput: function (e) {
            console.log(e);
            this.setData({ inputValue: e.detail.value });
        },

        onRateChange: function (idx, key, e) {
            const val = e.detail.value;
            const list = this.insurance.slice();
            list[idx][key] = val;
            this.setData({ insurance: list });
            this.total();
        },

        toNumber: function (v) {
            const n = parseFloat(v);
            return isNaN(n) ? 0 : n;
        },

        formatAmount: function (v) {
            const n = parseFloat(v);
            if (!isNaN(n)) {
                return n.toFixed(2);
            }
            return '0.00';
        },

        modalView: function (text) {
            uni.showModal({
                title: 'Warning',
                content: text,
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    }
                }
            });
        },

        startCount: function () {
            let inputValue = this.inputValue;
            if (!!inputValue) {
                if (!!(inputValue / 1)) {
                    if (inputValue > 0) {
                        // 根据城市范围校验并钳制
                        const city = this.array[this.index];
                        const range = this.cityBaseRange[city] || { min: 0, max: Number.MAX_SAFE_INTEGER };
                        const iv = parseFloat(inputValue);
                        inputValue = Math.min(Math.max(iv, range.min), range.max);
                        this.setData({
                            salary: inputValue,
                            focus: false
                        });
                    } else {
                        this.modalView('别开玩笑了，你还欠老板钱？');
                    }
                } else {
                    this.modalView('请输入数字，OK？');
                }
            } else {
                this.modalView('输入不能为空，请重新输入！');
            }
        },

        resetData: function () {
            this.setData({
                salary: 0,
                focus: true,
                inputValue: ''
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
