<template>
    <FloatPanel
        ref="floatPanel"
        :title="isEdit ? '编辑账号' : '新增账号'"
        position="right"
        :show-back="true"
        back-text="返回"
        @back="handleBack"
    >
        <template #header-right>
            <Button type="primary" @click="handleSave" :loading="saving">保存</Button>
        </template>

        <div class="account-edit-form">
            <Form ref="form" :model="formData" :rules="rules" :label-width="120">
                <!-- 基本信息 -->
                <Card title="基本信息" style="margin-bottom: 16px;">
                    <FormItem label="账户名" prop="name">
                        <Input v-model="formData.name" placeholder="请输入账户名" />
                    </FormItem>
                    <FormItem label="设备SN码" prop="sn_code">
                        <Input v-model="formData.sn_code" placeholder="请输入设备SN码" />
                    </FormItem>
                    <FormItem label="平台" prop="platform_type">
                        <Select v-model="formData.platform_type" placeholder="请选择平台">
                            <Option value="1">Boss直聘</Option>
                            <Option value="2">猎聘</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="登录名" prop="login_name">
                        <Input v-model="formData.login_name" placeholder="请输入登录名" />
                    </FormItem>
                    <FormItem label="密码" prop="pwd">
                        <Input v-model="formData.pwd" type="password" placeholder="请输入密码" />
                    </FormItem>
                    <FormItem label="搜索关键词">
                        <Input v-model="formData.keyword" placeholder="请输入搜索关键词" />
                    </FormItem>
                </Card>

                <!-- 编辑时才显示的配置项 -->
                <template v-if="isEdit">
                    <Card title="基础配置" style="margin-bottom: 16px;">
                        <FormItem label="启用状态">
                            <i-switch v-model="formData.is_enabled" :true-value="1" :false-value="0" />
                        </FormItem>
                        <FormItem label="职位类型">
                            <Select v-model="formData.job_type_id" placeholder="请选择职位类型" clearable>
                                <Option v-for="item in jobTypeOptions" :key="item.value" :value="item.value">
                                    {{ item.label }}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem label="用户地址">
                            <Input v-model="formData.user_address" placeholder="请输入用户地址，如：北京市朝阳区" />
                        </FormItem>
                    </Card>

                    <Card title="授权信息" style="margin-bottom: 16px;">
                        <FormItem label="授权日期">
                            <DatePicker
                                v-model="formData.authorization_date"
                                type="date"
                                placeholder="请选择授权日期（不选择则使用当前时间）"
                                style="width: 100%;"
                                format="yyyy-MM-dd"
                            />
                        </FormItem>
                        <FormItem label="授权天数">
                            <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                                <InputNumber
                                    v-model="formData.authorization_days"
                                    :min="0"
                                    placeholder="请输入授权天数"
                                    style="width: 200px;"
                                />
                                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                    <Button size="small" @click="setAuthorizationDays(7)">7天</Button>
                                    <Button size="small" @click="setAuthorizationDays(30)">30天</Button>
                                    <Button size="small" @click="setAuthorizationDays(90)">90天</Button>
                                    <Button size="small" @click="setAuthorizationDays(180)">180天</Button>
                                    <Button size="small" @click="setAuthorizationDays(365)">365天</Button>
                                </div>
                            </div>
                        </FormItem>
                        <FormItem label="剩余天数" v-if="formData.remaining_days !== undefined">
                            <span :style="{ color: getRemainingDaysColor(formData.remaining_days) }">
                                {{ formData.remaining_days || 0 }} 天
                            </span>
                        </FormItem>
                        <FormItem label="过期时间" v-if="formData.authorization_date && formData.authorization_days">
                            <span :style="{ color: getExpireDateColor(formData) }">
                                {{ getExpireDate(formData) }}
                            </span>
                        </FormItem>
                    </Card>

                    <Card title="排序优先级配置" style="margin-bottom: 16px;">
                        <FormItem label="排序优先级">
                            <div class="priority-config">
                                <div v-for="(item, index) in priorityList" :key="item.key" class="priority-item">
                                    <div class="priority-label">
                                        <Icon type="ios-menu" class="drag-handle" />
                                        <span>{{ getPriorityLabel(item.key) }}</span>
                                    </div>
                                    <div class="priority-control">
                                        <Slider
                                            v-model="item.weight"
                                            :min="0"
                                            :max="100"
                                            :step="1"
                                            show-input
                                            :show-tooltip="true"
                                            style="width: 200px; margin-right: 16px;"
                                        />
                                        <span class="priority-value">{{ item.weight }}%</span>
                                    </div>
                                </div>
                                <div class="priority-total">
                                    <span>总权重：<strong :class="{'weight-warning': totalWeight !== 100}">{{ totalWeight }}%</strong></span>
                                    <Button v-if="totalWeight !== 100" type="text" size="small" @click="normalizeWeights">自动平衡</Button>
                                </div>
                            </div>
                        </FormItem>
                    </Card>

                    <Card title="自动投递配置" style="margin-bottom: 16px;">
                        <FormItem label="自动投递">
                            <RadioGroup v-model="formData.auto_deliver">
                                <Radio :label="1">开启</Radio>
                                <Radio :label="0">关闭</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem label="投递间隔(分钟)">
                            <InputNumber v-model="formData.deliver_interval" :min="1" placeholder="默认30分钟" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="最低薪资(元)">
                            <InputNumber v-model="formData.min_salary" :min="0" placeholder="0表示不限制" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="最高薪资(元)">
                            <InputNumber v-model="formData.max_salary" :min="0" placeholder="0表示不限制" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="滚动页数">
                            <InputNumber v-model="formData.page_count" :min="1" placeholder="默认3次" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="每次最多投递数">
                            <InputNumber v-model="formData.max_deliver" :min="1" placeholder="默认10个" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="过滤关键词">
                            <Input v-model="formData.filter_keywords" placeholder="包含这些关键词的职位会被优先考虑，多个用逗号分隔" />
                        </FormItem>
                        <FormItem label="排除关键词">
                            <Input v-model="formData.exclude_keywords" placeholder="包含这些关键词的职位会被排除，多个用逗号分隔" />
                        </FormItem>
                        <FormItem label="投递开始时间">
                            <Input v-model="formData.deliver_start_time" placeholder="格式：HH:mm，如：09:00" />
                        </FormItem>
                        <FormItem label="投递结束时间">
                            <Input v-model="formData.deliver_end_time" placeholder="格式：HH:mm，如：18:00" />
                        </FormItem>
                        <FormItem label="是否仅工作日">
                            <RadioGroup v-model="formData.deliver_workdays_only">
                                <Radio :label="1">仅工作日</Radio>
                                <Radio :label="0">包含周末</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Card>

                    <Card title="自动沟通配置" style="margin-bottom: 16px;">
                        <FormItem label="自动沟通">
                            <RadioGroup v-model="formData.auto_chat">
                                <Radio :label="1">开启</Radio>
                                <Radio :label="0">关闭</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem label="沟通间隔(分钟)">
                            <InputNumber v-model="formData.chat_interval" :min="1" placeholder="默认30分钟" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="是否沟通外包岗位">
                            <RadioGroup v-model="formData.is_chat_outsourcing">
                                <Radio :label="1">是</Radio>
                                <Radio :label="0">否</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem label="沟通开始时间">
                            <Input v-model="formData.chat_start_time" placeholder="格式：HH:mm，如：09:00" />
                        </FormItem>
                        <FormItem label="沟通结束时间">
                            <Input v-model="formData.chat_end_time" placeholder="格式：HH:mm，如：18:00" />
                        </FormItem>
                        <FormItem label="是否仅工作日">
                            <RadioGroup v-model="formData.chat_workdays_only">
                                <Radio :label="1">仅工作日</Radio>
                                <Radio :label="0">包含周末</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Card>

                    <Card title="自动活跃配置" style="margin-bottom: 16px;">
                        <FormItem label="自动活跃">
                            <RadioGroup v-model="formData.auto_active">
                                <Radio :label="1">开启</Radio>
                                <Radio :label="0">关闭</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem label="活跃间隔(分钟)">
                            <InputNumber v-model="formData.active_interval" :min="1" placeholder="默认60分钟" style="width: 100%;" />
                        </FormItem>
                        <FormItem label="活跃动作配置">
                            <Input
                                v-model="formData.active_actions_json"
                                type="textarea"
                                :rows="4"
                                placeholder='JSON格式的活跃动作列表，如：[{"type":"view","count":5}]'
                            />
                        </FormItem>
                    </Card>
                </template>
            </Form>
        </div>
    </FloatPanel>
