<template>
    <view class="con-body">
        <view class="con-bg">
            <!-- 头部 -->
            <customHeader ref="customHeaderRef" :title="'走访报告添加'" :leftFlag="true" :rightFlag="true">
                <template #right>
                    <view class="head-right" @click="submitForm">
                        <uni-icons custom-prefix="iconfont" type="icon-phonebaocun" size="22"
                            color="#B7D2FF"></uni-icons>保存
                    </view>
                </template>
            </customHeader>

            <!-- 高度来避免头部遮挡 -->
            <view class="top-height"></view>

            <!-- 正文内容 -->
            <view class="white-bg">
                <view class="form-con">
                    <uni-forms ref="formRef" :model="formData"  label-width="100px">
                        <view @click="addVisistReport" class="form-item-container">
                            <uni-forms-item label="客户名称" name="cusName" class="f-c-right">
                                <text class="name">{{ formData.cusName }}</text>
                            </uni-forms-item>
                        </view>

                        <uni-forms-item label="签到记录" class="f-c-right">
                            <!-- <view class="f-c-text txt-right">--</view> -->
                            <view class="cu-form-group">
                                <view class="title">签到记录</view>
                            </view>
                        </uni-forms-item>

                        <view class="choose">
                            <radio-group @change="chooseRecord">
                                <label class="radio" v-for="(item, index) in records" :key="index">
                                    <view class="record-container">
                                        <radio :value="item.mapId" :checked="index === current" class="radio-style" />
                                        <view class="record-content">
                                            <view class="info-row">
                                                <text class="label">开始时间：</text>
                                                <text class="value">{{ item.goVisistStartTime }}</text>
                                            </view>
                                            <view class="info-row">
                                                <text class="label">开始地点：</text>
                                                <text class="value">{{ item.addressForStart }}</text>
                                            </view>
                                            <view class="info-row">
                                                <text class="label">结束时间：</text>
                                                <text class="value">{{ item.goVisistEndTime }}</text>
                                            </view>
                                            <view class="info-row">
                                                <text class="label">结束地点：</text>
                                                <text class="value">{{ item.addressForEnd }}</text>
                                            </view>
                                            <view class="info-row" v-if="item.remark != null">
                                                <text class="label">备注：</text>
                                                <text class="value">{{ item.remark }}</text>
                                            </view>
                                        </view>
                                    </view>
                                </label>
                            </radio-group>
                        </view>



                        <uni-forms-item label="我方领导" name="leader"
                            class="uni-forms-item is-direction-top is-top">

                            <multipleSelect :multiple="true" :value="chooseMyLeaderList" downInner
                                :options="myLeaderList" 
                                @change="changeValue2" :key="Math.round()" 
                                :slabel="'text'"
                            >
                            </multipleSelect>
                        </uni-forms-item>


                        <uni-forms-item label="走访日期" name="visitDate" class="uni-forms-item is-direction-top is-top">
                            <uni-datetime-picker :start="threeDaysAgoTimestamp" :end="todayTimestamp" type="date"
                                :clear-icon="true" v-model="formData.visitDate" @change="changeDate" />
                        </uni-forms-item>
                    </uni-forms>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, reactive, onUnmounted, computed } from 'vue'
import customHeader from '@/components/customHeader.vue'
import MultipleSelect from "../../../../components/multipleSelect.vue";
import { addMapForReport, addVisist } from '../../../../api/crm/activity/activity';
// import{ getGuestList} from '@/api/business.js'
let customerUser = reactive({})

//我方领导
const myLeaderList = [
    { value: 0, text: "姜海洋" },
    { value: 1, text: "曾炀" },
    { value: 2, text: "杨博" },
    { value: 3, text: "廖明君" },
    { value: 4, text: "唐海岩" },
    { value: 4, text: "赵飞" }
];
// 表单ref
const formRef = ref(null);

// 表单数据
const formData = ref({
    cusId: null,
    cusName: '',
    leader: '',
    visitDate: ''
});

// 我方人员
let chooseMyLeaderList = reactive([0]);
const changeValue2 = (item, value) => {
    chooseMyLeaderList = item;
    formData.value.leader = chooseMyLeaderList
};


// 修改日期
let changeDate = (e) => {
    console.log('changeDate:', e);
};

