<template>
	<view class="addPost">
		<u-navbar ref="uNavbar" :border-bottom="false" :back-icon-color="setNav.backColor" :is-back="setNav.isdisPlayNavTitle"
		 :title-size="setNav.size" :title-bold="setNav.bold" :title="setNav.navTitle" :title-color="setNav.color" :background="setNav"></u-navbar>
		<view class="content">
			<view class="title">
				<view class="lable">发文字号</view>
				<view class="text" @click="onShowZihao()">查看近期发文字号</view>
			</view>
			<view class="list">
				<textarea placeholder-style="color:#AAAAAA;font-size: 28rpx;" style="height:146rpx;width:calc(100% - (10px + 5px) * 2);;background: #EDEDED;color:#333;font-size: 28rpx;padding: 30rpx;border-radius: 6rpx;"
				 v-model="fixedData.message_code" placeholder="请输入发文字号" />
				</view>
			<view class="title">
				<view class="lable">发文日期</view>
				<u-input @click="onShowTime()" class="input" v-model="fixedData.message_time" placeholder-style="{color:#AAAAAA}" input-align="right" placeholder="请选择发文日期" type="text" :border="false" disabled />
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="title" @click="selectFile('text_data')">
				<view class="lable">正文上传</view>
				<view class="select">请选择pdf格式文件上传</view>
				<image class="black" src="/static/img/black.png" mode=""></image>
			</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<view class="title">
				<view class="lable">正文上传</view>
				<lsj-upload
					ref="lsjUpload"
					childId="upload"
					:size="10"
					style="width: 100%;"
					v-model="percent"
					@input="onInput"
					@callback="onCallback($event,'text_data')">
					<view class="title" >
						<view class="select">请选择文件</view>
						<image class="black" src="/static/img/black.png" mode=""></image>
					</view>
				</lsj-upload>
			</view>
			<!-- #endif -->
			<view class="uptEext" v-if="text_data.length > 0">
				<view class="item" v-for="(item, index) in text_data" :key="index">
					<view class="text">{{item.name}}</view>
					<image class="icon_sc_close" src="/static/img/icon_sc_close.png" mode="" @click="delFile('text_data', index)"></image>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="title"  @click="selectFile('enclosure_data')">
				<view class="lable">附件上传</view>
				<view class="select">请选择文件</view>
				<image class="black" src="/static/img/black.png" mode=""></image>
			</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<view class="title">
				<view class="lable">附件上传</view>
				<lsj-upload
					ref="lsjUploadS"
					childId="upload"
					:size="10"
					style="width: 100%;"
					v-model="percent2"
					@input="onInput"
					@callback="onCallback($event,'enclosure_data')">
					<view class="title" >
						<view class="select">请选择文件</view>
						<image class="black" src="/static/img/black.png" mode=""></image>
					</view>
				</lsj-upload>
				<!-- <uni-file-picker @select="selectAPP($event,'enclosure_data')" limit="1" file-mediatype="all"></uni-file-picker> -->
			</view>
			<!-- #endif -->
			<view class="uptEexts" v-if="enclosure_data.length > 0">
				<view class="item"  v-for="(item, index) in enclosure_data" :key="index">
					<image class="icon_sc_wj" src="/static/img/icon_sc_wj.png" mode=""></image>
					<view class="text">{{item.name}}</view>
					<image class="icon_sc_close" src="/static/img/icon_sc_close.png" mode="" @click="delFile('enclosure_data', index)"></image>
				</view>
			</view>
			<view class="title">
				<view class="lable">文件标题</view>
				<u-input class="input" v-model="fixedData.message_title" placeholder-style="{color:#AAAAAA}" input-align="right" placeholder="请输入文件标题" type="text" :border="false" />
			</view>
			<view class="title" @click="selectPeople">
				<view class="lable">分发人员</view>
				<view class="select">请选择分发人员</view>	
				<image class="black" src="/static/img/black.png" mode=""></image>
			</view>
			<view class="list">
				<view class="renyuan">
					<view class="tip" v-if="selectData.length">
						<text v-for="(item, index) in selectData" :key="index">{{item.nickName}}{{index == (selectData.length - 1) ? '' : ','}}</text>
					</view>
					<view class="tip" v-else>请选择分发人员</view>
				</view>
			</view>
			<view class="title">
				<view class="lable">分发单位</view>
				<view class="select" style="color: #343434;" @click="getDeptNameAndRoleName">请选择上方分发人员</view>
				<!-- <image class="black" src="/static/img/black.png" mode=""></image> -->
			</view>
			<view class="list">
				<view class="renyuan">
					
					<view class="tip" v-if="deptNameList.length">
						<text v-for="(item, index) in deptNameList" :key="index">{{item}}{{index == (deptNameList.length - 1) ? '' : ','}}</text>
					</view>
					<view class="tip" v-else>请选择上方分发人员</view>
				</view>
			</view>
			<view class="title">
				<view class="lable">备注</view>
			</view>
			<view class="list">
				<textarea v-model="fixedData.message_remark" placeholder-style="color:#AAAAAA;font-size: 28rpx;" style="height:146rpx;width:calc(100% - (10px + 5px) * 2);;background: #EDEDED;color:#333;font-size: 28rpx;padding: 30rpx;border-radius: 6rpx;" placeholder="请输入备注"/>
			</view>
			<view class="btnBox" @click="complexSave">提交</view>
			<view class="tipBtn">* 请仔细阅读发文信息后再提交</view>
		</view>
		<!-- 近期字号 -->
		<u-popup v-model="showZihao" mode="center" width="80%" border-radius="6" height="800">
			<view class="showZihao">
				<view class="ziTitle">
					<image class="icon_tc_close" src="/static/img/icon_tc_close.png" mode="" style="opacity: 0;"></image>
					<view class="text">近期发文字号</view>
					<image class="icon_tc_close" src="/static/img/icon_tc_close.png" mode="" @click="onShowZihao()"></image>
				</view>
				<view class="itemBox">
					<scroll-view class="scroll-view_H" scroll-x="true" @scroll="scroll" scroll-left="120" style="height: 550rpx;">
						<view class="item" v-for="(item,index) in csQueryListData" :key="index" @click="onCopy(index,item.message_code)">
							<view class="ld"></view>
							<view class="text" :class="index == copyIndex?'active':''">{{item.message_code}}</view>
						</view>
					</scroll-view>
				</view>
				<view class="btn" @click="ckCopy()">复制发文字号</view>
			</view>
		</u-popup>
		<!-- 时间 -->
		<u-picker mode="time" v-model="showTime" :params="params" @confirm="getTime"></u-picker>
	</view>
