<!-- 主题订制 -->
<template>
   <div class="innerMargin">
      <el-card class="box-card">
         <div style="cursor: default">
            <div class="search-box">
               <div class="filter-box">
                  <el-input
                     style="cursor: pointer"
                     size="small"
                     placeholder="请输入主题名称"
                     v-model="userGroupName"
                     clearable
                     @change="searchData()"
                  >
                     <i slot="suffix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                  <el-date-picker
                     style="cursor: pointer"
                     size="small"
                     v-model="timeRange"
                     type="daterange"
                     range-separator="至"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
                     @change="dateData"
                  ></el-date-picker>
               </div>
               <el-button type="blueInfo" size="mini" @click="addUserGroup()"
                  >新增主题</el-button
               >
            </div>
            <el-row :gutter="10">
               <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="6"
                  :xl="4"
                  v-for="item in userGroupList"
                  :key="item.id"
               >
                  <el-card class="box-card pad0">
                     <div class="img-box">
                        <span class="logo-box">
                           <template v-if="item.role_logo == ''">
                              <img
                                 :src="require('@/assets/images/equipdistribute/user.png')"
                              />
                           </template>
                           <img v-else :src="item.role_logo" alt="" class="" />
                           <!-- <img v-else :src=" $host + item.role_logo" alt="" class=""> -->
                        </span>
                        <p>{{ item.role_describe }}</p>
                     </div>
                     <div class="detail">
                        <p>
                           <span>创建时间</span>
                           <span>{{ (item.role_cre_time * 1000) | formatTime }}</span>
                        </p>
                        <p>
                           <span>首页主题</span> 
                           <span>{{ item.role_header }}</span>
                        </p>
                     </div>
                     <div class="bottom">
                        <span @click="viewDetail(item.role_describe)">
                           <i class="el-icon-document"></i> 查看详情
                        </span>
                        <span @click="edit(item.role_describe)">
                           <i class="el-icon-edit-outline"></i> 编辑
                        </span>
                     </div>
                  </el-card>
               </el-col>
            </el-row>
            <!-- 暂无数据 -->
            <div
               class="expertDiagnosis_referral_units_not"
               v-if="userGroupList.length <= 0"
            >
               <img
                  :src="$imghost + zanwu"
                  alt
                  class="expertDiagnosis_referral_units_notImg"
               />
            </div>
            <el-pagination
               v-if="userGroupList.length > 0"
               :current-page="page"
               background
               layout="prev, pager, next"
               :total="totalNum"
               :page-size="12"
               @current-change="changePage"
            ></el-pagination>
            <!-- 详情对话框 -->
            <el-dialog
               title="详情"
               :visible.sync="detailDialogVisible"
               class="detailDialog"
               width="30%"
            >
               <!-- <p>
                  <span>主题名称 :</span>
                  <span>{{ userDetail.role_cre_user }}</span>
               </p> -->
               <p>
                  <span>首页主题 :</span>
                  <span>{{ userDetail.role_header }}</span>
               </p>
               <p>
                  <span>创建时间 :</span>
                  <span>{{ (userDetail.role_cre_time * 1000) | formatTime }}</span>
               </p>
               <p>
                  <span>首页logo :</span>
                  <span>
                     <img
                        style="width: 3rem; height: 2.2rem"
                        :src="userDetail.role_logo"
                     />
                  </span>
               </p>
               <p>
                  <span>首页footer :</span>
                  <span>{{ userDetail.role_footer }}</span>
               </p>
            </el-dialog>
            <!-- 编辑对话框 -->
            <el-dialog
               title="编辑"
               :visible.sync="editDialogVisible"
               class="editDialog"
               width="30%"
			   top="180px"
            >
               <el-form
                  ref="form"
                  label-position="left"
                  :model="userDetail"
                  label-width="100px"
               >
                  <el-form-item label="首页logo : ">
                     <el-upload
                        class="avatar-uploader"
                        ref="upload"
                        :http-request="ImgUploadSectionFile"
                        :with-credentials="true"
                        :auto-upload="false"
                        accept=".png, .jpg, .gif, .svg"
                        action
                        :on-change="handleChange"
                        list-type="list"
                        :file-list="fileList"
                        multiple
                        :show-file-list="false"
                     >
                        <img
                           v-if="userDetail.role_logo"
                           :src="userDetail.role_logo"
                           class="avatar"
                        />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                     </el-upload>
                  </el-form-item>
                  <el-form-item label="主题 : ">
                     <el-input maxlength="18" v-model="userDetail.role_header"></el-input>
                  </el-form-item>
                  <!-- <el-form-item label="版权 : ">
                     <el-input
                        type="textarea"
                        :rows="2"
                        v-model="userDetail.role_footer"
                     ></el-input>
                  </el-form-item> -->
               </el-form>
               <span slot="footer" class="dialog-footer">
                  <el-button type="grayInfo" plain @click="editDialogVisible = false">取 消</el-button>
                  <el-button type="blueInfo" @click=";(editDialogVisible = false), addr()"
                     >保 存</el-button
                  >
               </span>
            </el-dialog>
            <!-- 新增主题 -->
            <el-dialog
               title="新增主题"
               :visible.sync="addUserGroupDialogVisible"
               class="editDialog"
               width="25%"
            >
               <el-form ref="form" :model="adduserGroupForm" label-width="100px">
                  <el-form-item label="主题名称">
                     <el-input required v-model="adduserGroupForm.userGroupName"></el-input>
                  </el-form-item>
               </el-form>
               <span slot="footer" class="dialog-footer">
                  <el-button type="grayInfo" plain @click="addUserGroupDialogVisible = false">取 消</el-button>
                  <el-button
                     type="blueInfo"
                     @click="listAddr()"
                     >确 定</el-button
                  >
               </span>
            </el-dialog>

            <!-- vueCropper 剪裁图片实现-->
            <el-dialog
               title="图片剪裁"
               :close-on-click-modal="false"
               :visible.sync="cropperVisible"
               width="500px"
            >
               <div class="cropper-content">
                  <div style="width: 100%; height: 300px">
                     <vue-cropper
                        ref="cropper"
                        :img="option.img"
                        :output-size="option.size"
                        :output-type="option.outputType"
                        :info="true"
                        :full="option.full"
                        :fixed="option.fixed"
                        :fixed-number="option.fixedNumber"
                        :can-move="option.canMove"
                        :can-move-box="option.canMoveBox"
                        :fixed-box="option.fixedBox"
                        :original="option.original"
                        :auto-crop="option.autoCrop"
                        :auto-crop-width="option.autoCropWidth"
                        :auto-crop-height="option.autoCropHeight"
                        :center-box="option.centerBox"
                        :high="option.high"
                        mode="cover"
                        :max-img-size="option.max"
                     ></vue-cropper>
                  </div>
               </div>
               <div slot="footer" class="dialog-footer">
                  <el-button type="grayInfo" plain @click="cropperVisible = false">取 消</el-button>
                  <el-button type="blueInfo" @click="cropperFinish">确认</el-button>
               </div>
            </el-dialog>
         </div>
      </el-card>
   </div>
