<template>
    <AppLayout back-gorund-color="#F4F4F4">

        <!-- 联系人列表 -->
        <view class="contacts-section">
            <view v-for="(contact, index) in contactList" :key="contact.tempId || contact.id" class="contact-item">
                <view class="contact-header">
                    <text class="contact-title">联系人{{ index + 1 }}</text>
                    <view class="contact-actions" v-if="contactList.length > 1">
                        <view class="action-btn delete-btn" @click="deleteContact(index)">
                            <uni-icons type="trash" size="16" color="#FF4D4F"></uni-icons>
                            <text class="action-text">删除</text>
                        </view>
                    </view>
                </view>
                
                <view class="contact-form">
                    <view class="form-item">
                        <view class="form-label">联系人姓名</view>
                        <input 
                            class="form-input" 
                            v-model="contact.contactPerson" 
                            placeholder="请输入联系人姓名"
                            @blur="validateContactName(index)"
                        />
                    </view>
                    
                    <view class="form-item">
                        <view class="form-label">联系电话</view>
                        <input 
                            class="form-input" 
                            v-model="contact.contactPersonPhone" 
                            placeholder="请输入联系电话"
                            type="number"
                            @blur="validateContactPhone(index)"
                        />
                    </view>
                </view>
            </view>
        </view>

        <!-- 添加联系人按钮 -->
        <view class="add-contact-section" v-if="contactList.length < 3">
            <view class="add-contact-btn btn-feel" @click="addContact">
                <uni-icons type="plus" size="20" color="#256BFA"></uni-icons>
                <text class="add-text">添加联系人</text>
            </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-section">
            <view class="save-btn btn-feel" @click="saveContacts">
                <text class="save-text">保存联系人</text>
            </view>
        </view>

        <!-- 提示信息 -->
        <view class="tips-section">
            <view class="tips-title">温馨提示</view>
            <view class="tips-content">
                <text class="tips-item">• 至少需要保留一个联系人，最多可添加3个联系人</text>
                <text class="tips-item">• 联系人姓名和电话为必填项</text>
                <text class="tips-item">• 联系电话请填写正确的手机号码</text>
            </view>
        </view>
    </AppLayout>
</template>

<script setup>
import { reactive, inject, ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import AppLayout from '@/components/AppLayout/AppLayout.vue';
import { createRequest } from '@/utils/request.js';

const { navTo } = inject('globalFunction');

// 联系人列表数据
const contactList = reactive([]);
let tempIdCounter = 0; // 用于生成临时ID

// 页面加载时获取联系人数据
onLoad((options) => {
    // 从缓存获取企业联系人信息
    loadContactsFromCache();
});

// 从缓存加载联系人数据
function loadContactsFromCache() {
    try {
        const cachedUserInfo = uni.getStorageSync('userInfo') || {};
        if (cachedUserInfo.company && cachedUserInfo.company.companyContactList) {
            const contacts = cachedUserInfo.company.companyContactList;
            
            // 如果联系人列表为空，至少添加一个空联系人
            if (contacts.length === 0) {
                contactList.push(createEmptyContact());
            } else {
                // 为每个联系人添加临时ID（如果没有ID的话）
                contacts.forEach(contact => {
                    if (!contact.tempId) {
                        contact.tempId = `temp_${++tempIdCounter}`;
                    }
                    contactList.push({ ...contact });
                });
            }
        } else {
            // 如果没有联系人数据，创建一个空联系人
            contactList.push(createEmptyContact());
        }
    } catch (error) {
        console.error('加载联系人数据失败:', error);
        // 出错时至少创建一个空联系人
        contactList.push(createEmptyContact());
    }
}

// 创建空联系人
function createEmptyContact() {
    return {
        id: '',
        contactPerson: '',
        contactPersonPhone: '',
        tempId: `temp_${++tempIdCounter}`
    };
}

// 添加联系人
function addContact() {
    if (contactList.length >= 3) {
        uni.showToast({
            title: '最多只能添加3个联系人',
            icon: 'none'
        });
        return;
    }
    
    contactList.push(createEmptyContact());
}

// 删除联系人
function deleteContact(index) {
    if (contactList.length <= 1) {
        uni.showToast({
            title: '至少需要保留一个联系人',
            icon: 'none'
        });
        return;
    }
    
    uni.showModal({
        title: '确认删除',
        content: '确定要删除这个联系人吗？',
        success: (res) => {
            if (res.confirm) {
                contactList.splice(index, 1);
            }
        }
    });
}

// 验证联系人姓名
function validateContactName(index) {
    const contact = contactList[index];
    if (!contact.contactPerson || contact.contactPerson.trim() === '') {
        uni.showToast({
            title: '请输入联系人姓名',
            icon: 'none'
        });
        return false;
    }
    return true;
}

// 验证联系人电话
function validateContactPhone(index) {
    const contact = contactList[index];
    if (!contact.contactPersonPhone || contact.contactPersonPhone.trim() === '') {
        uni.showToast({
            title: '请输入联系电话',
            icon: 'none'
        });
        return false;
    }
    
    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(contact.contactPersonPhone)) {
        uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
        });
        return false;
    }
    return true;
}

