<template>
    <view class="set-user-info-container">
        <!-- 标题 -->
        <view class="page-title">完善个人信息</view>

        <scroll-view class="form-scroll" scroll-y>
            <!-- 头像上传 -->
            <view class="avatar-section">
                <view class="avatar-wrapper" @click="chooseAvatar">
                    <image v-if="formData.avatar" :src="formData.avatar" class="avatar-image" mode="aspectFill" />
                    <view v-else class="avatar-placeholder">
                         <image src="/static/images/login/user.png" class="avatar-image" mode="aspectFill" style="width: 80%; height: 80%;" />
                    </view>
                </view>
                <view class="avatar-tip">
                    <text class="tip-text">点击上传头像</text>
                    <text class="required-mark">*</text>
                </view>
                <view v-if="errors.avatar" class="error-tip">{{ errors.avatar }}</view>
            </view>

            <!-- 表单字段 -->
            <view class="form-section">
                <!-- 真实姓名 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>真实姓名</text>
                        <text class="required-mark">*</text>
                    </view>
                    <input v-model="formData.realName" class="form-input" placeholder="请输入真实姓名"
                        @blur="validateField('realName')" />
                    <view v-if="errors.realName" class="error-tip">{{ errors.realName }}</view>
                </view>

                <!-- 从业时间 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>从业时间</text>
                        <text class="required-mark">*</text>
                    </view>
                    <picker mode="date" :value="formData.practiceYear" :start="startDate" :end="endDate"
                        @change="onPracticeYearChange">
                        <view class="picker-view">
                            <text :class="formData.practiceYear ? 'picker-text' : 'picker-placeholder'">
                                {{ formData.practiceYear ? formatDate(formData.practiceYear) : '请选择从业时间' }}
                            </text>
                            <text class="picker-arrow">›</text>
                        </view>
                    </picker>
                    <view v-if="errors.practiceYear" class="error-tip">{{ errors.practiceYear }}</view>
                </view>

                <!-- 专业领域 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>专业领域</text>
                        <text class="required-mark">*</text>
                    </view>
                    <picker mode="selector" :range="professionalFields" :value="professionalFieldIndex"
                        @change="onProfessionalFieldChange">
                        <view class="picker-view">
                            <text :class="formData.professionalField ? 'picker-text' : 'picker-placeholder'">
                                {{ formData.professionalField || '请选择专业领域' }}
                            </text>
                            <text class="picker-arrow">›</text>
                        </view>
                    </picker>
                    <view v-if="errors.professionalField" class="error-tip">{{ errors.professionalField }}</view>
                </view>

                <!-- 法律场景 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>法律场景</text>
                        <text class="required-mark">*</text>
                    </view>
                    <view class="picker-view" @click="showLegalScenarioModal = true">
                        <view class="picker-text-ellipsis">
                            <text :class="formData.legalScenarios && formData.legalScenarios.length > 0 ? 'picker-text' : 'picker-placeholder'">
                                {{ getLegalScenarioText() || '请选择法律场景' }}
                            </text>
                        </view>
                        <text class="picker-arrow">›</text>
                    </view>
                    <view v-if="errors.legalScenario" class="error-tip">{{ errors.legalScenario }}</view>
                </view>

                <!-- 联系地址 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>联系地址</text>
                        <text class="required-mark">*</text>
                    </view>
                    <input v-model="formData.address" class="form-input" placeholder="请输入常用联系地址"
                        @blur="validateField('address')" />
                    <view v-if="errors.address" class="error-tip">{{ errors.address }}</view>
                </view>

                <!-- 律师事务所名称 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>律师事务所名称</text>
                        <text class="required-mark">*</text>
                    </view>
                    <picker 
                        mode="selector" 
                        :range="firmList" 
                        range-key="firmName"
                        :value="lawFirmIndex"
                        @change="onLawFirmChange"
                    >
                        <view class="picker-view">
                            <text :class="formData.lawFirmName ? 'picker-text' : 'picker-placeholder'">
                                {{ formData.lawFirmName || '请选择律师事务所名称' }}
                            </text>
                            <text class="picker-arrow">›</text>
                        </view>
                    </picker>
                    <view v-if="errors.lawFirmName" class="error-tip">{{ errors.lawFirmName }}</view>
                </view>

                <!-- 律师事务所收款账号 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>律师事务所收款账号</text>
                        <text class="required-mark">*</text>
                    </view>
                    <picker 
                        mode="selector" 
                        :range="paymentAccountList" 
                        :value="paymentAccountIndex"
                        @change="onPaymentAccountChange"
                    >
                        <view class="picker-view">
                            <text :class="formData.paymentAccount ? 'picker-text' : 'picker-placeholder'">
                                {{ formData.paymentAccount || '请选择律师事务所收款账号' }}
                            </text>
                            <text class="picker-arrow">›</text>
                        </view>
                    </picker>
                    <view v-if="errors.paymentAccount" class="error-tip">{{ errors.paymentAccount }}</view>
                </view>

                

                <!-- 律师资格证 -->
                <view class="form-item">
                    <view class="form-label">
                        <text>律师资格证</text>
                        <text class="required-mark">*</text>
                    </view>
                    <view class="certificate-upload" @click="chooseCertificate">
                        <image v-if="formData.certificate" :src="formData.certificate" class="certificate-image"
                            mode="aspectFit" />
                        <view v-else class="certificate-placeholder">
                            <text class="certificate-icon">🏔️</text>
                            <text class="certificate-text">点击上传图片</text>
                        </view>
                    </view>
                    <view v-if="errors.certificate" class="error-tip">{{ errors.certificate }}</view>
                </view>
            </view>
        </scroll-view>

        <!-- 提交按钮 -->
        <view class="submit-section">
            <button class="submit-btn" @click="handleSubmit">提交信息</button>
        </view>
        
        <!-- 法律场景多选弹窗 -->
        <view class="modal-overlay" v-if="showLegalScenarioModal" @click="showLegalScenarioModal = false">
            <view class="legal-scenario-modal" @click.stop>
                <view class="modal-header">
                    <view class="modal-title">选择您擅长的法律场景</view>
                    <text class="cancel-btn" @click="showLegalScenarioModal = false">取消</text>
                </view>
                <view class="scenario-tags">
                    <view 
                        v-for="(scenario, index) in legalScenarios" 
                        :key="index"
                        class="scenario-tag"
                        :class="{ 'selected': isLegalScenarioSelected(scenario) }"
                        @click="toggleLegalScenario(scenario)"
                    >
                        {{ scenario }}
                    </view>
                </view>
                <button class="confirm-btn" @click="confirmLegalScenarios">选好了</button>
            </view>
        </view>
    </view>