</template>

<script>
export default {
	data() {
		return {
			zanwu: '/images/expertDiagnosis/zanwu.png',
			// 裁剪组件的基础配置option
			cropperVisible: false,
			option: {
				img: null,
				size: 1,
				full: false,
				outputType: 'png',
				canMove: true,
				fixed: false,
				// fixedNumber: [16, 9],
				// fixedNumber: [7, 6],
				fixedBox: false,
				original: false,
				canMoveBox: true,
				autoCrop: true,
				// 只有自动截图开启 宽度高度才生效
				autoCropWidth: 160,
				autoCropHeight: 150,
				centerBox: false,
				high: true,
				max: 99999
			},
			userGroupName: '',
			timeRange: '',
			fullHeight: document.documentElement.clientHeight, //自适应高度
			userGroupList: [],
			userDetail: {},
			detailDialogVisible: false,
			editDialogVisible: false,
			addUserGroupDialogVisible: false,
			totalNum: 0,
			adduserGroupForm: {
				userGroupName: ''
			},
			fileList: [],
			imageSrc: '', //后端返回的图片链接
			Str: '', //转换后的开始时间
			end: '', //转换后的结束时间
			page: 1,
			ulrData: '',
			img_file: ''
		}
	},
	watch: {
		fullHeight(val) {
			//监控浏览器高度变化
			if (!this.timer) {
				this.fullHeight = val
				this.timer = true
				let that = this
				setTimeout(function () {
					//防止过度调用监测事件，导致卡顿
					that.timer = false
				}, 400)
			}
		},

		// 编辑弹框监测
		editDialogVisible(val) {
			if (val == true) {
				//显示
				console.log('显示')
			} else if (val == false) {
				// 关闭
				this.$refs.upload.clearFiles() //清空
			}
		},

		// 新增主题监测
		addUserGroupDialogVisible(val) {
			if (val == false) {
				this.adduserGroupForm.userGroupName = ''
			}
		}
	},
	methods: {
		//动态获取浏览器高度
		get_boderHeight() {
			const that = this
			window.onresize = () => {
				return (() => {
					window.fullHeight = document.documentElement.clientHeight
					that.fullHeight = window.fullHeight - 128
				})()
			}
		},

		// 查看详情
		viewDetail(name) {
			let that = this
			let postData = that.qs.stringify({
				role: name, //名称
				req: 'details', //详情数据回显
				img_file: '', //首页图片
				role_footer: '', //版权
				role_header: '', //主题
				role_logo: '' //首页图片链接
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_img',
					data: postData
				})
				.then((res) => {
					if (res.data.data.nums !== 0) {
						this.userDetail = res.data.data
						that.detailDialogVisible = true
					}
				})
				.catch((err) => {
					console.log(err)
				})
		},

		//编辑
		edit(name) {
			let that = this
			let postData = that.qs.stringify({
				role: name, //名称
				req: 'details', //详情数据回显
				img_file: '', //首页图片
				role_footer: '', //版权
				role_header: '', //主题
				role_logo: '' //首页图片链接
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_img',
					data: postData
				})
				.then((res) => {
					if (res.data.data.nums !== 0) {
						this.userDetail = res.data.data
						this.img_file = res.data.data.role_logo
						that.editDialogVisible = true
					}
				})
				.catch((err) => {
					console.log(err)
				})
		},

		// 新增主题
		addUserGroup() {
			this.addUserGroupDialogVisible = true
		},
		//新增主题确定按钮
		listAddr() {
         let that = this
         if(!that.adduserGroupForm.userGroupName){
			that.$message({
				message: '请填写主题名称',
				type: 'error'
			})
            return
         }
         this.addUserGroupDialogVisible = false
			let postData = that.qs.stringify({
				// add_role: that.adduserGroupForm.userGroupName, //角色描述
				add_role: 'add', //角色描述
				role_describe: that.adduserGroupForm.userGroupName,
				page: this.page
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_view',
					data: postData
				})
				.then((res) => {
					if (res.data.data.data == 200) {
						that.$message({
							message: '添加新主题成功',
							type: 'success',
							duration: 1500
						})
						var timeoutId = setTimeout(function () {
							that.listData(1, '') //列表数据请求
						}, 1500)
					} else if (res.data.data.data == 201) {
						that.$message.error({
							message: '该主题名称已存在',
							duration: 1500
						})
					}
				})
				.catch((err) => {
					console.log(err)
				})
		},

		// // 上传过图片编辑保存
		ImgUploadSectionFile(param) {
			let that = this
			let formData = new FormData()
			var dataUrl = that.dataURLtoFile(that.ulrData)
			var dataUrlA = that.blobToFile(that.ulrData, param.file.name)
			formData.append('img_file', dataUrlA) //首页图片
			formData.append('role', that.userDetail.role_describe) //角色描述
			formData.append('req', 'img') //上传图片
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_img',
					data: formData
				})
				.then((res) => {
					if (res.data.data.src !== '0') {
						that.imageSrc = res.data.data.src
						that.userDetail.role_logo = res.data.data.src
					} else {
						that.$message.error({
							message: '上传图片失败，请重试',
							duration: 1500
						})
					}
				})
				.catch((err) => {
					console.log(err)
				})
			that.clearUploadBox()
		},

		clearUploadBox() {
			this.userDetail.role_logo = ''
			this.img_file = ''
		},
		handleChange(file, fileList) {
			if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(file.raw.name)) {
				alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
				return false
			}
			let reader = new FileReader()
			reader.onload = (e) => {
				let data
				if (typeof e.target.result === 'object') {
					// 把Array Buffer转化为blob 如果是base64不需要
					data = window.URL.createObjectURL(new Blob([e.target.result]))
				} else {
					data = e.target.result
				}
				this.option.img = data
			}
			this.cropperVisible = true
			reader.readAsArrayBuffer(file.raw)
			this.fileList = fileList
		},
		//转成blob
		blobToFile(Blob, fileName) {
			Blob.lastModifiedDate = new Date()
			Blob.name = fileName
			return Blob
		},
		cropperFinish() {
			var that = this
			that.$refs.cropper.getCropData((data) => {
				that.userDetail.role_logo = data
				that.ulrData = data
				that.cropperVisible = false
				that.btnShow = true
				that.$refs.upload.submit()
			})
		},

		// base64转换为blob文件类型
		dataURLtoFile(dataurl) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			return new Blob([u8arr], { type: mime })
		},

		// blob转换为file文件类型
		blobToFile(dataurl, filename) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			return new File([u8arr], filename, { type: mime })
		},

		// 编辑保存
		addr() {
			this.upDataList() //上传数据
		},
		// 在没有上传图片的情况下编辑上传数据
		upDataList() {
			let that = this
			var img = that.img_file == '' ? that.imageSrc : that.img_file
			let postData = that.qs.stringify({
				req: 'add', //主题信息保存
				img_file: '', //首页图片
				role_footer: that.userDetail.role_footer, //版权
				role_header: that.userDetail.role_header, //主题
				role_logo: img, //首页图片链接
				role: that.userDetail.role_describe //角色描述
			})
			console.log(that.img_file)
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_img',
					data: postData
				})
				.then((res) => {
					if (res.data.data.data == 200) {
						that.$message({
							message: '编辑成功',
							type: 'success',
							duration: 1500
						})
						that.listData(1, '') //列表数据请求
					} else if (res.data.data.data == 400) {
						that.$message.error({
							message: '编辑失败，请重试',
							duration: 1500
						})
					}
				})
				.catch((err) => {
					console.log(err)
				})
		},

		// 分页
		changePage(e) {
			this.listData(e, '')
		},

		// 列表数据请求
		listData(page, add_role) {
			let that = this
			let postData = that.qs.stringify({
				page: page, //页码
				add_role: add_role //角色描述
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_view',
					data: postData
				})
				.then((res) => {
					var data = res.data.data
					that.userGroupList = data.data
					var nums = data.nums
					that.totalNum = nums
				})
				.catch((err) => {
					console.log(err)
				})
		},

		//搜索主题名称
		searchData() {
			let that = this
			console.log(that.timeRange)
			let postData = that.qs.stringify({
				page: this.page, //页数
				role: that.userGroupName, //名称
				time_begin: that.Str, //开始时间
				time_end: that.end //结束时间
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_search',
					data: postData
				})
				.then((res) => {
					var data = res.data.data.data
					that.userGroupList = data
					var nums = res.data.data.nums
					that.totalNum = nums
				})
				.catch((err) => {
					console.log(err)
				})
		},

		// 时间筛选
		dateData() {
			let that = this
			// 开始时间
			let date = new Date(that.timeRange[0])
			let Str =
				date.getFullYear() +
				'-' +
				(date.getMonth() + 1) +
				'-' +
				date.getDate() +
				' ' +
				date.getHours() +
				':' +
				date.getMinutes() +
				':' +
				date.getSeconds()
			Str = Str.replace(' 0:0:0', '')
			that.Str = Str

			// 结束时间
			let dateA = new Date(that.timeRange[1])
			let end =
				dateA.getFullYear() +
				'-' +
				(dateA.getMonth() + 1) +
				'-' +
				dateA.getDate() +
				' ' +
				dateA.getHours() +
				':' +
				dateA.getMinutes() +
				':' +
				dateA.getSeconds()
			end = end.replace(' 0:0:0', '')
			that.end = end

			let postData = that.qs.stringify({
				page: this.page, //页数
				role: that.userGroupName, //名称
				time_begin: Str, //开始时间
				time_end: end //结束时间
			})
			that
				.$axios({
					method: 'post',
					url: 'api/api_gateway?method=pest.warning_record.rolemanage_search',
					data: postData
				})
				.then((res) => {
					var data = res.data.data.data
					that.userGroupList = data
					var nums = res.data.data.nums
					that.totalNum = nums
				})
				.catch((err) => {
					console.log(err)
				})
		}
	},
	created() {},
	mounted() {
		this.get_boderHeight() //自适应
		this.listData(this.page, '') //列表数据请求
	}
}
</script>

