﻿<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll width="600px" v-loading="loading">
		<el-row :gutter="15" class="" >
				<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
					<el-col :span="24">
						<el-form-item label="拓客活动" prop="eventId">
							<el-select v-model="dataForm.eventId" placeholder="请选择拓客活动" clearable :style='{"width":"100%"}' filterable >
								<el-option v-for="(item, index) in tkhdOptions" :key="index" :label="item.EventName" :value="item.EventId" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="拓客人员" prop="expansionUserId">
							<user-select v-model="dataForm.expansionUserId" placeholder="请选择" clearable >
							</user-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="24">
						<el-form-item label="拓客时间" prop="expansionTime">
							<el-date-picker v-model="dataForm.expansionTime" placeholder="请选择" :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" readonly disabled >
							</el-date-picker>
						</el-form-item>
					</el-col> -->
					<el-col :span="24">
						<el-form-item label="顾客姓名" prop="customerName">
							<el-input v-model="dataForm.customerName" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="电话号码" prop="customerPhone">
							<el-input v-model="dataForm.customerPhone" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="24">
						<el-form-item label="购买张数" prop="buyNumber">
							<el-input v-model="dataForm.buyNumber" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col> -->
					<el-col :span="24">
						<el-form-item label="支付方式" prop="paymentMethod">
							<el-select v-model="dataForm.paymentMethod" placeholder="请选择" clearable :style='{"width":"100%"}' filterable >
								<el-option v-for="(item, index) in zffsOptions" :key="index" :label="item.fullName" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="是否加微信" prop="isAddWeChat">
							<el-select v-model="dataForm.isAddWeChat" placeholder="请选择" clearable :style='{"width":"100%"}' >
								<el-option v-for="(item, index) in sfjwxOptions" :key="index" :label="item.fullName" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="备注" prop="remarks">
							<el-input v-model="dataForm.remarks" placeholder="请输入" show-word-limit :style='{"width":"100%"}' type='textarea' :autosize='{"minRows":4,"maxRows":4}' >
							</el-input>
						</el-form-item>
					</el-col>
				</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false" :disabled="loading">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail" :loading="loading">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	import { previewDataInterface } from '@/api/systemData/dataInterface'
	import { getLqEventList } from '@/api/extend/lqevent'
	import { UserSettingInfo } from '@/api/permission/userSetting'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
						dataForm: {
							id: undefined,
							eventId: undefined,
							expansionUserId: undefined,
							// expansionTime: this.getCurrentTimestamp(),
							expansionTime: undefined,
							customerName: undefined,
							customerPhone: undefined,
							buyNumber: 1,
							paymentMethod: '微信',
							isAddWeChat: '否',
							remarks: undefined,
						},
				rules: {
					eventId: [
						{ required: true, message: '请选择拓客活动', trigger: 'change' }
					],
					expansionUserId: [
						{ required: true, message: '请选择拓客人员', trigger: 'change' }
					],
					customerName: [
						{ required: true, message: '请输入顾客姓名', trigger: 'blur' }
					],
					customerPhone: [
						{ required: true, message: '请输入电话号码', trigger: 'blur' },
						{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
					],
					buyNumber: [
						{ required: true, message: '请输入购买张数', trigger: 'blur' },
						{ pattern: /^[1-9]\d*$/, message: '请输入正确的购买张数', trigger: 'blur' }
					]
				},
				zffsOptions:[{"fullName":"微信","id":"微信"},{"fullName":"支付宝","id":"支付宝"},{"fullName":"现金","id":"现金"},{"fullName":"银行转账","id":"银行转账"}],
				sfjwxOptions:[{"fullName":"是","id":"是"},{"fullName":"否","id":"否"}],
				tkhdOptions:[],
				userinfo: {},
			}
		},
		computed: {},
        watch: {},
        created() {
			this.int()
		},
		mounted() {
        },
		methods: {
			// 获取当前时间戳
			getCurrentTimestamp() {
				return new Date().getTime()
			},
			int() {
				UserSettingInfo().then(response => {
					this.userinfo = response.data
					this.dataForm.expansionUserId = this.userinfo.id
					this.getTkhdOptions()
				})
			},
			// 获取拓客活动选项
			getTkhdOptions() {
				// 获取当前日期作为查询参数
				const today = new Date()
				const startTime = this.formatDate(today)
				const endTime = this.formatDate(today)
				
				request({
					url: '/api/Extend/lqevent/user/'+this.userinfo.id+'/current',
					method: 'GET'
				}).then(response => {
					if (response.code === 200 && response.data) {
						this.tkhdOptions = response.data || []
						// 默认选择第一个活动
						if (this.tkhdOptions.length > 0 && !this.dataForm.eventId) {
							this.dataForm.eventId = this.tkhdOptions[0].EventId
						}
					}
				})
			},
			
			// 格式化日期为 YYYY-MM-DD 格式
			formatDate(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day} `
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				this.dataForm.id = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					// 如果是新建记录，重新设置当前时间和默认活动
					if (!this.dataForm.id) {
						this.dataForm.expansionTime = this.getCurrentTimestamp()
						// 设置默认活动
						if (this.tkhdOptions.length > 0) {
							this.dataForm.eventId = this.tkhdOptions[0].EventId
						}
					}
					if (this.dataForm.id) {
						this.loading = true
						request({
							url: '/api/Extend/LqTkjlb/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.loading = false
							if (res.code === 200 && res.data) {
								this.dataForm = res.data;
							} else {
								this.$message.error('获取数据失败')
							}
						}).catch(err => {
							this.loading = false
							this.$message.error('获取数据失败，请重试')
							console.error('获取拓客记录详情失败:', err)
						})
					}
				})
			},
			formatTime(time) {
				return new Date(time).toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				})
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						this.loading = true
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/LqTkjlb`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
								this.loading = false
                                this.$message({
                                    message: res.msg || '创建成功',
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
								let tkinfo = res.data;
								let datanew = {
									"webhookUrl": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6f8686ec-5011-4c1d-bae9-d82a2a2f4d83",
									"content": 
`🎉 拓客记录
⏩门店：${tkinfo.storeinfo.Dm}
⏩拓客人员：${this.userinfo.realName || '未知'}
⏩战队：${tkinfo.entity.TeamName || '未知'}
⏩顾客姓名：${this.dataForm.customerName}
⏩电话号码：${this.dataForm.customerPhone}
⏩购买张数：${this.dataForm.buyNumber}
⏩拓客时间：${this.formatTime(tkinfo.entity.ExpansionTime)}
⏩支付方式：${this.dataForm.paymentMethod}
⏩是否加微信：${this.dataForm.isAddWeChat}
⏩备注：${this.dataForm.remarks || ''}`
		
								};
								const resultnew = request({
									url: 'http://wx.lvqianmeiye.com/api/Bot/send-text',
									data: datanew,
									method: 'POST'
								});
                            }).catch(err => {
								console.log(err)
								this.loading = false
								this.$message.error(err?err+'':'创建失败，请重试')
							})
                        } else {
                            request({
                                url: '/api/Extend/LqTkjlb/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
								this.loading = false
                                this.$message({
                                    message: res.msg || '更新成功',
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            }).catch(err => {
								console.log(err)
								this.loading = false
								this.$message.error(err?err+'':'更新失败，请重试')
							})
                        }
                    }
                })
			},
		}
	}
</script>
