<template>
    <u-modal 
        :show="visible" 
        title="推送短信"
        :show-cancel-button="true"
        :showCancelButton="true"
        :show-confirm-button="true"
        :showConfirmButton="true"
        confirmText="确定"
        cancelText="关闭"
        @confirm="handleSubmit"
        @cancel="handleCancel"
        @close="handleCancel"
        width="650rpx"
    >
        <view class="modal-content">
            <u-form 
                ref="formRef"
                :model="form" 
                :rules="rules"
                labelWidth="120"
                labelPosition="top"
            >
                <u-form-item label="短信类型" prop="type" required>
                    <u-radio-group 
                        v-model="form.type" 
                        placement="column"
                        @change="handleChangeType"
                    >
                        <u-radio 
                            v-for="item in smsContentList"
                            :key="item.type"
                            :name="item.type"
                            :label="item.typeName"
                        ></u-radio>
                    </u-radio-group>
                </u-form-item>
                
                <u-form-item label="短信预览" prop="remark" required>
                    <u-textarea 
                        v-model="form.remark"
                        placeholder="请输入短信预览"
                        :disabled="true"
                        :rows="4"
                        count
                    ></u-textarea>
                </u-form-item>
                
                <u-form-item label="推送历史">
                    <view class="sms-history">
                        <view v-if="smsRecords.length === 0" class="no-data">
                            <text>暂无推送记录</text>
                        </view>
                        <view v-else class="history-list">
                            <view 
                                v-for="(record, index) in smsRecords" 
                                :key="record.id || index"
                                class="history-item"
                            >
                                <view class="history-header">
                                    <text class="sender">{{ record.createName }}</text>
                                    <text class="time">{{ record.createTime }}</text>
                                    <text 
                                        class="status" 
                                        :class="record.status == 1 ? 'success' : 'fail'"
                                    >
                                        {{ record.status == 1 ? '成功' : '失败' }}
                                    </text>
                                </view>
                                <view class="history-content">
                                    <text>{{ record.smsContent }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </u-form-item>
            </u-form>
        </view>
    </u-modal>
</template>

<script setup>
import { ref, reactive, nextTick, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const emit = defineEmits(['success']);

/** 弹窗是否打开 */
const visible = defineModel({ type: Boolean });

/** 表单引用 */
const formRef = ref();

/** SMS记录数据 */
const smsRecords = ref([]);

const form = reactive({
    orderId: null,
    type: '',
    remark: ''
});

/** 短信内容列表 */
const smsContentList = ref([]);

/** 短信类型改变 */
const handleChangeType = (val) => {
    const selectedItem = smsContentList.value.find(item => item.type === val);
    if (selectedItem) {
        form.remark = selectedItem.smsContent;
    }
};

/** 表单验证规则 */
const rules = reactive({
    type: [
        {
            required: true,
            message: '请选择短信类型',
            trigger: 'change'
        }
    ],
    remark: [
        {
            required: true,
            message: '请输入短信预览',
            trigger: 'blur'
        }
    ]
});

/** 关闭弹窗 */
const handleCancel = () => {
    visible.value = false;
    resetForm();
};

/** 重置表单 */
const resetForm = () => {
    form.orderId = null;
    form.type = '';
    form.remark = '';
    smsRecords.value = [];
    smsContentList.value = [];
    formRef.value?.resetFields();
};

/** 弹窗打开事件 */
const handleOpen = (orderId) => {
    resetForm();
    if (orderId) {
        console.log('打开短信弹窗，订单ID:', orderId);
        visible.value = true;
        getSmsLogInfo(orderId);
    }
};

/** 获取短信记录信息 */
const getSmsLogInfo = (orderId) => {
    uni.$u.http.get(`/app/orderinfo/orderSmsLog/${orderId}`).then((res) => {
        if (res.code === 200) {
            let data = res.data || {};
            form.orderId = data.orderId;
            smsRecords.value = data.smsLogList || [];
            smsContentList.value = data.smsContentList || [];
        } else {
            uni.$u.toast(res.msg || '获取短信记录失败');
        }
    }).catch((err) => {
        console.error('获取短信记录失败:', err);
        uni.$u.toast('获取短信记录失败');
    });
};

/** 提交表单 */
const handleSubmit = () => {
    formRef.value?.validate().then(valid => {
        if (!valid) return;
        
        uni.$u.http.post('/app/orderinfo/orderSmsLogSend', {
            orderId: form.orderId,
            type: form.type
        }).then((res) => {
            if (res.code == 200) {
                uni.$u.toast('短信发送成功');
                emit('success');
                handleCancel();
            } else {
                uni.$u.toast(res.msg || '短信发送失败');
            }
        }).catch((err) => {
            console.error('短信发送失败:', err);
            uni.$u.toast('短信发送失败');
        });
    }).catch(err => {
        console.log('表单验证失败:', err);
    });
};

defineExpose({
    handleOpen
});
</script>

<style lang="scss" scoped>
.modal-content{
    max-height: 72vh;
    overflow: auto;
}
.sms-history {
    .no-data {
        text-align: center;
        color: #999;
        padding: 40rpx 0;
    }
    
    .history-list {
        .history-item {
            margin-bottom: 20rpx;
            padding: 20rpx;
            background-color: #f8f9fa;
            border-radius: 8rpx;
            border-left: 4rpx solid #409eff;
            
            .history-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10rpx;
                
                .sender {
                    font-size: 28rpx;
                    font-weight: bold;
                    color: #333;
                }
                
                .time {
                    font-size: 24rpx;
                    color: #666;
                }
                
                .status {
                    font-size: 24rpx;
                    padding: 4rpx 8rpx;
                    border-radius: 4rpx;
                    
                    &.success {
                        background-color: #67c23a;
                        color: white;
                    }
                    
                    &.fail {
                        background-color: #f56c6c;
                        color: white;
                    }
                }
            }
            
            .history-content {
                font-size: 26rpx;
                line-height: 1.5;
                color: #666;
            }
        }
    }
}

/* 自定义单选框样式 */
:deep(.u-radio-group) {
    .u-radio {
        margin-bottom: 20rpx;
    }
}
</style> 