<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">
		<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" v-if="false" >
						<el-form-item label="消息编号" prop="ff">
							<el-input v-model="dataForm.ff" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="标题" prop="bt">
							<el-input v-model="dataForm.bt" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="内容" prop="nr">
							<NCC-Quill v-model="dataForm.nr" placeholder="请输入内容..." >
							</NCC-Quill>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="分类" prop="fl">
							<el-select v-model="dataForm.fl" placeholder="请选择" clearable :style='{"width":"100%"}' >
								<el-option v-for="(item, index) in flOptions" :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="tssj">
							<el-date-picker v-model="dataForm.tssj" placeholder="请选择" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
							<div class="form-tip">选择后将按该时间定时发送（需后台定时任务支持，请测试验证）</div>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="接收人（人员）" prop="jsrUserIds">
							<user-select v-model="jsrUserIds" placeholder="可多选人员" clearable multiple />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="接收人（组织/客户公司）" prop="jsrOrganizeIds">
							<NCC-TreeSelect v-model="jsrOrganizeIds" :options="organizeTreeData" placeholder="可多选组织" clearable multiple />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建人" prop="cjr">
							<user-select v-model="dataForm.cjr" placeholder="请选择" clearable >
							</user-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建时间" prop="cjsj">
							<el-date-picker v-model="dataForm.cjsj" placeholder="请选择" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="是否已读" prop="sfyd">
							<el-radio-group v-model="dataForm.sfyd" :style='{}' >
								<el-radio v-for="(item, index) in sfydOptions" :key="index" :label="item.id"  >{{item.fullName}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="阅读时间" prop="ydsj">
							<el-date-picker v-model="dataForm.ydsj" placeholder="请选择" clearable :style='{"width":"100%"}' type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	import { getOrganizeTree } from '@/api/permission/organize'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				jsrUserIds: '',      // 接收人-人员（多选，逗号分隔）
				jsrOrganizeIds: '', // 接收人-组织（多选，逗号分隔）
				organizeTreeData: [],
				dataForm: {
					id:undefined,
					ff:undefined,
					bt:undefined,
					nr:undefined,
					fl:undefined,
					tssj:undefined,
					jsr:undefined,
					cjr:undefined,
					cjsj:undefined,
					sfyd:undefined,
					ydsj:undefined,
				},
				rules: {
				},
				flOptions:[{"fullName":"生日祝福","id":"生日祝福"},{"fullName":"新闻热点","id":"新闻热点"},{"fullName":"技术类","id":"技术类"},{"fullName":"系统问题反馈","id":"系统问题反馈"},{"fullName":"设备问题反馈","id":"设备问题反馈"}],
				sfydOptions:[{"fullName":"是","id":"是"},{"fullName":"否","id":"否"}],
			}
		},
		computed: {},
        watch: {},
        created() {
			getOrganizeTree().then(res => {
				const raw = res.data
				this.organizeTreeData = Array.isArray(raw) ? raw : (raw && Array.isArray(raw.list) ? raw.list : [])
			}).catch(() => { this.organizeTreeData = [] })
		},
		mounted() {
        },
		methods: {
			// 将接口返回的 jsr 解析为人员、组织两个绑定值
			parseJsrToForm(jsr) {
				if (!jsr) {
					this.jsrUserIds = ''
					this.jsrOrganizeIds = ''
					return
				}
				const t = jsr.trim()
				if (t.startsWith('{')) {
					try {
						const o = JSON.parse(t)
						this.jsrUserIds = (o.userIds && Array.isArray(o.userIds)) ? o.userIds.join(',') : ''
						this.jsrOrganizeIds = (o.organizeIds && Array.isArray(o.organizeIds)) ? o.organizeIds.join(',') : ''
					} catch (e) {
						this.jsrUserIds = t
						this.jsrOrganizeIds = ''
					}
				} else {
					this.jsrUserIds = t
					this.jsrOrganizeIds = ''
				}
			},
			// 提交前将人员、组织合并为 jsr JSON
			buildJsrForSubmit() {
				const userIds = (this.jsrUserIds || '').split(',').map(s => s.trim()).filter(Boolean)
				const organizeIds = (this.jsrOrganizeIds || '').split(',').map(s => s.trim()).filter(Boolean)
				if (userIds.length || organizeIds.length) {
					this.dataForm.jsr = JSON.stringify({ userIds, organizeIds })
				} else {
					this.dataForm.jsr = undefined
				}
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				this.dataForm.id = id || 0;
				this.dataForm.ff = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				this.jsrUserIds = '';
				this.jsrOrganizeIds = '';
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						request({
							url: '/api/Extend/Xxtsjl/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							if (this.dataForm.ff) {
								this.dataForm.id = this.dataForm.ff;
							}
							this.parseJsrToForm(this.dataForm.jsr);
						})
					}
				})
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
                        this.buildJsrForSubmit();
                        if (!this.dataForm.id && this.dataForm.ff) {
                            this.dataForm.id = this.dataForm.ff;
                        }
                        if (!this.dataForm.ff && this.dataForm.id) {
                            this.dataForm.ff = this.dataForm.id;
                        }
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/Xxtsjl`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false,
                                            this.$emit('refresh', true)
                                    }
                                })
                            })
                        } else {
                            request({
                                url: '/api/Extend/Xxtsjl/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            })
                        }
                    }
                })
			},
		}
	}
</script>
<style lang="scss" scoped>
.form-tip {
	font-size: 12px;
	color: #909399;
	margin-top: 4px;
}
</style>
