<template>
    <uni-popup ref="popup" :mask-click="false" background-color="white" borderRadius="10px" class="pop">
        <view style="height: 250px; width: 300px; padding: 15px; box-sizing: border-box; display: flex; flex-direction:column; justify-content: space-between; align-items: center;" class="popup-content">
            <input placeholder="联系人姓名" v-model="newContacts.name" style="width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 5px;" />
            <input placeholder="联系方式" v-model="newContacts.phone" style="width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 5px;" />
            <checkbox @click="handleIsDefaultChanges()" :key="newContacts.id"  style="width: auto; margin-top: 10px;">设置为默认联系人</checkbox>
            <view style="width: 100%; display: flex; justify-content: space-between;">
                <button @click="addContact" style="flex: 1; padding: 8px 0; background-color: #007aff; color: white; border: none; border-radius: 5px; margin-right: 5px;">添加</button>
                <button @click="close" style="flex: 1; padding: 8px 0; background-color: #ccc; color: #333; border: none; border-radius: 5px; margin-left: 5px;">取消</button>
            </view>
        </view>
    </uni-popup>
    <uni-popup ref="popup1" :mask-click="false" background-color="white" borderRadius="10px" class="pop">
        <view style="height: 250px; width: 300px; padding: 15px; box-sizing: border-box; display: flex; flex-direction:column; justify-content: space-between; align-items: center;" class="popup-content">
            <input placeholder="联系人姓名" v-model="newContact.name" style="width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 5px;" />
            <input placeholder="联系方式" v-model="newContact.phone" style="width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 5px;" />
            <checkbox @click="handleIsDefaultChanges()" :key="newContacts.id" :checked="newContact.isDefault === 1" style="width: auto; margin-top: 10px;">设置为默认联系人</checkbox>
            <view style="width: 100%; display: flex; justify-content: space-between;">
                <button @click="saveModifiedContact" style="flex: 1; padding: 8px 0; background-color: #007aff; color: white; border: none; border-radius: 5px; margin-right: 5px;">保存</button>
                <button @click="close1" style="flex: 1; padding: 8px 0; background-color: #ccc; color: #333; border: none; border-radius: 5px; margin-left: 5px;">取消</button>
            </view>
        </view>
    </uni-popup>
    <view class="flex-col page">
        <view class="flex-col">
            <view class="flex-row justify-center items-center relative group">
                <text class="text">联系人信息</text>
                <image class="image pos"
                    src="https://ide.code.fun/api/image?token=673329a3c471750012deb1ec&name=888e11f2c452b3d64f79a5136a779376.png" />
            </view>
            <view class="mt-16 flex-col">
                <view class="flex-row justify-between items-center list-item mt-5"
                    v-for="(item, index) in filteredContacts" :key="index">
                    <view class="flex-row items-center">
                        <text class="font ml-9">{{item.name}}</text>
                        <text class="font_2 ml-9">{{item.phone}}</text>
                    </view>
                    <text v-if="item.isDefault === 1" class="font_3 ml-12">默认联系人</text>
                    <view class="flex-row group_2">
                        <image class="image_2"
                            src="https://carbon2.obs.cn-north-4.myhuaweicloud.com:443/feiyi%2Ftest%2F0%2FEclWfXMx-bj.png"
                            @click="editContact(index)" />
                        <image class="ml-12 image_2"
                            src="https://carbon2.obs.cn-north-4.myhuaweicloud.com:443/feiyi%2Ftest%2F0%2FzgFMedLP-sc.png"
                            @click="deleteContact(index)" />
                    </view>
                </view>
            </view>
        </view>
        <view class="flex-col justify-start items-center section mt-431" @click="open">
            <view class="flex-col justify-start items-center text-wrapper"><text class="text_2">添加新联系人</text></view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { baseUrl } from '../../../api/request'
import { onLoad } from "@dcloudio/uni-app";
import { getFonts } from '../../../common/globalFont';

onLoad(() => {
	getFonts()
})

onMounted(() => {
    getContacts()
})

const newContact = ref({
    name: '',
    phone: '',
    isDefault: 0,
    id: 0
})
const newContacts = ref({
    name: '',
    phone: '',
    isDefault: 0,
    id: 0
})

const editContact = async (index) => {
    popup1.value.open('center');
    const contact = filteredContacts.value[index];
    newContact.value = {
        name: contact.name,
        id: contact.id,
        phone: contact.phone,
        isDefault: contact.isDefault
    };
}

