import { sendSmsCode } from '@/api/auth'
import { getAreaChildren } from '@/api/fulfiller'

export default {
    data() {
        return {
            formData: {
                mobile: '',
                code: '',
                name: '',
                gender: 1, // 1男 2女
                birthday: '',
                password: '',
                serviceType: [],
                city: '',
                station: '',
                stationId: null
            },
            showPwd: false,
            isAgreed: false,
            serviceTypes: ['宠物接送', '上门喂遛', '上门洗护'],

            // 验证码倒计时
            countDown: 0,
            timer: null,

            // 日期选择器相关
            showPicker: false,
            years: [],
            months: [],
            days: [],
            pickerValue: [0, 0, 0],
            tempYear: 0,
            tempMonth: 0,
            tempDay: 0,

            // 城市选择器相关（从后端加载）
            showCityPicker: false,
            selectStep: 0,
            selectedPathway: [],
            currentList: [],
            selectedCityId: null,

            // 站点选择器相关（从后端加载）
            showStationPicker: false,
            stationList: [],

            // 协议弹窗
            showPrivacy: false,
            privacyTitle: '',
            privacyContent: ''
        }
    },
    created() {
        this.initDateData();
    },
    beforeDestroy() {
        if (this.timer) clearInterval(this.timer);
    },
    methods: {
        initDateData() {
            const now = new Date();
            const currentYear = now.getFullYear();

            // 初始化年份 (1980 - 2030)
            for (let i = 1980; i <= currentYear + 5; i++) {
                this.years.push(i);
            }
            // 初始化月份
            for (let i = 1; i <= 12; i++) {
                this.months.push(i);
            }
            // 初始化日期 (默认31天, 实际应动态计算, 这里简化处理或在change中联动)
            for (let i = 1; i <= 31; i++) {
                this.days.push(i);
            }
        },

        // 打开选择器
        openPicker() {
            // 解析当前选中日期或默认日期
            const dateStr = this.formData.birthday || '2000-01-01';
            const [y, m, d] = dateStr.split('-').map(Number);

            // 查找索引
            const yIndex = this.years.indexOf(y);
            const mIndex = this.months.indexOf(m);
            const dIndex = this.days.indexOf(d);

            this.pickerValue = [
                yIndex > -1 ? yIndex : 0,
                mIndex > -1 ? mIndex : 0,
                dIndex > -1 ? dIndex : 0
            ];

            this.tempYear = this.years[this.pickerValue[0]];
            this.tempMonth = this.months[this.pickerValue[1]];
            this.tempDay = this.days[this.pickerValue[2]];

            this.showPicker = true;
        },

        closePicker() {
            this.showPicker = false;
        },

        onPickerChange(e) {
            const val = e.detail.value;
            this.tempYear = this.years[val[0]];
            this.tempMonth = this.months[val[1]];
            this.tempDay = this.days[val[2]];
        },

        confirmPicker() {
            // 格式化日期
            const mStr = this.tempMonth < 10 ? '0' + this.tempMonth : this.tempMonth;
            const dStr = this.tempDay < 10 ? '0' + this.tempDay : this.tempDay;
            this.formData.birthday = `${this.tempYear}-${mStr}-${dStr}`;
            this.closePicker();
        },

        toggleService(item) {
            const idx = this.formData.serviceType.indexOf(item);
            if (idx > -1) {
                this.formData.serviceType.splice(idx, 1);
            } else {
                this.formData.serviceType.push(item);
            }
        },

        // 验证码
        async getVerifyCode() {
            if (this.countDown > 0) return;
            if (!this.formData.mobile || this.formData.mobile.length !== 11) {
                uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
                return;
            }
            try {
                const res = await sendSmsCode(this.formData.mobile);
                this.countDown = 60;
                this.timer = setInterval(() => {
                    this.countDown--;
                    if (this.countDown <= 0) clearInterval(this.timer);
                }, 1000);
                // TODO 【生产环境必须删除】开发模式自动填入验证码
                const devCode = res.data;
                if (devCode) {
                    this.formData.code = devCode;
                    uni.showToast({ title: '验证码: ' + devCode, icon: 'none', duration: 3000 });
                } else {
                    uni.showToast({ title: '验证码已发送', icon: 'none' });
                }
            } catch (err) {
                console.error('发送验证码失败:', err);
            }
        },

        // 城市选择器 logic（从后端加载）
        async openCityPicker() {
            this.showCityPicker = true;
            if (this.selectedPathway.length === 0) {
                await this.resetCityPicker();
            }
        },
        async resetCityPicker() {
            this.selectStep = 0;
            this.selectedPathway = [];
            await this.loadAreaChildren(0);
        },
        closeCityPicker() {
            this.showCityPicker = false;
        },
        async loadAreaChildren(parentId) {
            try {
                const res = await getAreaChildren(parentId);
                // 城市选择器只显示 城市(0) 和 区域(1)，不显示站点(2)
                this.currentList = (res.data || [])
                    .filter(item => item.type !== 2)
                    .map(item => ({
                        id: item.id,
                        name: item.name,
                        type: item.type,
                        parentId: item.parentId
                    }));
            } catch (err) {
                console.error('加载区域数据失败:', err);
                this.currentList = [];
            }
        },
        async selectCityItem(item) {
            this.selectedPathway[this.selectStep] = item;
            // type: 0=城市, 1=区域
            // 城市级(0)继续加载子级区域
            if (item.type === 0) {
                this.selectStep++;
                this.selectedPathway = this.selectedPathway.slice(0, this.selectStep);
                await this.loadAreaChildren(item.id);
                // 如果已无子级区域，自动确认
                if (this.currentList.length === 0) {
                    this.selectedCityId = item.id;
                    this.confirmCity();
                }
            } else {
                // 区域级(1)选完即确认，站点由站点选择器单独加载
                this.selectedCityId = item.id;
                this.confirmCity();
            }
        },
        async jumpToStep(step) {
            this.selectStep = step;
            if (step === 0) {
                await this.loadAreaChildren(0);
            } else {
                const parent = this.selectedPathway[step - 1];
                if (parent) {
                    await this.loadAreaChildren(parent.id);
                }
            }
        },
        confirmCity() {
            const fullPath = this.selectedPathway.map(i => i.name).join(' ');
            this.formData.city = fullPath;
            // 重置已选站点
            this.formData.station = '';
            this.formData.stationId = null;
            // 选完城市/区域后加载该区域下的站点(type=2)
            const lastSelected = this.selectedPathway[this.selectedPathway.length - 1];
            if (lastSelected) {
                this.loadStations(lastSelected.id);
            }
            this.closeCityPicker();
        },

        // 站点选择器（从后端加载，只取type=2的站点）
        async loadStations(parentId) {
            try {
                const res = await getAreaChildren(parentId);
                this.stationList = (res.data || [])
                    .filter(item => item.type === 2)
                    .map(item => ({
                        id: item.id,
                        name: item.name
                    }));
            } catch (err) {
                console.error('加载站点数据失败:', err);
                this.stationList = [];
            }
        },
        openStationPicker() {
            if (this.stationList.length === 0) {
                uni.showToast({ title: '请先选择工作城市', icon: 'none' });
                return;
            }
            this.showStationPicker = true;
        },
        closeStationPicker() {
            this.showStationPicker = false;
        },
        selectStation(item) {
            this.formData.station = item.name;
            this.formData.stationId = item.id;
            this.closeStationPicker();
        },

        openPrivacy() {
            this.privacyTitle = '宠宝履约者说明';
            this.privacyContent = '1. 履约职责\n作为宠宝履约者，您需要按照平台标准完成宠物接送、喂遛或洗护服务，确保宠物安全与健康。\n\n2. 结算方式\n服务费用将根据订单类型和距离计算，定期结算至您的账户。具体结算周期请查看钱包说明。\n\n3. 行为规范\n请在这个过程中保持专业，穿着整洁，礼貌待人。严禁虐待宠物，违反者将承担法律责任。';
            this.showPrivacy = true;
        },

        goToAuth() {
            if (!this.isAgreed) {
                uni.showToast({ title: '请勾选协议', icon: 'none' });
                return;
            }
            if (!this.formData.mobile || this.formData.mobile.length !== 11) {
                uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
                return;
            }
            if (!this.formData.name) {
                uni.showToast({ title: '请输入姓名', icon: 'none' });
                return;
            }
            if (this.formData.serviceType.length === 0) {
                uni.showToast({ title: '请选择服务类型', icon: 'none' });
                return;
            }
            // 暂存表单数据到本地，供后续页面组装提交
            uni.setStorageSync('recruit_form_data', JSON.stringify(this.formData));
            const services = JSON.stringify(this.formData.serviceType);
            uni.navigateTo({
                url: `/pages/recruit/auth?services=${services}`
            });
        }
    }
}