</template>

<script>
import plaAccountServer from '@/api/profile/pla_account_server.js'
import jobTypesServer from '@/api/work/job_types_server.js'

export default {
    name: 'PlaAccountEdit',
    props: {
        jobTypeOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            isEdit: false,
            saving: false,
            formData: {
                id: null,
                name: '',
                sn_code: '',
                platform_type: '',
                login_name: '',
                pwd: '',
                keyword: '',
                // 编辑时才有的字段
                is_enabled: 1,
                job_type_id: null,
                user_address: '',
                is_salary_priority: '',
                auto_deliver: 0,
                deliver_interval: 30,
                min_salary: 0,
                max_salary: 0,
                page_count: 3,
                max_deliver: 10,
                filter_keywords: '',
                exclude_keywords: '',
                deliver_start_time: '09:00',
                deliver_end_time: '18:00',
                deliver_workdays_only: 1,
                auto_chat: 0,
                chat_interval: 30,
                is_chat_outsourcing: 0,
                chat_start_time: '09:00',
                chat_end_time: '18:00',
                chat_workdays_only: 1,
                auto_active: 0,
                active_interval: 60,
                active_actions_json: '',
                // 授权相关字段
                authorization_date: null,
                authorization_days: 0,
                remaining_days: 0
            },
            // 排序优先级列表
            priorityList: [
                { key: 'distance', weight: 50 },
                { key: 'salary', weight: 20 },
                { key: 'work_years', weight: 10 },
                { key: 'education', weight: 20 }
            ],
            rules: {
                name: [{ required: true, message: '请填写账户名', trigger: 'blur' }],
                sn_code: [{ required: true, message: '请填写设备SN码', trigger: 'blur' }],
                platform_type: [{ required: true, message: '请选择平台', trigger: 'change' }],
                login_name: [{ required: true, message: '请填写登录名', trigger: 'blur' }]
            },
            jobTypeOptions: []
        }
    },
    mounted() {
        this.loadJobTypes()
    },
    methods: {
        // 显示新增表单
        showAdd() {
            this.isEdit = false
            this.resetForm()
            this.$refs.floatPanel.show()
        },
        // 显示编辑表单
        showEdit(row) {
            this.isEdit = true
            this.resetForm()
            
            // 复制基础字段（包含 id）
            this.formData.id = row.id
            this.formData.name = row.name || ''
            this.formData.sn_code = row.sn_code || ''
            this.formData.platform_type = row.platform_type || ''
            this.formData.login_name = row.login_name || ''
            this.formData.pwd = row.pwd || ''
            this.formData.keyword = row.keyword || ''
            
            // 复制编辑字段
            this.formData.is_enabled = row.is_enabled !== undefined ? row.is_enabled : 1
            this.formData.job_type_id = row.job_type_id || null
            this.formData.user_address = row.user_address || ''
            
            // 处理 JSON 配置字段
            this.processJsonFields(row)
            
            this.$refs.floatPanel.show()
        },
        // 处理 JSON 配置字段
        processJsonFields(row) {
            // 处理授权信息
            if (row.authorization_date) {
                this.formData.authorization_date = new Date(row.authorization_date)
            } else {
                // 如果没有授权日期，默认使用当天
                this.formData.authorization_date = new Date()
            }
            this.formData.authorization_days = row.authorization_days || 0
            this.formData.remaining_days = row.remaining_days || 0
            
            // is_salary_priority 配置
            if (row.is_salary_priority) {
                const priorityConfig = typeof row.is_salary_priority === 'string'
                    ? JSON.parse(row.is_salary_priority)
                    : row.is_salary_priority
                // 更新优先级列表
                if (Array.isArray(priorityConfig)) {
                    this.priorityList = priorityConfig.map(item => ({
                        key: item.key,
                        weight: item.weight || 0
                    }))
                }
            } else {
                // 使用默认值
                this.priorityList = [
                    { key: 'distance', weight: 50 },
                    { key: 'salary', weight: 20 },
                    { key: 'work_years', weight: 10 },
                    { key: 'education', weight: 20 }
                ]
            }
            
            // deliver_config 配置
            if (row.deliver_config) {
                const deliverConfig = typeof row.deliver_config === 'string'
                    ? JSON.parse(row.deliver_config)
                    : row.deliver_config
                this.formData.deliver_interval = deliverConfig.deliver_interval || 30
                this.formData.min_salary = deliverConfig.min_salary || 0
                this.formData.max_salary = deliverConfig.max_salary || 0
                this.formData.page_count = deliverConfig.page_count || 3
                this.formData.max_deliver = deliverConfig.max_deliver || 10
                this.formData.filter_keywords = Array.isArray(deliverConfig.filter_keywords)
                    ? deliverConfig.filter_keywords.join(',')
                    : (deliverConfig.filter_keywords || '')
                this.formData.exclude_keywords = Array.isArray(deliverConfig.exclude_keywords)
                    ? deliverConfig.exclude_keywords.join(',')
                    : (deliverConfig.exclude_keywords || '')
                // 处理时间区间配置
                if (deliverConfig.time_range) {
                    this.formData.deliver_start_time = deliverConfig.time_range.start_time || '09:00'
                    this.formData.deliver_end_time = deliverConfig.time_range.end_time || '18:00'
                    this.formData.deliver_workdays_only = deliverConfig.time_range.workdays_only !== undefined ? deliverConfig.time_range.workdays_only : 1
                }
            }
            
            // chat_strategy 配置
            if (row.chat_strategy) {
                const chatStrategy = typeof row.chat_strategy === 'string'
                    ? JSON.parse(row.chat_strategy)
                    : row.chat_strategy
                this.formData.chat_interval = chatStrategy.chat_interval || 30
                this.formData.is_chat_outsourcing = chatStrategy.is_chat_outsourcing !== undefined ? chatStrategy.is_chat_outsourcing : 0
                if (chatStrategy.time_range) {
                    this.formData.chat_start_time = chatStrategy.time_range.start_time || '09:00'
                    this.formData.chat_end_time = chatStrategy.time_range.end_time || '18:00'
                    this.formData.chat_workdays_only = chatStrategy.time_range.workdays_only !== undefined ? chatStrategy.time_range.workdays_only : 1
                }
            }
            
            // active_actions 配置
            if (row.active_actions) {
                const activeActions = typeof row.active_actions === 'string'
                    ? JSON.parse(row.active_actions)
                    : row.active_actions
                this.formData.active_interval = activeActions.active_interval || 60
                this.formData.active_actions_json = JSON.stringify(activeActions.actions || [], null, 2)
            } else {
                this.formData.active_actions_json = JSON.stringify([], null, 2)
            }
        },
        // 重置表单
        resetForm() {
            this.formData = {
                id: null,
                name: '',
                sn_code: '',
                platform_type: '',
                login_name: '',
                pwd: '',
                keyword: '',
                is_enabled: 1,
                job_type_id: null,
                user_address: '',
                is_salary_priority: '',
                auto_deliver: 0,
                deliver_interval: 30,
                min_salary: 0,
                max_salary: 0,
                page_count: 3,
                max_deliver: 10,
                filter_keywords: '',
                exclude_keywords: '',
                auto_chat: 0,
                chat_interval: 30,
                is_chat_outsourcing: 0,
                chat_start_time: '09:00',
                chat_end_time: '18:00',
                chat_workdays_only: 1,
                auto_active: 0,
                active_interval: 60,
                active_actions_json: JSON.stringify([], null, 2)
            }
            // 重置优先级列表
            this.priorityList = [
                { key: 'distance', weight: 50 },
                { key: 'salary', weight: 20 },
                { key: 'work_years', weight: 10 },
                { key: 'education', weight: 20 }
            ]
            this.$nextTick(() => {
                if (this.$refs.form) {
                    this.$refs.form.resetFields()
                }
            })
        },
        // 获取过期时间
        getExpireDate(formData) {
            if (!formData.authorization_date || !formData.authorization_days) {
                return '未授权'
            }
            const authDate = new Date(formData.authorization_date)
            const expireDate = new Date(authDate.getTime() + formData.authorization_days * 24 * 60 * 60 * 1000)
            const year = expireDate.getFullYear()
            const month = String(expireDate.getMonth() + 1).padStart(2, '0')
            const day = String(expireDate.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        // 获取过期时间颜色
        getExpireDateColor(formData) {
            const remainingDays = formData.remaining_days || 0
            if (remainingDays <= 0) {
                return '#ed4014'
            } else if (remainingDays <= 7) {
                return '#ff9900'
            } else {
                return '#515a6e'
            }
        },
        // 获取剩余天数颜色
        getRemainingDaysColor(remainingDays) {
            if (!remainingDays || remainingDays <= 0) {
                return '#ed4014'
            } else if (remainingDays <= 7) {
                return '#ff9900'
            } else {
                return '#19be6b'
            }
        },
        // 设置授权天数（快捷按钮）
        setAuthorizationDays(days) {
            this.formData.authorization_days = days
            // 如果没有设置授权日期，自动设置为当前日期
            if (!this.formData.authorization_date) {
                this.formData.authorization_date = new Date()
            }
            // 计算剩余天数（如果已有授权日期）
            if (this.formData.authorization_date && days > 0) {
                const authDate = new Date(this.formData.authorization_date)
                const expireDate = new Date(authDate.getTime() + days * 24 * 60 * 60 * 1000)
                const now = new Date()
                const remaining = Math.ceil((expireDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000))
                this.formData.remaining_days = Math.max(0, remaining)
            }
            this.$Message.success(`已设置授权天数为 ${days} 天`)
        },
        // 返回
        handleBack() {
            this.$refs.floatPanel.hide()
        },
        // 保存
        async handleSave() {
            // 验证表单
            this.$refs.form.validate(async (valid) => {
                if (!valid) {
                    this.$Message.error('请填写必填项')
                    return
                }
                
                this.saving = true
                try {
                    const saveData = this.buildSaveData()
                    
                    if (this.isEdit) {
                        await plaAccountServer.update(saveData)
                    } else {
                        await plaAccountServer.add(saveData)
                    }
                    
                    this.$Message.success('保存成功！')
                    this.$refs.floatPanel.hide()
                    this.$emit('on-save')
                } catch (error) {
                    console.error('保存失败:', error)
                    this.$Message.error('保存失败：' + (error.message || '请稍后重试'))
                } finally {
                    this.saving = false
                }
            })
        },
        // 构建保存数据
        buildSaveData() {
            const saveData = { ...this.formData }
            
            // 新增时只需要基础字段
            if (!this.isEdit) {
                return {
                    name: saveData.name,
                    sn_code: saveData.sn_code,
                    platform_type: saveData.platform_type,
                    login_name: saveData.login_name,
                    pwd: saveData.pwd,
                    keyword: saveData.keyword
                }
            }
            
            // 编辑时需要处理所有字段
            // 处理 is_salary_priority（从 priorityList 生成）
            saveData.is_salary_priority = this.priorityList.map(item => ({
                key: item.key,
                weight: Number(item.weight) || 0
            }))
            
            // 处理 deliver_config
            const deliverConfig = {}
            deliverConfig.deliver_interval = Number(saveData.deliver_interval) || 30
            deliverConfig.min_salary = Number(saveData.min_salary) || 0
            deliverConfig.max_salary = Number(saveData.max_salary) || 0
            deliverConfig.page_count = Number(saveData.page_count) || 3
            deliverConfig.max_deliver = Number(saveData.max_deliver) || 10
            deliverConfig.filter_keywords = typeof saveData.filter_keywords === 'string' && saveData.filter_keywords.trim()
                ? saveData.filter_keywords.split(',').map(k => k.trim()).filter(k => k)
                : []
            deliverConfig.exclude_keywords = typeof saveData.exclude_keywords === 'string' && saveData.exclude_keywords.trim()
                ? saveData.exclude_keywords.split(',').map(k => k.trim()).filter(k => k)
                : []
            // 处理时间区间配置
            deliverConfig.time_range = {
                start_time: saveData.deliver_start_time || '09:00',
                end_time: saveData.deliver_end_time || '18:00',
                workdays_only: saveData.deliver_workdays_only ? 1 : 0
            }
            saveData.deliver_config = deliverConfig
            delete saveData.deliver_interval
            delete saveData.min_salary
            delete saveData.max_salary
            delete saveData.page_count
            delete saveData.max_deliver
            delete saveData.filter_keywords
            delete saveData.exclude_keywords
            delete saveData.deliver_start_time
            delete saveData.deliver_end_time
            delete saveData.deliver_workdays_only
            
            // 处理 chat_strategy
            const chatStrategy = {}
            chatStrategy.chat_interval = Number(saveData.chat_interval) || 30
            chatStrategy.is_chat_outsourcing = saveData.is_chat_outsourcing ? 1 : 0
            chatStrategy.time_range = {
                start_time: saveData.chat_start_time || '09:00',
                end_time: saveData.chat_end_time || '18:00',
                workdays_only: saveData.chat_workdays_only ? 1 : 0
            }
            saveData.chat_strategy = chatStrategy
            delete saveData.chat_interval
            delete saveData.is_chat_outsourcing
            delete saveData.chat_start_time
            delete saveData.chat_end_time
            delete saveData.chat_workdays_only
            
            // 处理 active_actions
            const activeActions = {}
            activeActions.active_interval = Number(saveData.active_interval) || 60
            if (saveData.active_actions_json) {
                try {
                    activeActions.actions = typeof saveData.active_actions_json === 'string'
                        ? JSON.parse(saveData.active_actions_json)
                        : saveData.active_actions_json
                    if (!Array.isArray(activeActions.actions)) {
                        activeActions.actions = []
                    }
                } catch (e) {
                    console.error('解析活跃动作配置失败:', e)
                    this.$Message.warning('活跃动作配置格式错误，将使用空数组')
                    activeActions.actions = []
                }
            } else {
                activeActions.actions = []
            }
            saveData.active_actions = activeActions
            delete saveData.active_interval
            delete saveData.active_actions_json
            
            return saveData
        },
        // 加载职位类型
        async loadJobTypes() {
            try {
                const res = await jobTypesServer.getAll()
                if (res.code === 0 && res.data) {
                    this.jobTypeOptions = res.data.map(item => ({
                        value: item.id,
                        label: item.name
                    }))
                }
            } catch (err) {
                console.error('加载职位类型失败:', err)
            }
        },
        // 获取优先级标签
        getPriorityLabel(key) {
            const labelMap = {
                'distance': '距离',
                'salary': '薪资',
                'work_years': '工作年限',
                'education': '学历'
            }
            return labelMap[key] || key
        },
        // 自动平衡权重
        normalizeWeights() {
            const total = this.totalWeight
            if (total === 0) {
                // 如果总权重为0，平均分配
                const avgWeight = Math.floor(100 / this.priorityList.length)
                this.priorityList.forEach(item => {
                    item.weight = avgWeight
                })
                // 处理余数
                const remainder = 100 - (avgWeight * this.priorityList.length)
                if (remainder > 0 && this.priorityList.length > 0) {
                    this.priorityList[0].weight += remainder
                }
            } else {
                // 按比例缩放
                this.priorityList.forEach(item => {
                    item.weight = Math.round((item.weight / total) * 100)
                })
                // 确保总和为100
                const newTotal = this.priorityList.reduce((sum, item) => sum + item.weight, 0)
                if (newTotal !== 100 && this.priorityList.length > 0) {
                    const diff = 100 - newTotal
                    this.priorityList[0].weight += diff
                }
            }
        }
    },
    computed: {
        // 计算总权重
        totalWeight() {
            return this.priorityList.reduce((sum, item) => sum + (Number(item.weight) || 0), 0)
        }
    }
}
</script>

<style scoped>
.account-edit-form {
    padding: 16px;
    height: 100%;
    overflow-y: auto;
}

.priority-config {
    padding: 16px;
    background: #f8f8f9;
    border-radius: 4px;
}

.priority-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    margin-bottom: 12px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #e8eaec;
}

.priority-item:last-child {
    margin-bottom: 0;
}

.priority-label {
    display: flex;
    align-items: center;
    min-width: 120px;
    font-weight: 500;
    color: #515a6e;
}

.drag-handle {
    margin-right: 8px;
    color: #c5c8ce;
    cursor: move;
}

.priority-control {
    display: flex;
    align-items: center;
    flex: 1;
    max-width: 400px;
}

.priority-value {
    min-width: 50px;
    text-align: right;
    color: #2d8cf0;
    font-weight: 500;
}

.priority-total {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e8eaec;
    font-size: 14px;
}

.weight-warning {
    color: #ed4014;
}
</style>