const handleIsDefaultChanges = (e) => {
    let currentValue = newContact.value.isDefault;
    let updatedValue = currentValue === 0? 1 : 0;
    newContact.value.isDefault = updatedValue;
    console.log(updatedValue);
}
const handleIsDefaultChange = (e) => {
    //console.log(newContact.value.isDefault)
    let currentValue = newContact.value.isDefault;
    let updatedValue = currentValue === 0? 1 : 0;
    newContact.value.isDefault = updatedValue;
    console.log(updatedValue);
}

// 获取联系人列表
const getContacts = async () => {
    const res = await uni.request({
        url: baseUrl + '/contacts/list',
        method: 'POST',
        header: {
            cookie: wx.getStorageSync('cookie')
        }
    });
    // console.log(res)
    if (res.data.code === 1) {
        const correctContacts = [];
        let defaultContact = null;
        res.data.data.forEach((contact) => {
            if (contact.isDefault === 1) {
                if (!defaultContact) {
                    defaultContact = contact;
                } else {
                    contact.isDefault = 0;
                }
            }
            correctContacts.push(contact);
        });
        filteredContacts.value = correctContacts;
        if (defaultContact) {
            const index = filteredContacts.value.findIndex(
                c => c.id === defaultContact.id
            );
            if (index!== -1) {
                filteredContacts.value[index].isDefault = 1;
            }
        }
    } else {
        uni.showToast({
            icon: 'error',
            title: '获取失败'
        });
    }
}

const searchText = ref('');
const filteredContacts = ref([]);

watch(searchText, () => {
    if (searchText.value === '') {
        filteredContacts.value = contacts.value;
    } else {
        filteredContacts.value = contacts.value.filter(contact => {
            return contact.name.includes(searchText.value) || contact.phone.includes(
                searchText.value)
        });
    }
});

// 添加联系人
const addContact = async () => {
    popup.value.close();
    // 清除之前默认联系人
    if (newContacts.value.isDefault) {
        for (let i = 0; i < filteredContacts.value.length; i++) {
            if (filteredContacts.value[i].isDefault === 1) {
                filteredContacts.value[i].isDefault = 0;
            }
        }
    }
    const res = await uni.request({
        url: baseUrl + '/contacts/add',
        method: 'POST',
        header: {
            cookie: wx.getStorageSync('cookie')
        },
        data: {
            name: newContacts.value.name,
            phone: newContacts.value.phone,
            isDefault: newContacts.value.isDefault
        }
    });
    if (res.data.code === 1) {
        console.log('添加成功');
        newContacts.value = {
            name: '',
            phone: '',
            isDefault: 0,
            id: 0
        };
    } else {
        uni.showToast({
            icon: 'error',
            title: '添加失败'
        });
    }
    getContacts();
}

// 删除联系人
const deleteContact = async (index) => {
    const res = await uni.request({
        url: baseUrl + '/contacts/delete',
        method: 'POST',
        header: {
            cookie: wx.getStorageSync('cookie')
        },
        data: {
            id: filteredContacts.value[index].id,
        }
    });
    console.log(res, '1111111111111');
    if (res.data.code === 1) {
        console.log('删除成功');
    } else {
        uni.showToast({
            icon: 'error',
            title: '删除失败'
        });
    }
    getContacts();
}

const contactToModify = ref({});
const indexToModify = ref(null);

// 更新联系人
const saveModifiedContact = async () => {
    popup1.value.close();
    if (!newContact.value.name ||!newContact.value.phone) {
        uni.showToast({
            icon: 'error',
            title: '不能为空'
        });
        return;
    }
    if (newContact.value.isDefault) {
        for (let i = 0; i < filteredContacts.value.length; i++) {
            if (filteredContacts.value[i].isDefault === 1) {
                filteredContacts.value[i].isDefault = 0;
            }
        }
    }
    const res = await uni.request({
        url: baseUrl + '/contacts/update',
        method: 'POST',
        header: {
            cookie: wx.getStorageSync('cookie')
        },
        data: {
            name: newContact.value.name,
            phone: newContact.value.phone,
            id: newContact.value.id,
            isDefault: newContact.value.isDefault
        }
    });
    if (res.data.code === 1) {
        console.log('更新成功');
        console.log(newContact.value.isDefault, '000000000000000000000000 ');
    } else {
        uni.showToast({
            icon: 'error',
            title: '更新失败'
        });
    }
    getContacts();
}