// 保存走访报告
let saveVisistReportForm = reactive({});
const submitForm = async () => {
    try {
        // 验证表单
        await formRef.value.validate();
        // 验证通过后的操作
        uni.showToast({
            title: '验证通过',
            icon: 'success'
        });
        saveVisistReportForm.cusId = formData.value.cusId
        if (Array.isArray(formData.value.leader)) {
          saveVisistReportForm.joinUser = formData.value.leader.map(item => item.text).join(',');
        }
        saveVisistReportForm.visistDate = formData.value.visitDate
        saveVisistReportForm.visistType = 'I类活动（走访）'
        saveVisistReportForm.mapId = mapId.value
        addVisist(saveVisistReportForm).then(
            res => {
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        duration: 2000
                    });
                    setTimeout(function () {
                        uni.navigateBack({
                            success: () => { }
                        })
                    }, 500);
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none',
                    });
                }
            },
        );

    } catch (err) {
        console.log('表单验证失败:', err);
    }
};

//日期禁用
const todayTimestamp = computed(() => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    return today.getTime()
});

const threeDaysAgoTimestamp = computed(() => {
    const date = new Date()
    date.setDate(date.getDate() - 3)
    date.setHours(0, 0, 0, 0)
    return date.getTime()
});


//选择客户
function addVisistReport() {
    uni.navigateTo({
        url: './chooseCus'
    })
}
//定义数据接收的值
let selectedCustomer = reactive(null)

//监听时间
onMounted(() => {
    uni.$on('onCustomerSelected', handleCustomerSelected)
})
//取消监听
onUnmounted(() => {
    uni.$off('onCustomerSelected', handleCustomerSelected)
})

//处理 接收数据
const handleCustomerSelected = (data) => {
    formData.value.cusName = data.cusName
    formData.value.cusId = data.cusId
}

//查询签到记录
onMounted(() => {
    recordList()
})
let records = ref([])
//走访记录列表
function recordList() {
    addMapForReport().then(
        res => {
            if (res.code == 200) {
                records.value = res.rows;
                // that.$forceUpdate()
            } else {
                uni.showToast({
                    icon: 'none',
                    title: "请求失败",
                });
            }
        },
        rej => { }
    );
}

//选择签到记录
let mapId = ref()
function chooseRecord(e) {
    mapId.value = e.detail.value
}


</script>

<style scoped>
.white-bg {
    width: 750rpx;
    padding: 30rpx 0 0;
    margin-bottom: 0;
    border-radius: 8px 8px 0 0;
}

.form-con {
    /* #ifdef APP-PLUS */
    height: calc(100vh - 95px) !important;
    /* #endif */
    /* #ifndef APP-PLUS */
    height:calc(100vh - 68px) !important;
    /* #endif */
}

:deep(.uni-date-x) {
    display: block;
}

:deep(.uni-date-x .icon-calendar) {
    float: right;
    margin-top: 15rpx;
    margin-right: 20rpx;
    background: url('../../../static/images/business/icon-date.png') no-repeat;
    background-size: 32rpx 35rpx;
    width: 32rpx;
    height: 35rpx;
}

:deep(.uni-date-x .icon-calendar::before) {
    display: none;
}

:deep(.uni-date-x .uni-date__x-input) {
    padding-left: 20rpx;
    color: #919191;
}

.form-item-container .uni-forms-item {
    display: flex;
    align-items: center;
    /* 垂直居中 */
}

/* 确保 text 元素也垂直居中 */
.form-item-container .name {
    line-height: normal;
    /* 避免 line-height 影响 */
    display: flex;
    align-items: center;
}

/*======*/
.choose {
    padding: 20rpx;
}

.record-container {
    display: flex;
    align-items: flex-start;
    padding: 20rpx;
    margin-bottom: 20rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.radio-style {
    margin-right: 20rpx;
    margin-top: 8rpx;
}

.record-content {
    flex: 1;
}

.info-row {
    display: flex;
    margin-bottom: 10rpx;
    line-height: 1.4;
}

.label {
    width: 160rpx;
    font-weight: bold;
    color: #333;
    flex-shrink: 0;
}

.value {
    flex: 1;
    color: #666;
    word-break: break-all;
}
</style>