</template>

<script>
	// import upload from '@/components/pretty-uploadFile/pretty-uploadFile.vue'
	// import upload from '@/components/uni-file-picker/uni-file-picker.vue'
	export default {
		components: {
			// upload
		},
		data() {
			return {
				percent: '',
				percent2: '',
				setNav:{
					backgroundColor:'#fff',  //背景色
					color:'#333',  //字体颜色
					bold: true,
					size: '36',
					backColor: '#333',
					isdisPlayNavTitle: true, //是否显示返回按钮
					navTitle:'填写发文信息' //导航标题
				},
				fromData: {
					table: 'boman_message',
					objId: -1,
					message_time:''
				},
				fixedData: {
					message_code: '',
					message_title: '',
					message_remark: '',
					send_time: '',
					message_situation: '1',
					send_user_id: '',
					send_user_name: '',
					create_dept_nam: '',
					message_time: '',
					message_upload: [],
					message_id: 'fk.boman_message'
				},
				textareaVal: '',
				showZihao: false,
				queryListPageNo: 1,
				csQueryListData: [],
				copyIndex: null,
				ckCopyData: '',
				showTime: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				text_data: [],
				enclosure_data: [],
				userInfo: {},
				isGo: false,
				selectData: [],
				deptNameList: [],
				tableInfo: {},
				objId: '',
				isLogin: false,
				isWixin: false,
				tmpId: []
			}
		},
		onLoad(options) {
			this.objId = options.objId && options.objId != 'undefined' ? options.objId : ''
			if (this.objId) {
				this.getOneMap()
				this.getChldren()
			}
			uni.removeStorageSync('selectData')
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
			this.fixedData.send_user_id = this.userInfo.id
			this.fixedData.send_user_name = this.userInfo.userName
			this.fixedData.create_dept_nam = this.userInfo.dept.deptName
			this.getCsQueryList()
			this.tableInfo = JSON.parse(uni.getStorageSync('byTableInfo') || '{}')
			// #ifdef MP-WEIXIN
				this.isWixin = true
			// #endif
			
		},
		onShow() {
			let selectData = JSON.parse(uni.getStorageSync('selectData') || '[]')
			this.selectData = selectData
			console.log(selectData)
			if (selectData && selectData.length) {
				this.getDeptNameAndRoleName()
			}
			
		},
		onReady() {
			this.onCreate();
		},
		methods: {
			onCreate() {
				// 初始化参数并创建上传DOM
				this.$refs.lsjUpload.create({
					// #ifdef APP-PLUS
					cuWebview: this.$mp.page.$getAppWebview(), // app必传
					// #endif
					url: 'https://qsjyoa.qs163.cn/prod-api/boman-file/upload', //替换为你的接口地址
					name: 'file', // 附件key
					size: 10, // 附件上传大小上限(M)，默认10M
					debug: true,
					//根据你接口需求自定义请求头
					formData: {
						filename: ''
					}, 
					header: {
						'Authorization': uni.getStorageSync('authToken')
					},
			});
			this.$refs.lsjUploadS.create({
					// #ifdef APP-PLUS
					cuWebview: this.$mp.page.$getAppWebview(), // app必传
					// #endif
					url: 'https://qsjyoa.qs163.cn/prod-api/boman-file/upload', //替换为你的接口地址
					name: 'file', // 附件key
					size: 10, // 附件上传大小上限(M)，默认10M
					debug: true,
					//根据你接口需求自定义请求头
					formData: {
						filename: ''
					}, 
					header: {
						'Authorization': uni.getStorageSync('authToken')
					},
			});
		},
		onInput(e) {
			uni.showLoading({
				mask: true,
				title: '文件上传中'
			})
		},
		onCallback(e,type) {
			let files = JSON.parse(e.responseText)
			if (files.code == 200) {
				if (type == 'text_data') {
					this.fixedData.message_title = files.data.name.substring(0, files.data.name.indexOf('.'))
				}
				this[type].push(files.data)
			}
			uni.hideLoading()
		},
			selectAPP(e,type) {
				console.log(e)
				uni.showLoading({
					mask: true,
					title: '文件上传中'
				})
				uni.uploadFile({
					url: 'https://qsjyoa.qs163.cn/prod-api/boman-file/upload',
					filePath: e.tempFilePaths[0],
					name: 'file',
					formData: {
						filename: e.tempFiles[0].name
					}, 
					header: {
						'Authorization': uni.getStorageSync('authToken')
					},
					success: resFile => {
						let files = JSON.parse(resFile.data)
						if (files.code == 200) {
							if (type == 'text_data') {
								this.fixedData.message_title = files.data.name.substring(0, files.data.name.indexOf('.'))
							}
							this[type].push(files.data)
						}
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			onShowZihao() {
				this.showZihao = !this.showZihao
			},
			async getCsQueryList () {
				let that = this
				let data = { 
					"table": "boman_message", 
					"orderBy": 
					"create_time desc", 
					"pageSize": 10, 
					"pageNo": that.queryListPageNo, 
					"showData": [ "message_code" ] ,
				}
				let res = await that.$u.post(`boman-web-core/p/cs/queryList`,data)
				that.csQueryListData = res.data.rows
			},
			async getOneMap () {
				let that = this
				let data = { 
					"table": "boman_message",
					"fixedData": {
					    "id": this.objId
					}
				}
				let res = await that.$u.post(`boman-web-core/p/cs/one/map`,data)
				
				if (res.code == 200) {
					let {message_code, message_time, message_title, message_remark, send_time, message_upload = "", message_enclosure = ""} = res.data
					this.fixedData.message_code = message_code
					this.fixedData.message_time = message_time
					this.fixedData.message_title = message_title
					this.fixedData.message_remark = message_remark
					this.fixedData.send_time = send_time
					if (message_upload) {
						this.text_data = JSON.parse(message_upload)
					}
					if (message_enclosure) {
						this.enclosure_data = JSON.parse(message_enclosure)
					}
				}
			},
			async getChldren () {
				let that = this
				let data = {
					"table": "boman_message_receive",
					"pageNo": 1,
					"isUi": false,
					"pageSize": 1000,
					"orderBy": "create_time desc",
					"fixedData": {
					    "condition": {
					        "visible": "Y",
					        "message_id": this.objId,
					        "is_del":"N"
					    }
					}
				}
				let res = await that.$u.post(`boman-web-core/p/cs/queryList`,data)
				if (res.code == 200) {
					this.deptNameList = []
					this.selectData = res.data.rows.map(item => {
						this.deptNameList.push(item.receive_dept_name)
						return {
							userName: item.receive_user_name,
							deptName: item.receive_dept_name,
							id: item.receive_user_id
						}
					})
					// if (selectData && selectData.length) {
					// 	this.getDeptNameAndRoleName()
					// }
				}
			},
			onCopy(index,val) {
				this.copyIndex = index
				this.ckCopyData = val
			},
			ckCopy() {
				this.fixedData.message_code = this.ckCopyData
				this.showZihao = false
				// uni.setClipboardData({
				//     data: this.ckCopyData ,
				//     success: function () {
				//         uni.showToast({
				//         	icon: 'none',
				// 			title: '已复制'
				//         })
				//     }
				// });
			},
			async complexSave () {
				if (this.isLogin) {
					return
				}
				if (!this.fixedData.message_time) {
					return uni.showToast({
						title: '请选择发文日期',
						icon: 'none'
					})
				}
				// if (!this.text_data.length) {
				// 	return uni.showToast({
				// 		title: '请上传正文',
				// 		icon: 'none'
				// 	})
				// }
				if (!this.selectData.length) {
					return uni.showToast({
						title: '请选择分发人员',
						icon: 'none'
					})
				}
				
				this.isLogin = true
				uni.showLoading({
					title: '发文中...'
				})
				let json = Object.assign({}, this.fixedData, {
					send_time: this.setTime(),
					has_annex: "N",
					message_upload: JSON.stringify(this.text_data.concat(this.enclosure_data))
				})
				let children = []
				if (this.selectData.length) {
					children = this.selectData.map((item, index) => {
						return {
							"table": 'boman_message_receive',
							"objId":  -1, //this.objId ||
							"from_dept_name": this.fixedData.create_dept_nam,
							"fixedData": {
								"message_id": "fk.boman_message",
								"send_message_time": json.send_time,
								// 'message_situation': '1',
								// "create_dept_name": this.fixedData.create_dept_nam,
								"receive_user_id": item.id,
								"receive_user_name": item.nickName,
								"receive_dept_name": item.dept.deptName,
								"send_user_id": json.send_user_id,
								"from_dept_name": json.create_dept_nam,
								"message_title": json.message_title,
								"send_user_name": json.send_user_name
							}
						}
					})
				}
				let res = await this.$u.post(`boman-web-core/p/cs/complex/save`, {
					"table": "boman_message",
					"objId":  -1, // this.objId ||
					"create_dept_name": this.fixedData.create_dept_nam,
					"fixedData": json,
					children
					
				})
				if (res.code == 200) {
					
					let ress = await this.$u.post(`jflow/p/c/process/launch`, {
						"businessCodes": res.data[0].data, 
						"businessType": this.tableInfo.id, 
						"businessTypeName": this.tableInfo.tableName, 
						"dbname": this.tableInfo.tableName, 
						"initiator": this.fixedData.send_user_id, 
						"userName": this.fixedData.send_user_name
					})
					if (ress.resultCode == 0) {
						uni.showToast({
							title: '发文成功',
						})
						setTimeout(() => {
							uni.switchTab({
							  url: `/pages/tabbar/index/index`,    //要跳转的路径
							})
						}, 1500)
						
					}
					this.isLogin = false
					uni.hideLoading()
				} else {
					uni.showToast({
						title: '发文错误，联系管理员',
						icon: 'none'
					})
					this.isLogin = false
					uni.hideLoading()
				}
			}, 
			async getDeptNameAndRoleName () {
				if (!this.selectData.length) {
					return uni.showToast({
						title: '请选择分发人员',
						icon: 'none'
					})
				}
			
				let res = await this.$u.post(`system/user/getDeptNameAndRoleName`, this.selectData)
				if (res.nikeNameList) {
					this.deptNameList = res.nikeNameList
				}
			},
			setTime () {
			  let dateTime
			  let yy = new Date().getFullYear()
			  let mm = new Date().getMonth() + 1
			  let dd = new Date().getDate()
			  let hh = new Date().getHours()
			  let mf = new Date().getMinutes() < 10 ? ('0' + new Date().getMinutes())
				:
				new Date().getMinutes()
			  let ss = new Date().getSeconds() < 10 ? ('0' + new Date().getSeconds())
				:
				new Date().getSeconds()
			  dateTime = yy + '-' + (mm < 10 ? ('0' + mm) : mm) + '-' + (dd < 10 ? ('0' + dd) : dd) + ' ' + (hh < 10 ? ('0' + hh) : hh) + ':' + (mf < 10 ? ('0' + mf) : mf) + ':' + (ss < 10 ? ('0' + ss) : ss)
			  return dateTime
			},
			onShowTime() {
				this.showTime = !this.showTime
			},
			getTime(e) {
				// console.log(e);
				this.fixedData.message_time = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`
			},
			selectPeople () {
				uni.navigateTo({
					url: '/pages/postView/selectPeople/index'
				})
			},
			delFile (type, index) {
				this[type].splice(index, 1)
				this[type] = JSON.parse(JSON.stringify(this[type]))
			},
			selectFile (type) {
				let chooseFile = uni.chooseFile;
				if (typeof wx !== 'undefined' &&
				    typeof wx.chooseMessageFile === 'function') {
				    chooseFile = wx.chooseMessageFile;
				}
				if (typeof chooseFile !== 'function') {
				    return uni.showToast({
				    	title: '请指定 type 类型，该平台仅支持选择 image 或 video。',
						icon:'none',
				    })
				}
				chooseFile({
					  count: 1,
					  type: 'all',
					  success: (res) => {
					    // tempFilePath可以作为img标签的src属性显示图片
					    const tempFilePaths = res.tempFiles
						if (tempFilePaths && tempFilePaths.length) {
							// if (tempFilePaths[0].path.indexOf('.pdf') != -1) {
								uni.showLoading({
									mask: true,
									title: '文件上传中'
								})
								uni.uploadFile({
									url: 'https://qsjyoa.qs163.cn/prod-api/boman-file/upload',
									filePath: tempFilePaths[0].path,
									name: 'file',
									formData: {
										filename: tempFilePaths[0].name
									}, 
									header: {
										'Authorization': uni.getStorageSync('authToken')
									},
									success: resFile => {
										uni.hideLoading()
										let files = JSON.parse(resFile.data)
										if (files.code == 200) {
											if (type == 'text_data') {
												this.fixedData.message_title = files.data.name.substring(0, files.data.name.indexOf('.'))
											}
											this[type].push(files.data)
										}
									}
								})
							// } else {
							// 	uni.showToast({
							// 		title: '请选择pdf文件',
							// 		icon:'none',
							// 	})
							// }
						}
					  },
					  fail: (res) => {
						  // uni.showToast({
						  // 	title: res.errMsg,
						  // 	icon:'none',
						  // })
					  }
				})
			},
			getPdf() {
				uni.chooseImage({
					count: 1, //默认100
					success: function (res) {
						uni.uploadFile({
							url: 'https://qsjyoa.qs163.cn/prod-api/boman-file/upload', //仅为示例，非真实的接口地址
							filePath: res.tempFilePaths[0],
							name: 'file',
							header: {
								Authorization: uni.getStorageSync('authToken')
							},
							success: (uploadFileRes) => {
								console.log(uploadFileRes.data);
							},
							complete: (err) => {
								console.log(err);
							}
						});
				    }
				});
			}
		}
	}
</script>
<style>
	page{
		background: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
.content{
	padding: 30rpx;
	.title{
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-weight: 500;
		padding: 30rpx 0 0 0;
		.lable{
			font-size: 28rpx;
			color: #343434;
			flex:  0 0 120rpx;
		}
		.text{
			font-size: 26rpx;
			color: #0099FF;
		}
		.input{
			font-size: 28rpx;
		}
		.select {
			color: #aaa;
			font-size: 28rpx;
			flex: 1;
			text-align: right;
		}
		.black{
			width: 15rpx;
			height: 26rpx;
			margin-left: 20rpx;
		}
	}
	.list{
		margin-top: 30rpx;
		.textarea{
			background: #EDEDED;
			border-radius: 8rpx;
			padding: 20rpx 30rpx !important;
		}
		.renyuan{
			background: #EDEDED;
			border-radius: 8rpx;
			min-height: 186rpx;
			padding: 20rpx 30rpx !important;
			color: #AAAAAA;
		}
	}
	.uptEext{
		margin-top: 30rpx;
		.item{
			font-size: 26rpx;
			color: #0099FF;
			margin-bottom: 20rpx;
			display: flex;
			&:last-child{
				margin-bottom: 0;
			}
			.text{
				flex: 1;
				margin-right: 30rpx;
			}
			.icon_sc_close{
				width: 30rpx;
				height: 30rpx;
				margin-left: auto;
			}
		}
	}
	.uptEexts{
		margin-top: 30rpx;
		.item{
			font-size: 26rpx;
			color: #0099FF;
			margin-bottom: 20rpx;
			display: flex;
			&:last-child{
				margin-bottom: 0;
			}
			.text{
				flex: 1;
				margin: 0 30rpx;
			}
			.icon_sc_wj{
				width: 33rpx;
				height: 29rpx;
				margin-top: 4rpx;
			}
			.icon_sc_close{
				width: 30rpx;
				height: 30rpx;
				margin-left: auto;
			}
		}
	}
	.btnBox{
		color: #fff;
		background: #009FE8;
		line-height: 84rpx;
		border-radius: 6rpx;
		text-align: center;
		margin-top: 60rpx;
	}
	.tipBtn{
		font-size: 24rpx;
		color: #FF0000;
		text-align: center;
		margin-top: 20rpx;
	}
}
.showZihao{
	.ziTitle{
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 30rpx;
		.icon_tc_close{
			width: 30rpx;
			height: 30rpx;
		}
		.text{
			flex: 1;
			text-align: center;
			margin: 0 30rpx;
			font-size: 30rpx;
			font-weight: 700;
		}
	}
	.btn{
		font-size: 28rpx;
		background: #009FE8;
		color: #fff;
		text-align: center;
		line-height: 80rpx;
		border-radius: 10rpx;
		margin: 30rpx;
	}
	.itemBox{
		.item{
			display: flex;
			align-items: center;
			padding: 30rpx 30rpx 0 30rpx;
			.ld{
				width: 14rpx;
				height: 14rpx;
				background: #009FE8;
				border-radius: 100%;
			}
			.text{
				flex: 1;
				font-size: 26rpx;
				margin-left: 30rpx;
				line-height: 33rpx;
			}
			.active{
				color: #009FE8;
			}
		}
	}
}
</style>