const popup = ref(null);
const popup1 = ref(null);
const open = () => {
    popup.value.open('center');
}
const open1 = () => {
    popup1.value.open('center');
}
const close = () => {
    popup.value.close();
}
const close1 = () => {
    popup1.value.close();
}
</script>

<style lang="scss" scoped>
	.font_3 {
	    color: #007aff; 
	    font-size: 14px;
	}
	.mt-5 {
		margin-top: 9.38rpx;
	}

	.ml-9 {
		margin-left: 16.88rpx;
	}

	.mt-431 {
		margin-top: 808.13rpx;
	}

	.page {
		padding-top: 18.75rpx;
		background-color: #f5f5dc;
		border-radius: 28.13rpx 28.13rpx 0rpx 0rpx;
		width: 100%;
		overflow-y: auto;
		overflow-x: hidden;
		height: 100%;
	}

	.group {
		padding: 11.25rpx 24.38rpx 7.5rpx;
	}

	.text {
		color: #323232;
		font-size: 37.5rpx;
		font-family: FZSongKeBenXiuKaiS-R-GB;
		line-height: 35.21rpx;
	}

	.image {
		width: 52.5rpx;
		height: 52.5rpx;
	}

	.pos {
		position: absolute;
		right: 24.38rpx;
		top: 50%;
		transform: translateY(-50%);
	}

	.list-item {
		padding: 52.5rpx 15rpx;
		background-color: #fffef8;
		border-bottom: solid 1.88rpx #c8c8c8;
	}

	.list-item:first-child {
		margin-top: 0;
	}

	.image_3 {
		width: 33.75rpx;
		height: 33.75rpx;
	}

	.font {
		font-size: 30rpx;
		font-family: FZSongKeBenXiuKaiS-R-GB;
		line-height: 27.19rpx;
		color: #323232;
	}

	.font_2 {
		font-size: 30rpx;
		font-family: FZSongKeBenXiuKaiS-R-GB;
		line-height: 22.05rpx;
		color: #323232;
	}

	.group_2 {
		margin-right: 11.25rpx;
	}

	.image_2 {
		width: 39.38rpx;
		height: 39.38rpx;
	}

	.section {
		margin-left: 16.88rpx;
		padding: 22.5rpx 0 15rpx;
		background-color: #fffef8;
	}

	.text-wrapper {
		padding: 30rpx 0;
		background-color: #fbb612;
		border-radius: 75rpx;
		width: 639.38rpx;
	}

	.text_2 {
		color: #ffffff;
		font-size: 33.75rpx;
		font-family: FZSongKeBenXiuKaiS-R-GB;
		line-height: 31.22rpx;
	}
   //  .pop{
   //        height: 300px;
		 //  width: 400px;
		 //  padding: 20px;
   //      /* 输入框的通用样式 */
   //      input {
			// margin-left: 10%;
   //          width: 80%; // 占满弹窗宽度，可按需调整
   //          margin-bottom: 15px;
   //          padding: 10px;
   //          border: 1px solid #ccc;
   //          border-radius: 5px;
   //      }
    
   //      /* 复选框的通用样式 */
   //      checkbox {
   //          margin-bottom: 15px;
   //      }
    
   //      /* 按钮的通用样式 */
   //      button {
   //          width: 45%; // 按钮宽度占比，可根据实际调整布局
   //          padding: 8px 0;
   //          border: none;
   //          border-radius: 5px;
   //          font-size: 14px;
   //          cursor: pointer;
   //          transition: background-color 0.3s ease;
   //      }
   //  }
    
   //  /* 第一个弹窗添加联系人的特定按钮样式 */
   //  .pop:first-child button:first-child {
   //      background-color: #007aff;
   //      color: white;
   //  }
    
   //  .pop:first-child button:last-child {
   //      background-color: #ccc;
   //      color: #333;
   //  }
    
   //  /* 第二个弹窗修改联系人的特定按钮样式 */
   //  .pop:last-child button:first-child {
   //      background-color: #4caf50;
   //      color: white;
   //  }
    
   //  .pop:last-child button:last-child {
   //      background-color: #ccc;
   //      color: #333;
   //  }
	@import url(/common/css/global.css);
</style>