</template>

<script>
import upload from '@/utils/upload'
import { updateUserProfile, uploadAvatar } from '@/api/system/user'
import { getFirmList, getLegalProblemScenarioList, getExpertiseAreaList } from '@/api/setUserInfo'
import { getToken } from '@/utils/auth'
import config from '@/config'

export default {
    data() {
        return {
            formData: {
                avatar: '',
                realName: '',
                practiceYear: '',
                professionalField: '',
                legalScenarios: [], // 改为数组支持多选
                address: '',
                paymentAccount: '',
                lawFirmName: '',
                certificate: ''
            },
            errors: {},
            startDate: '1950-01-01', // 最早可选日期
            endDate: '', // 最晚可选日期（今天）
            professionalFields: ['刑事法律', '民事法律', '商事法律', '行政法律', '知识产权', '劳动法律', '其他'],
            professionalFieldIndex: -1,
            legalScenarios: ['家庭生活', '职场工作', '邻里与社区', '网络与数字', '交通出行', '居住与物业', '消费与服务'],
            showLegalScenarioModal: false,
            firmList: [], // 律师事务所列表
            lawFirmIndex: -1,
            paymentAccountList: [], // 收款账号列表
            paymentAccountIndex: -1,
            baseUrl: config.baseUrl
        }
    },
    onLoad() {
        // 设置最晚可选日期为今天
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        this.endDate = `${year}-${month}-${day}`
        // 加载律师事务所列表
        // this.getPageInfo()
    },
    methods: {
        getPageInfo() {
            getFirmList().then(res => {
                if (res.data && res.data.length > 0) {
                    this.firmList = res.data
                    // 提取收款账号列表（假设每个律师事务所都有收款账号字段）
                    this.paymentAccountList = res.data.map(item => item.paymentAccount || item.account || '').filter(account => account)
                }
            }).catch(() => {
                // 如果接口失败，使用默认数据
                this.firmList = []
                this.paymentAccountList = []
            })
        },
        
        // 律师事务所选择
        onLawFirmChange(e) {
            this.lawFirmIndex = e.detail.value
            const selectedFirm = this.firmList[e.detail.value]
            if (selectedFirm) {
                this.formData.lawFirmName = selectedFirm.firmName || selectedFirm.name || ''
                // 如果选择的律师事务所有收款账号，自动填充
                if (selectedFirm.paymentAccount || selectedFirm.account) {
                    this.formData.paymentAccount = selectedFirm.paymentAccount || selectedFirm.account
                    // 找到对应的收款账号索引
                    const accountIndex = this.paymentAccountList.indexOf(this.formData.paymentAccount)
                    if (accountIndex > -1) {
                        this.paymentAccountIndex = accountIndex
                    }
                }
                this.errors.lawFirmName = ''
            }
        },
        
        // 收款账号选择
        onPaymentAccountChange(e) {
            this.paymentAccountIndex = e.detail.value
            this.formData.paymentAccount = this.paymentAccountList[e.detail.value] || ''
            this.errors.paymentAccount = ''
        },
        // 选择头像
        chooseAvatar() {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    const tempFilePath = res.tempFilePaths[0]
                    this.uploadAvatarFile(tempFilePath)
                }
            })
        },

        // 上传头像
        uploadAvatarFile(filePath) {
            this.$modal.loading('上传中...')
            uni.uploadFile({
                url: 'http://192.168.2.54:8899/file/upload',
                filePath: filePath,
                name: 'avatarfile',
                header: {
                    'Authorization': 'Bearer ' + (getToken() || '')
                },
                success: (res) => {
                    try {
                        const result = JSON.parse(res.data)
                        if (result.code === 200) {
                            this.$modal.closeLoading()
                            this.formData.avatar = this.baseUrl + result.imgUrl
                            this.errors.avatar = ''
                        } else {
                            this.$modal.closeLoading()
                            this.$modal.msgError(result.msg || '上传失败')
                        }
                    } catch (e) {
                        this.$modal.closeLoading()
                        this.$modal.msgError('上传失败')
                    }
                },
                fail: (error) => {
                    this.$modal.closeLoading()
                    this.$modal.msgError('上传失败')
                }
            })
        },

        // 选择律师资格证
        chooseCertificate() {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    const tempFilePath = res.tempFilePaths[0]
                    this.uploadCertificateFile(tempFilePath)
                }
            })
        },

        // 上传资格证
        uploadCertificateFile(filePath) {
            this.$modal.loading('上传中...')
            upload({
                url: '/system/user/profile/certificate',
                name: 'certificate',
                filePath: filePath
            }).then(res => {
                this.$modal.closeLoading()
                this.formData.certificate = this.baseUrl + res.imgUrl
                this.errors.certificate = ''
            }).catch(() => {
                this.$modal.closeLoading()
            })
        },

        // 从业时间选择
        onPracticeYearChange(e) {
            this.formData.practiceYear = e.detail.value
            this.errors.practiceYear = ''
        },
        
        // 格式化日期显示
        formatDate(dateStr) {
            if (!dateStr) return ''
            const date = new Date(dateStr)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}年${month}月${day}日`
        },

        // 专业领域选择
        onProfessionalFieldChange(e) {
            this.professionalFieldIndex = e.detail.value
            this.formData.professionalField = this.professionalFields[e.detail.value]
            this.errors.professionalField = ''
        },

        // 获取法律场景显示文本
        getLegalScenarioText() {
            if (!this.formData.legalScenarios || this.formData.legalScenarios.length === 0) {
                return ''
            }
            return this.formData.legalScenarios.join('、')
        },
        
        // 判断法律场景是否已选中
        isLegalScenarioSelected(scenario) {
            return this.formData.legalScenarios && this.formData.legalScenarios.includes(scenario)
        },
        
        // 切换法律场景选择状态
        toggleLegalScenario(scenario) {
            if (!this.formData.legalScenarios) {
                this.formData.legalScenarios = []
            }
            const index = this.formData.legalScenarios.indexOf(scenario)
            if (index > -1) {
                // 已选中，取消选择
                this.formData.legalScenarios.splice(index, 1)
            } else {
                // 未选中，添加选择
                this.formData.legalScenarios.push(scenario)
            }
        },
        
        // 确认法律场景选择
        confirmLegalScenarios() {
            if (this.formData.legalScenarios && this.formData.legalScenarios.length > 0) {
                this.errors.legalScenario = ''
            }
            this.showLegalScenarioModal = false
        },

        // 验证单个字段
        validateField(field) {
            this.errors[field] = ''
            const value = this.formData[field]

            if (!value || value.trim() === '') {
                switch (field) {
                    case 'realName':
                        this.errors.realName = '请填写真实姓名'
                        break
                    case 'address':
                        this.errors.address = '请填写联系地址'
                        break
                    case 'paymentAccount':
                        this.errors.paymentAccount = '请选择律师事务所收款账号'
                        break
                    case 'lawFirmName':
                        this.errors.lawFirmName = '请选择律师事务所名称'
                        break
                }
            }
        },

        // 验证所有字段
        validateForm() {
            this.errors = {}
            let isValid = true

            if (!this.formData.avatar) {
                this.errors.avatar = '请上传头像'
                isValid = false
            }

            if (!this.formData.realName || this.formData.realName.trim() === '') {
                this.errors.realName = '请填写真实姓名'
                isValid = false
            }

            if (!this.formData.practiceYear) {
                this.errors.practiceYear = '请选择从业时间'
                isValid = false
            }

            if (!this.formData.professionalField) {
                this.errors.professionalField = '请选择专业领域'
                isValid = false
            }

            if (!this.formData.legalScenarios || this.formData.legalScenarios.length === 0) {
                this.errors.legalScenario = '请选择法律场景'
                isValid = false
            }

            if (!this.formData.address || this.formData.address.trim() === '') {
                this.errors.address = '请填写联系地址'
                isValid = false
            }

            if (!this.formData.paymentAccount || this.formData.paymentAccount.trim() === '') {
                this.errors.paymentAccount = '请选择律师事务所收款账号'
                isValid = false
            }

            if (!this.formData.lawFirmName || this.formData.lawFirmName.trim() === '') {
                this.errors.lawFirmName = '请选择律师事务所名称'
                isValid = false
            }

            if (!this.formData.certificate) {
                this.errors.certificate = '请上传律师资格证'
                isValid = false
            }

            return isValid
        },

        // 提交表单
        handleSubmit() {
            if (!this.validateForm()) {
                this.$modal.msgError('请完善所有必填信息')
                return
            }

            this.$modal.loading('提交中...')
            updateUserProfile(this.formData).then(() => {
                this.$modal.closeLoading()
                this.$modal.msgSuccess('提交成功')
                setTimeout(() => {
                    uni.navigateBack()
                }, 1500)
            }).catch(() => {
                this.$modal.closeLoading()
            })
        }
    }
}
</script>

<style lang="scss" scoped>
page {
    background-color: #F9FAFC;
}

input,.picker-view {
    background-color: #fff !important;
    width: 676rpx;
    height: 103rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 2rpx 11rpx 0rpx rgba(0, 0, 0, 0.06);
    border-radius: 23rpx 23rpx 23rpx 23rpx;
}

.set-user-info-container {
    min-height: 100vh;
    padding-bottom: 120rpx;
}

.page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    padding: 40rpx 0 30rpx;
    // background-color: #fff;
}

.form-scroll {
    height: calc(100vh - 200rpx);
    padding: 0 30rpx;
}

.avatar-section {
    // background-color: #F9FAFC;
    padding: 40rpx 0;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.avatar-wrapper {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    overflow: hidden;
    // background-color: #f0f0f0;
    margin-bottom: 20rpx;
}

.avatar-image {
    width: 100%;
    height: 100%;
}

.avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    // background-color: #f0f0f0;
}

.avatar-icon {
    font-size: 80rpx;
    color: #ccc;
}

.camera-icon {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 48rpx;
    height: 48rpx;
    background-color: #4a90e2;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 3rpx solid #fff;
}

.camera-text {
    font-size: 24rpx;
}

.avatar-tip {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #4a90e2;
}

.tip-text {
    margin-right: 4rpx;
}

.required-mark {
    color: #ff4d4f;
    font-size: 28rpx;
}

.form-section {
    // background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.form-item {
    margin-bottom: 40rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.form-input {
    width: 100%;
    height: 80rpx;
    background-color: #f8f9fa;
    border-radius: 12rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
}

.picker-view {
    width: 100%;
    height: 80rpx;
    background-color: #f8f9fa;
    border-radius: 12rpx;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
}

.picker-text {
    font-size: 28rpx;
    color: #333;
}

.picker-placeholder {
    font-size: 28rpx;
    color: #999;
}

.picker-text-ellipsis {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 20rpx;
}

.picker-arrow {
    font-size: 40rpx;
    color: #999;
    font-weight: 300;
}

.certificate-upload {
    width: 100%;
    height: 300rpx;
    border: 2rpx dashed #ddd;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;
    box-sizing: border-box;
}

.certificate-image {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
}

.certificate-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.certificate-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
}

.certificate-text {
    font-size: 28rpx;
    color: #999;
}

.error-tip {
    font-size: 24rpx;
    color: #ff4d4f;
    margin-top: 10rpx;
    padding: 8rpx 16rpx;
    background-color: #fff2f0;
    border-radius: 8rpx;
    display: inline-block;
}

.submit-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
    color: #fff;
    font-size: 32rpx;
    border-radius: 16rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
}

 uni-button:after {
     border: none !important;
 }

 .modal-overlay {
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     background: rgba(0, 0, 0, 0.5);
    //  display: flex;
    //  align-items: center;
    //  justify-content: center;
     z-index: 1000;
 }

 .legal-scenario-modal {
     width: 100%;
     background: #fff;
     border-radius: 24rpx 24rpx 0 0;
     padding: 40rpx 30rpx 30rpx;
     max-height: 80vh;
     display: flex;
     flex-direction: column;
     position: fixed;
     left: 0;
     bottom: 0;
 }

 .modal-header {
     position: relative;
     display: flex;
     justify-content: center;
     align-items: center;
     margin-bottom: 40rpx;
     padding: 0 60rpx;
 }

 .modal-title {
     font-size: 32rpx;
     font-weight: bold;
     color: #333;
     text-align: center;
 }

 .cancel-btn {
     font-size: 28rpx;
     color: #999;
     position: absolute;
     right: 30rpx;
     top: 50%;
     transform: translateY(-50%);
 }

 .scenario-tags {
     display: flex;
     flex-wrap: wrap;
     gap: 20rpx;
     margin-bottom: 40rpx;
     max-height: 50vh;
     overflow-y: auto;
 }

 .scenario-tag {
     min-width: 200rpx;
     height: 70rpx;
     background-color: #f5f5f5;
     border-radius: 45rpx;
     display: flex;
     align-items: center;
     justify-content: center;
     font-size: 28rpx;
     color: #666;
     flex: 0 0 calc(33.333% - 14rpx);
     box-sizing: border-box;
     transition: all 0.3s;
 }

 .scenario-tag.selected {
     background:#ECF1FE;
     color: #2652C2;
 }

 .confirm-btn {
     width: 100%;
     height: 88rpx;
     background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
     color: #fff;
     font-size: 32rpx;
     border-radius: 16rpx;
     border: none;
     display: flex;
     align-items: center;
     justify-content: center;
 }
 </style>
