<template>
	<div>
		<!-- <div style="margin:2% 0;display: inline-block;">
				<el-input style="width: 180px;" @keydown.enter.native="select" clearable placeholder="请输入活动名称"
					v-model="integralName"></el-input>
			</div> -->
			<div style="text-align: right;">
				<el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="selectHd">刷新
				</el-button>
				<!-- <el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="cleansHs">重置
				</el-button> -->
			</div>
			<el-table v-loading="tableDataLoadingHd" :data="huodongData">
				<el-table-column prop="id" label="编号" width="80">
				</el-table-column>
				<el-table-column prop="title" label="活动名称" width="150">
				</el-table-column>
        <el-table-column prop="type" label="活动类型">
          <template slot-scope="scope">
            <span v-if="scope.row.type==1">普通活动</span>
            <span v-else-if="scope.row.type==2">时段优惠</span>
            <span v-else-if="scope.row.type==3">满额优惠</span>
            <span v-else-if="scope.row.type==4">全场优惠</span>
          </template>
        </el-table-column>
				<el-table-column prop="image" label="活动图片" width="200">
					<template slot-scope="scope">
						<div v-if="scope.row.image">
							<div v-for="(item,index) in scope.row.image.split(',')" :key="index"
								style="display: inline-block; margin: 3px;">
								<el-popover placement="top-start" title="" trigger="hover">
									<img style="width: 50px; height: 50px" :src="item" alt="" slot="reference">
									<img style="width: 300px; height: auto" :src="item" alt="">
								</el-popover>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="content" label="活动内容">
					<template slot-scope="scope">
						<el-popover placement="top-start" title="" trigger="hover">
							<div style="display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;max-height:80px;"
								slot="reference">{{scope.row.content}}</div>
							<div style="width: 300px; height: auto;word-break: break-all;">{{scope.row.content}}
							</div>
						</el-popover>

					</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="创建时间" width="160">
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="160">
					<template slot-scope="scope">
						<el-button size="mini" v-if="scope.row.quantity==0" type="primary" @click="querenBtnHd(scope.row)" style="margin: 3px;">参加活动
						</el-button>


						<template v-else>
							<el-button size="mini" type="warn" disabled style="margin: 3px;">已参加
							</el-button>
							<el-button size="mini" type="primary" style="margin: 3px;" v-if="scope.row.type=='3'" @click="selectshangpin(scope.row)">选择商品
							</el-button>
							<el-button size="mini" type="primary" style="margin: 3px;" @click="quitHuo(scope.row)">退出活动
							</el-button>
						</template>

					</template>
				</el-table-column>
			</el-table>
			<!-- <div style="text-align: center;margin-top: 10px;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:page-sizes="[10, 15, 20, 25]" :page-size="limitH" :current-page="pageH"
					layout="total,sizes, prev, pager, next" :total="huodongData.length">
				</el-pagination>
			</div> -->
    <!-- 参与活动弹框 -->
		<el-dialog title="参与活动" :visible.sync="dialogFormcanyuhuo" center>
			<div>
				<div style="margin-bottom: 10px;">
					<span style="width: 200px;display: inline-block;text-align: right;">活动名称：</span>
					<span>{{huoList.title}}</span>
				</div>
				<div style="margin-bottom: 10px;" v-if="huoList.image">
					<div style="width: 200px;display: inline-block;text-align: right;">活动图片：</div>
					<div class="imgs" v-for="(item,index) in huoList.image.split(',')" :key="index">
						<img width="100%" class="images" height="100%" :src="item" alt="">
					</div>
				</div>
				<div style="margin-bottom: 10px;">
					<span style="width: 200px;display: inline-block;text-align: right;">活动详情：</span>
					<div class="divs" v-html="huoList.content" style="margin-left: 200px;width: 50%;">
					</div>
				</div>
        		<!-- <div style="margin-bottom: 10px;" v-if="huoList.type=='3'">
					<span style="width: 200px;display: inline-block;text-align: right;">参与活动的商品：</span>
					<span class="divs" style="width: 50%;color: rgba(62, 142, 247, 1);" @click="selectshangpin">请选择/修改</span>
				</div> -->
        		<div style="margin-bottom: 10px;">
					<span style="width: 200px;display: inline-block;text-align: right;">活动类型：</span>
					<span v-if="huoList.type=='1'">普通活动</span>
					<span v-if="huoList.type=='2'">时段优惠</span>
					<span v-if="huoList.type=='3'">满额优惠</span>
					<span v-if="huoList.type=='4'">全场优惠</span>
				</div>
        		<div style="margin-bottom: 10px;" v-if="huoList.type=='2' || huoList.type=='3' || huoList.type=='4'">
					<span style="width: 200px;display: inline-block;text-align: right;">适用情况：</span>
					<el-radio v-model="suitType" :label="'1'">皆适用</el-radio><br>
					<div style="margin-left: 205px;width: 200px;">
						<el-radio v-model="suitType" :label="'2'">仅针对第一次下单</el-radio>
					</div>
				</div>
        		<div style="margin-bottom: 10px;">
					<span style="width: 200px;display: inline-block;text-align: right;">活动时间：</span>
					<span>{{huoList.startTime}}至{{huoList.endTime}}</span>
				</div>
        		<div style="margin-bottom: 10px;" v-if="huoList.type=='2' || huoList.type=='3' || huoList.type=='4'">
					<span style="width: 200px;display: inline-block;text-align: right;">使用限制：</span>
					<el-radio v-model="limitType" :label="'1'">无限制</el-radio><br>
					<div style="margin-left: 205px;">
						<el-radio v-model="limitType" :label="'2'">每天使用</el-radio>
						<el-input v-model="limitNum" type="number" style="width:23%;display: inline-table;"></el-input>
						<span>次</span>
					</div>
				</div>
				<div style="margin-bottom: 10px;">
					<div class="canquxiao" @click="joinHuo">确定</div>
					<div class="canqueding">取消</div>
				</div>
			</div>
		</el-dialog>
    <!-- 选择活动商品弹框 -->
		<el-dialog title="优惠商品" :visible.sync="dialogFormVisibleshangp" center width="70%">
      <div style="margin:2% 0;display: inline-block;">
        <span>商品名称：</span>
        <el-input style="width: 180px;" @keydown.enter.native="select" clearable placeholder="请输入商品名称"
          v-model="integralName"></el-input>
      </div>
      <div style="display: inline-block;">
        <el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="select">查询
        </el-button>
      </div>
	  <div style="display: inline-block;">
        <el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="yiselect()">已选择商品
        </el-button>
      </div>
			<el-table v-loading="tableDataLoadingShop":data="shopData.list" ref="dataTable"
      :key="randomKey"
              @select="selectdan"
              @select-all="selectAll">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
				<el-table-column label="编号" prop="goodsId" width="80" fixed="left">
				</el-table-column>
				<el-table-column label="标题" prop="goodsName" fixed="left">
				</el-table-column>
				<el-table-column prop="goodsCover" label="商品图" width="150">
				  <template slot-scope="scope">

				    <div style="display: inline-block; margin: 3px;">
				      <el-popover placement="top-start" title="" trigger="hover">
				        <img style="width: 50px; height: 50px" :src="scope.row.goodsCover" alt="" slot="reference">
				        <img style="width: 300px; height: auto" :src="scope.row.goodsCover" alt="">
				      </el-popover>
				    </div>
				  </template>
				</el-table-column>
        <el-table-column label="商品描述" prop="goodsDescribe" width="120">
				</el-table-column>
				<el-table-column label="创建时间" prop="createTime">
				</el-table-column>

			</el-table>
      <el-button style='margin-left:15px;margin-top: 10px;' size="mini" type="primary" icon="document" @click="tianjiahuo">确定
      </el-button>
			<div style="text-align: center;margin-top: 10px;">
				<el-pagination @size-change="handleSizeChangeShop" @current-change="handleCurrentChangeShop"
					:page-sizes="[10, 15, 20, 25]" :page-size="limit1" :current-page="page1"
					layout="total,sizes, prev, pager, next" :total="shopData.totalCount">
				</el-pagination>
			</div>
		</el-dialog>

		<!-- 已选择商品 -->
		<el-dialog title="已选择商品" :visible.sync="dialogFormVisibleshangpYi" center width="70%">
			<el-table v-loading="tableDataLoadingShopYi":data="shopDataYi">
				<el-table-column label="编号" prop="goodsId" width="80" fixed="left">
				</el-table-column>
				<el-table-column label="标题" prop="goodsName" fixed="left">
				</el-table-column>
				<el-table-column prop="goodsCover" label="商品图" width="150">
				  <template slot-scope="scope">

				    <div style="display: inline-block; margin: 3px;">
				      <el-popover placement="top-start" title="" trigger="hover">
				        <img style="width: 50px; height: 50px" :src="scope.row.goodsCover" alt="" slot="reference">
				        <img style="width: 300px; height: auto" :src="scope.row.goodsCover" alt="">
				      </el-popover>
				    </div>
				  </template>
				</el-table-column>
        <el-table-column label="商品描述" prop="goodsDescribe" width="120">
				</el-table-column>
				<el-table-column label="创建时间" prop="createTime">
				</el-table-column>

			</el-table>
			<!-- <div style="text-align: center;margin-top: 10px;">
				<el-pagination @size-change="handleSizeChangeShop2" @current-change="handleCurrentChangeShop2"
					:page-sizes="[10, 15, 20, 25]" :page-size="limit2" :current-page="page2"
					layout="total,sizes, prev, pager, next" :total="shopTotal">
				</el-pagination>
			</div> -->
		</el-dialog>
	</div>