<style lang='less' scoped>
.search-box {
	display: flex;
	justify-content: flex-left;
	justify-content: space-between;
	margin-bottom: 10px;
	.filter-box > div {
		margin-right: 15px;
	}
	.el-input {
		width: 200px;
	}
	.el-date-editor--daterange {
		width: 222px;
	}
}
.el-card {
	.img-box {
		text-align: center;
		border-bottom: 1px solid #e1e1e1;
		padding: 15px 0;
		.logo-box {
			display: inline-block;
			width: 60px;
			height: 60px;
			overflow: hidden;
			border-radius: 100%;
			background: #ddd;
			img {
				width: 100%;
				height: 100%;
				border-radius: 50px;
			}
		}
		p {
			font-size: 14px;
			font-weight: 800;
			width: 70%;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			margin: 10px auto 0;
		}
	}
	.detail {
		border-bottom: 1px solid #e1e1e1;
		padding: 10px 0;
		padding: 0 20px;
		p {
			display: flex;
			justify-content: space-between;
			font-size: 13px;
			line-height: 34px;
			color: #666;
			padding: 0 0px;
			>span:nth-child(1){
				width: 65px;
			}
			>span:nth-child(2){
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex: 1;
			}
		}
	}
	.bottom {
		display: flex;
		font-size: 13px;
		color: #666;
		line-height: 50px;
		span {
			flex: 1;
			text-align: center;
			cursor: pointer;
			i {
				font-size: 16px;
			}
		}
		span:first-child {
			border-right: 1px solid #e1e1e1;
		}
	}
}
.detailDialog {
	p {
		display: flex;
		padding: 10px 0;
		span:nth-child(1) {
			width: 100px;
			margin-right: 10px;
			text-align: left;
		}
		span:nth-child(2) {
			flex: 1;
			text-align: left;
		}
	}
}
// 分页为蓝色调
/deep/.el-pagination .el-pager li.active{
  background-color: #0295ff!important;  
}
/deep/.el-pagination.is-background .el-pager li:not(.disabled):hover{
  color: #0295ff;
}
/deep/.el-input__inner:focus{
  outline: none;
  border-color: #0295ff;
}

</style>