// 验证所有联系人
function validateAllContacts() {
    for (let i = 0; i < contactList.length; i++) {
        if (!validateContactName(i) || !validateContactPhone(i)) {
            return false;
        }
    }
    return true;
}

// 保存联系人
async function saveContacts() {
    // 验证所有联系人信息
    if (!validateAllContacts()) {
        return;
    }
    
    try {
        uni.showLoading({
            title: '保存中...',
            mask: true
        });
        
        // 获取companyId
        const companyId = getCompanyIdFromCache();
        if (!companyId) {
            uni.showToast({
                title: '获取企业信息失败，请重新登录',
                icon: 'none'
            });
            return;
        }
        
        // 准备API数据，移除临时ID，添加companyId
        const apiData = contactList.map(contact => ({
            id: contact.id || '',
            contactPerson: contact.contactPerson.trim(),
            contactPersonPhone: contact.contactPersonPhone.trim(),
            companyId: companyId
        }));
        
        // 调用API保存联系人
        const response = await createRequest(
            '/app/companycontact/batchInsertUpdate',
            {
                companyContactList: apiData
            },
            'POST',
            false
        );
        
        if (response.code === 200) {
            // 保存成功，更新本地缓存
            updateLocalCache(apiData);
            
            uni.showToast({
                title: '保存成功',
                icon: 'success'
            });
            
            // 延迟返回上一页
            setTimeout(() => {
                goBack();
            }, 1500);
        } else {
            uni.showToast({
                title: response.msg || '保存失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('保存联系人失败:', error);
        uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
        });
    } finally {
        uni.hideLoading();
    }
}

// 从缓存获取companyId
function getCompanyIdFromCache() {
    try {
        const cachedUserInfo = uni.getStorageSync('userInfo') || {};
        if (cachedUserInfo.company && cachedUserInfo.company.companyId) {
            return cachedUserInfo.company.companyId;
        }
        return null;
    } catch (error) {
        console.error('获取companyId失败:', error);
        return null;
    }
}

// 更新本地缓存
function updateLocalCache(contactData) {
    try {
        const cachedUserInfo = uni.getStorageSync('userInfo') || {};
        if (cachedUserInfo.company) {
            cachedUserInfo.company.companyContactList = contactData;
            uni.setStorageSync('userInfo', cachedUserInfo);
        }
    } catch (error) {
        console.error('更新本地缓存失败:', error);
    }
}

// 返回上一页
function goBack() {
    uni.navigateBack();
}
</script>

<style lang="stylus" scoped>
.save-section {
    margin: 0 20rpx 20rpx;
    
    .save-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88rpx;
        background: #256BFA;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 20rpx rgba(37, 107, 250, 0.3);
        
        .save-text {
            font-size: 32rpx;
            color: #FFFFFF;
            font-weight: 600;
        }
    }
}

.contacts-section {
    margin: 20rpx;
    
    .contact-item {
        background: #FFFFFF;
        border-radius: 20rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
        
        .contact-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 30rpx 30rpx 20rpx;
            border-bottom: 1rpx solid #F5F5F5;
            
            .contact-title {
                font-size: 28rpx;
                font-weight: 600;
                color: #333333;
            }
            
            .contact-actions {
                display: flex;
                align-items: center;
                
                .action-btn {
                    display: flex;
                    align-items: center;
                    padding: 8rpx 16rpx;
                    border-radius: 8rpx;
                    
                    &.delete-btn {
                        background: #FFF2F0;
                        
                        .action-text {
                            font-size: 24rpx;
                            color: #FF4D4F;
                            margin-left: 8rpx;
                        }
                    }
                }
            }
        }
        
        .contact-form {
            padding: 20rpx 30rpx 30rpx;
            
            .form-item {
                margin-bottom: 30rpx;
                
                &:last-child {
                    margin-bottom: 0;
                }
                
                .form-label {
                    font-size: 26rpx;
                    color: #6C7282;
                    margin-bottom: 16rpx;
                }
                
                .form-input {
                    width: 100%;
                    height: 80rpx;
                    background: #F8F9FA;
                    border: 1rpx solid #E9ECEF;
                    border-radius: 12rpx;
                    padding: 0 20rpx;
                    font-size: 28rpx;
                    color: #333333;
                    box-sizing: border-box;
                    
                    &:focus {
                        border-color: #256BFA;
                        background: #FFFFFF;
                    }
                }
            }
        }
    }
}

.add-contact-section {
    margin: 0 20rpx 20rpx;
    
    .add-contact-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88rpx;
        background: #FFFFFF;
        border: 2rpx dashed #256BFA;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
        
        .add-text {
            font-size: 28rpx;
            color: #256BFA;
            margin-left: 12rpx;
        }
    }
}

.tips-section {
    margin: 0 20rpx 40rpx;
    padding: 30rpx;
    background: #F8F9FA;
    border-radius: 20rpx;
    
    .tips-title {
        font-size: 26rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 20rpx;
    }
    
    .tips-content {
        .tips-item {
            display: block;
            font-size: 24rpx;
            color: #6C7282;
            line-height: 1.6;
            margin-bottom: 8rpx;
            
            &:last-child {
                margin-bottom: 0;
            }
        }
    }
}

.btn-feel {
    transition: transform 0.2s ease;
    
    &:active {
        transform: scale(0.98);
    }
}
</style>