</template>

<script>
	import {
		jsonp
	} from 'vue-jsonp'
	import {
		provinceAndCityData,
		regionData,
		provinceAndCityDataPlus,
		regionDataPlus,
		CodeToText,
		TextToCode
	} from 'element-china-area-data'
	var geocoder, map, markersArray = [];
	export default {
		data() {
			return {
				limit: 10,
				page: 1,
				limit1: 10,
				page1: 1,
				limit2: 10,
				page2: 1,
				shopId: '',
				shopName: '',
				img: [], //任务轮播图
				shopTypeName: '',
				shopCover: '',

				dialogFormVisibleHd: false,
				dialogFormcanyuhuo:false,//参与活动弹框
				dialogFormVisibleshangp:false,//优惠商品选择弹框
				dialogFormVisibleshangpYi:false,//已选择商品弹框
				shopData:{},
        selectedItems: [],//存储选中的数组
		    randomKey: Math.random(),
        suoshoplength:0,//所有商品数量
				shopDataYi:[],//已选择商品
				shopTotal:'',
				tableDataLoadingHd: false,
				huodongData: [],
				limitH: 10,
				pageH: 1,
				integralName: '',
				xiangqingData: {},
				activityId:'',
				// 参与活动参数
				huoList:{},
				huoId:'',
				suitType:'1',//适用情况
				limitType:'1',//使用限制
				limitNum:'',
				actShopid:'',//选择商品的id

			}
		},
		methods: {
			// 活动弹框
			canjiaHd(row) {
				this.shopId = this.$cookie.get('shopId')
				this.activityId = row.activityId
				this.dialogFormVisibleHd = true
				this.shopSelect()
			},
			// 获取活动列表
			huodongSelect(returnData) {
				this.tableDataLoadingHd = true
				this.$http({
					url: this.$http.adornUrl('admin/activity/page'),
					method: 'get',
					params: this.$http.adornParams({
            		'page': this.pageH,
				    'limit': this.limitH,
					})
				}).then(({
					data
				}) => {
					let length=data.data.totalCount
					this.$http({
					url: this.$http.adornUrl('admin/activity/page'),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.pageH,
						'limit': length,
					})
					}).then(({
						data
					}) => {
						this.tableDataLoadingHd = false
						let returnData2 = data.data
						const newList =returnData2.list.map(item =>{
						return{...item,quantity:0}
            return{...item,activityShopId:0}
						})
						var arr = []
						for(var j in returnData){
						newList.forEach(item => {
							if (item.id === returnData[j].activityId) {
							// 'status'为属性名，'非活动'为修改后的内容
							item.quantity = 1
              item.activityShopId = returnData[j].activityShopId
							}
						})
						}
						arr=newList
						this.huodongData = arr
					})
				})
			},
			selectHd() {
				this.pageH = 1
				this.shopSelect()
			},
			cleansHs() {
				this.pageH = 1
				this.huodongSelect()
			},
      handleSizeChangeShop(val) {
        this.limit1 = val
        this.getGoods11()
      },
      handleCurrentChangeShop(val) {
        this.page1 = val
        this.getGoods11()
      },
      handleSizeChangeShop2(val) {
        this.limit2 = val
        this.selectShang()
      },
      handleCurrentChangeShop2(val) {
        this.page2 = val
        this.selectShang()
      },
      //添加商品
      tianjiahuo(){
        if (this.selectedItems.length <= 0) {
          this.$message('请勾选需要添加的商品');
          return;
        }
        var shangIds=[]
        this.selectedItems.forEach(item => {
          shangIds.push(item.goodsId)
        })
        this.$http({
            url: this.$http.adornUrl(
              "/admin/activity-goods"
            ),
            method: 'post',
            data: this.$http.adornData({
              "activityShopId": this.actShopid,
					    "goodsIds": shangIds
            })
          }).then(({
            data
          }) => {
            if(data.code==0){
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.dialogFormVisibleshangp = false
                  this.selectedItems=[]
                  this.shopSelect()
                }
              })
						}else{
							this.$message({
								message: data.msg,
								type: 'warning',
								duration: 1500,
								onClose: () => {
								}
							})
						}
          })
      },
			//选择商品
			selectshangpin(row){
				this.dialogFormVisibleshangp=true
				this.actShopid=row.activityShopId
				this.getGoods11()
			},
			//所有商品11
			getGoods11(){
				this.$http({
					url: this.$http.adornUrl('admin/goodsShop/selectGoodsByShopId'),
					method: 'get',
					params: this.$http.adornParams({
						"page": this.page1,
						"limit": this.limit1,
						"goodsName": this.integralName,
						"shopId": this.shopId,
					})
				}).then(({
					data
				}) => {
					if(data.msg=='success'){
            this.suoshoplength=data.data.totalCount
						this.shopData=data.data
            //randomKey是table数据改动时，刷新table的
            this.randomKey = Math.random()
					  this.selectedPreExisting(this.selectedItems)
					}else{
						this.$message({
							message: data.msg,
							type: 'warning',
							duration: 1500,
							onClose: () => {
							}
						})
					}
				})
			},
      //选中table已有数据
      selectedPreExisting (rows) {
        if (rows.length > 0) {
          //这里使用this.$nextTick是防止表格未渲染完成就执行，导致无法添加选中效果
          this.$nextTick(() => {
          rows.forEach(row => {
            //判断row是存在当前tableData
            let selectedItem = this.shopData.list.find(item => item.goodsId == row.goodsId)
            this.$refs.dataTable.toggleRowSelection(selectedItem);
          });
          })
        } else {
          this.$refs.dataTable.clearSelection();
        }
      },
      //表格单选
      selectdan (selection, row) {
        //因为翻页之后，点选时selection会出现undefined,所以这里需要进行判断
        //这里可以通过判断选择selection中有没有row，就可以判断出是增加还是删减
        if (selection && selection.find(item => item && (item.goodsId == row.goodsId))) {
          this.addRows([row])
        } else {
          this.deleteRows([row])
        }
      },
      //表格全选
      selectAll (selection) {
        //判断是选中还是取消tableData
        if (selection.length > 0) {
          this.addRows(this.shopData.list)
        } else {
          this.deleteRows(this.shopData.list)
        }
      },
      //添加选中
      addRows (rows) {
        rows.forEach(row => {
          //过滤，当selectedItems有此条数据时，则直接返回，不执行添加
          if (this.selectedItems.find(item => item.goodsId == row.goodsId)) { return }
          this.selectedItems.push(row)
        });
      },
      //取消选中
      deleteRows (rows) {
        //当selectedItems为空数组时，不执行删除
        if (this.selectedItems.length == 0) { return }
        rows.forEach(row => {
          this.selectedItems = this.selectedItems.filter(item => item.goodsId !== row.goodsId)
        })
      },
			// 已选择商品
			yiselect(row){
				this.dialogFormVisibleshangpYi=true
				this.selectShang()
			},
			// 店铺已选择商品
			selectShang(){
				this.$http({
					url: this.$http.adornUrl(`admin/activity-goods/${this.actShopid}`),
					method: 'get',
					params: this.$http.adornParams({
					})
				}).then(({
					data
				}) => {
					if(data.msg=='success'){
						let returnData = data.data
						//商品列表
						this.getGoods(returnData)
					}else{
						this.$message({
							message: data.msg,
							type: 'warning',
							duration: 1500,
							onClose: () => {
							}
						})
					}
				})
			},
			//所有商品
			getGoods(returnData){
				this.$http({
					url: this.$http.adornUrl('admin/goodsShop/selectGoodsByShopId'),
					method: 'get',
					params: this.$http.adornParams({
						"page": this.page2,
						"limit": this.suoshoplength,
						"goodsName": this.integralName,
						"shopId": this.shopId,
					})
				}).then(({
					data
				}) => {
					if(data.msg=='success'){
						let returnData2 = data.data
						const newList =returnData2.list
						var arr = []
            for(var j in returnData){
              newList.forEach(item => {
                if (item.goodsId === returnData[j]) {
                  arr.push(item)
                }
              })
            }
						this.shopDataYi = arr
            this.shopTotal =this.shopDataYi.length
					}else{
						this.$message({
							message: data.msg,
							type: 'warning',
							duration: 1500,
							onClose: () => {
							}
						})
					}
				})
			},
			// 确认参加活动
			querenBtnHd(row) {
				this.huoId=row.id
				this.getActivity(row.id)
			},
			//退出活动
			quitHuo(row){
				this.$confirm(`确定退出该活动?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: this.$http.adornUrl('admin/activity-shop/quit'),
						method: 'put',
						params: this.$http.adornParams({
							"shopId":this.shopId,
							"activityId": row.id
						})
					}).then(({
						data
					}) => {
						if(data.code==0){
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.shopSelect()
								}
							})
						}else{
							this.$message({
								message: data.msg,
								type: 'warning',
								duration: 1500,
								onClose: () => {
								}
							})
						}

					})
				}).catch(() => {})
			},
			//参与活动
			joinHuo(){
				var shopid=[this.shopId]
				if (this.limitType == '') {
					this.$notify({
						title: '提示',
						duration: 1800,
						message: '有限制时不能为空',
						type: 'warning'
					});
					return
				}
				this.$http({
					url: this.$http.adornUrl('admin/activity-shop/join'),
					method: 'post',
					data: this.$http.adornData({
						"activityId": this.huoId,
						"limitType": this.limitType,
						"limitValue": this.limitNum,
						"shopIds": shopid,
						"suitType": this.suitType
					})
				}).then(({
					data
				}) => {
					if(data.code==0){
						this.dialogFormcanyuhuo = false
						this.$message({
							message: '操作成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.shopSelect()
							}
						})
					}else{
						this.$message({
							message: data.msg,
							type: 'warning',
							duration: 1500,
							onClose: () => {
							}
						})
					}

				})
			},
			//获取活动信息
			getActivity(id){
				this.$http({
					url: this.$http.adornUrl(`admin/activity/${id}`),
					method: 'get',
					params: this.$http.adornParams({
						// 'shopId': this.shopId,
					})
				}).then(({
					data
				}) => {
					if(data.msg=='success'){
						let returnData = data.data
						this.huoList=returnData
						this.dialogFormcanyuhuo=true
					}else{
						this.$message({
							message: data.msg,
							type: 'warning',
							duration: 1500,
							onClose: () => {
							}
						})
					}
				})
			},
			shopSelect() {
				this.$http({
					url: this.$http.adornUrl(`admin/activity-shop/shop-activity-list/${this.shopId}`),
					method: 'get',
					params: this.$http.adornParams({
						// 'shopId': this.shopId,
					})
				}).then(({
					data
				}) => {
					let returnData = data.data
					// if(data.data){
					// 	this.activityId = returnData.activityId
					// }else{
					// 	this.activityId = ''
					// }
					this.huodongSelect(returnData)
				})
			},

		},
		mounted() {
			this.shopId = this.$cookie.get('shopId')
			this.shopSelect()

		}
	}
</script>

<style>
	.imgs {
		position: relative;
		border-radius: 6px;
		width: 148px;
		height: 148px;
		margin-right: 10px;
		display: inline-block;
	}

	.dels {
		position: absolute;
		top: 0;
		left: 0;
		display: none;
	}

	.dels .el-icon-delete {
		line-height: 148px;
		padding-left: 58px;
		font-size: 25px;
		color: #fff;
	}

	.imgs:hover .dels {
		width: 100%;
		height: 100%;
		background: #000;
		display: block;
		opacity: 0.5;
	}

	.bqList {
		padding: 4px 14px;
		margin: 4px;
		border: 1px solid #efefef;
		font-size: 12px;
		color: #999;
		border-radius: 4px;
		margin-right: 15px;
	}

	.delss {
		display: none;
		position: relative;
	}

	.delss .el-icon-delete {
		position: absolute;
		top: 0;
	}

	.bqList:hover .delss {
		display: initial;
		opacity: 0.5;

	}

	.tj {
		padding: 6px !important;
		margin: 4px;
		font-size: 12px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.divs img {
		width: 100%;
	}
  /* //参与活动弹框 */
	.canquxiao{
		margin-top: 20px;
		margin-left: 287px;
		width: 76px;
		height: 35px;
		opacity: 1;
		background: rgba(62, 142, 247, 1);
		border-radius: 5px;
		font-size: 16px;
		font-weight: 400;
		line-height: 35px;
		color: rgba(255, 255, 255, 1);
		text-align: center;
	}
	.canqueding{
		margin-top: -35px;
		margin-left: 407px;
		width: 76px;
		height: 35px;
		opacity: 1;
		border-radius: 5px;
		border: 1px solid rgba(0, 0, 0, 1);
		font-size: 16px;
		font-weight: 400;
		line-height: 35px;
		color: rgba(0, 0, 0, 1);
		text-align: center;
	}
</style>
