<template>
  <div class="step-info">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="新建推送名称">
        <span class="gray">
          <span class="star-red">*</span> 推送名称仅供数据中心操作记录查询，您推送的会员将不会看到此信息。
        </span>
      </el-form-item>
      <el-form-item label="推送名称">
        <el-input v-model.trim="form.name" maxlength="10" placeholder="请输入推送名称，10字以内"></el-input>
      </el-form-item>
      <el-form-item label="选择推送素材" class="step-choose">
        <span class="gray">
          <span class="star-red">*</span> 推送素材需前往
          <a href="#">微信公众平台</a>-管理-素材管理维护。
        </span>
        <div class="add-material" @click="showMaterList()" v-if="!isHaveMater">
          <div v-if="!chooseItem">
            <el-button type="text" class="add-title">
              <p>
                <i class="el-icon-plus add-plus"></i>
              </p>添加微信素材
            </el-button>
          </div>
        </div>
        <div v-else>
          <div
            class="mater-item"
            @click="showMaterList()"
            style="    border: 1px solid #ececec; padding:10px; width:270px;height:230px; margin: 0 20px 20px 0;  position: relative;"
          >
            <div class="mater-wrap">
              <span
                style="    position: absolute;
																				left: 35%;
																				top: 45%;
																				font-size: 16px;
																				color: white;"
              >替换素材</span>
            </div>
            <div
              class="m-title"
              style=" font-size: 14px; color: #3b3a46;  line-height:33px"
            >{{selectedItem.title}}</div>
            <div class="m-img">
              <img
                width="256px"
                :src="selectedItem.thumb_url"
                height="135px; font-weight: normal; padding:10px;"
              >
            </div>
            <!-- <div class="m-content" v-html="item.content"></div> -->
          </div>
        </div>
        <el-dialog
          title="微信消息素材"
          :visible.sync="centerDialogVisible"
          width="1000px"
          center
          class="add-subtitle title"
        >
          <el-row>
            <el-col :span="24">
              <div class="add-line"></div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="add-container">
            <el-col v-if="!materList.length">暂无素材</el-col>
            <el-col
              v-else
              :span="8"
              v-for="(item,index) in materList"
              :key="index"
              style="    width: 100%;
    display: flex; flex-wrap: wrap;"
            >
              <div
                class="mater-item"
                @click="selectMater(item)"
                style="    border: 1px solid #ececec; padding:10px; width:270px;height:230px; margin: 0 20px 20px 0;  position: relative;"
              >
                <div class="mater-wrap">
                  <span
                    style="    position: absolute;
																				left: 35%;
																				top: 45%;
																				font-size: 16px;
																				color: white;"
                  >选择素材</span>
                </div>
                <div
                  class="m-title"
                  style=" font-size: 14px; color: #3b3a46;  line-height:33px"
                >{{item.title}}</div>
                <div class="m-img">
                  <img
                    :src="item.thumb_url"
                    width="256px"
                    height="135px; font-weight: normal; padding:10px;"
                  >
                </div>
                <!-- <div class="m-content" v-html="item.content"></div> -->
              </div>
              <!-- <div class="add-content" @click="handleChoose(item)">
                <span
                  v-if="item.content.news_item.length===1"
                  v-for="(art,index) in item.content.news_item"
                  :key="index"
                >
                  <div>
                    <p
                      style="white-space:normal;
														word-break:break-all;
														word-wrap:break-word;padding:15px 0 0 15px;height:30px"
                    >{{art.title}}</p>
                    <img
                      :src="art.thumb_url"
                      style="width:240px;height:125px;margin:5px 10px;border:1px solid #ccc"
                    >
                    <p
                      v-html="art.content"
                      style="padding-left:10px;
																						font-size: 8px;
																						line-height: 1.3em;
																						color: #a49d96;
																						word-wrap: break-word;"
                    ></p>
                    <span style="padding-left:10px;">查看全文</span>
                  </div>
                </span>
                <span
                  v-if="item.content.news_item.length===2"
                  v-for="(art,index) in item.content.news_item"
                  :key="index"
                  class="two-item"
                >
                  <div style="border-top:1px solid #eee;height:60px;">
                    <p
                      style="width:185px;
														white-space:normal;
														word-break:break-all;
														word-wrap:break-word;padding: 5px 0 0 5px;display:inline-block;"
                    >{{art.title}}</p>
                    <img style="width:40px;heigth:40px; margin-top: 8px;" :src="art.thumb_url">
                  </div>
                </span>
                <span
                  v-if="item.content.news_item.length>2"
                  v-for="(art,index) in item.content.news_item"
                  :key="index"
                  class="three-item"
                >
                  <div class="dv clear">
                    <p>{{art.title}}</p>
                    <img :src="art.thumb_url">
                  </div>
                </span>
                <div class="box-mask">
                  <span>选择素材</span>
                </div>
              </div>-->
            </el-col>
          </el-row>
          <span slot="footer" class="add-footer">
            <el-button
              @click="centerDialogVisible = false"
              style="color: #fff;background-color: #204d74; border-color: #122b40;"
            >取 消</el-button>
          </span>
        </el-dialog>
      </el-form-item>
      <el-form-item label="选择推送范围">
        <el-radio-group v-model="form.resource">
          <el-radio label="全体推送" @change="getAll"></el-radio>
          <el-radio label="精准推送" @change="getsingele"></el-radio>
        </el-radio-group>
        <span v-if="isCount">统计中...</span>
        <span v-else>预计推送数量{{currentTagCount}}（关注微信公众号用户）</span>
        <div v-if="form.resource === '精准推送'">
          <div class="form-tags">
            <span v-for="(item,index) in tagList" :key="item.tagId">
              <span
                @click="handleClickTag(item, index)"
                class="el-tag tag-info"
                :class="{active:item.isActive}"
              >{{item.name}}</span>
            </span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="预览推送数量">
        <span class="gray">
          <span class="star-red">*</span>实际推送成功数量将略有偏差，选中多个标签为同时满足选中标签群体的会员。推送人数必须大于1人。
        </span>
        <div v-if="isCount">
          <el-button class="form-button">选中标签，预览</el-button>
          <span>统计中，请稍候</span>
        </div>
        <div v-else>
          <el-button class="form-button" @click="reCheckNum()">重新预览</el-button>
          <span class="form-checknum" v-if="form.resource === '全体推送'">{{this.currentTagCount}}</span>
          <span class="form-checknum" v-else>{{successNum}}</span>人
          <span class="form-vipnum">标签会员数： {{tagNum}} 人</span>
          <span>其中，关注公众号： {{followNum}} 人</span>
          <span>已推送4次会员： {{fourthNum}} 人</span>
        </div>
      </el-form-item>
      <el-form-item label="执行推送任务">
        <span class="gray">
          <span class="star-red">*</span>填写邮箱后，勾选免责说明，确认进行推送，推送完成后将发送邮件通知至指定邮箱。
        </span>
        <el-checkbox v-model="checked">本次推送为t测试组商户123自发行为，发放内容请遵守国家相关法律规定..</el-checkbox>
      </el-form-item>
      <el-form-item label="指定接收邮箱">
        <el-input v-model="email" type="email" placeholder="请输入您要接收任务信息的邮箱"></el-input>
      </el-form-item>
      <el-form-item class="submit-dialog">
        <el-button
          class="form-button"
          @click="handleConfirmPush"
          :style="isBtnCheckd"
          :disabled="!checked"
        >确认推送</el-button>
        <el-dialog title="推送确认" :visible.sync="submitDialogVisible" width="30%" center>
          <div>
            <img :src="currentImgUrl">
            <p>向{{currentTagCount}}名粉丝推送</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </span>
        </el-dialog>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import api from '@/tool/api'
import {mapMutations, mapState} from 'vuex';

export default {
	data() {
		return {
			form: {
				name: '',
				type: [],
				resource: '全体推送',
			},
			materList: [],
			email: '',
			checked: false,
			dialogVisible: false,
			centerDialogVisible: false,
			submitDialogVisible: false,
			currentImgUrl: '',
			currentImgId: '',
			isCount: false,
			currentTagCount: 0,
			tagNum: 0,
			followNum: 0,
			fourthNum: 0,
			successNum: 0,
      currentTagIndex: 0,
      isHaveMater: false,
			tagIds: [],
			tagIdsSave: [],
			tagList: [],
			tagIdsList: [],
			chooseTag: [],
			chooseItem: '',
      selectedItem:{},
      materListId: ''
		}
	},
	created() {
		if (localStorage && localStorage.materList) {
			this.materList = JSON.parse(localStorage.materList)
		}
		this.getTagList()
	},
	computed: {
		isBtnCheckd() {
			return this.checked ? 'opacity: 1' : 'opacity: .65'
		},
		...mapState(['global']),
		item() {
			return this.global.chooseItem
		}
	},
	methods: {
		...mapMutations(['CHOOSE_ITEM']),
		handleChoose(item) {
			this.chooseItem = item
			this.currentImgId = item.media_id
			this.CHOOSE_ITEM(item)
			this.centerDialogVisible = false
    },
    selectMater(item) {
      console.log(item);
      this.centerDialogVisible = false;
			this.isHaveMater = true;
			this.selectedItem = item;
    },
    async showMaterList() {
    this.centerDialogVisible = true;

      await this.axios.post(api.add.getMaterial, {
        pageNo: 1,
        pageSize: 20,
      })
      .then( res => {
        let result = res.data.result;
        if(result.result && result.result.length >0 )
          this.materList = result.result[0].content.news_item;
          this.materListId = result.result[0].media_id;
          console.log(this.materList)
      })
    },
		getAll() {
			this.isCount = true
			this.getTagCountAll()
		},
		getsingele() {
			this.currentTagCount = 0
		},
		handleConfirmPush() {
			// 校验
			if (!this.form.name) {
				return this.$message({
					message: '请输入推送标题',
					type: 'warning',
				})
			}
			if (!this.isHaveMater) {
				return this.$message({
					message: '请选择推送素材',
					type: 'warning',
				})
			}

			var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/

			if (!this.email) {
				return this.$message({
					message: '请选择邮箱',
					type: 'warning',
				})
			} else if (!reg.test(this.email)) {
				return this.$message({
					message: '邮箱格式不正确',
					type: 'warning',
				})
			}
			this.submitDialogVisible = true
		},
		handleClickTag(item, index) {
			console.log(arguments)
			item.isActive = !item.isActive
		  this.currentTagIndex = index
			this.isCount = true

			if (item.isActive) {
				this.tagIds.push(item.tagId)
				this.tagIdsSave.push({
					tagId: item.tagId,
					name: item.name,
				})
			} else {
				this.tagIds.forEach((tag, index) => {
					if (tag === item.tagId) {
						this.tagIds.splice(index, 1)
					}
				})
				this.tagIdsSave.forEach((tag, index) => {
					if (tag.tagId === item.tagId) {
						this.tagIdsSave.splice(index, 1)
					}
				})
			}
      this.tagList = this.tagList.splice(0)
      console.log(this.tagList )
			this.getTagCount()
			this.getViewCount()
		},
		onSubmit() {
			if (this.currentTagCount < 1) {
				return this.$message({
					message: '推送成功人数>1时才可推送',
					type: 'warning',
				})
			}
			this.submitDialogVisible = false
			this.save()
    },
    reCheckNum() {
      this.getViewCount();
    },
		// 确认推送
		async save() {
      console.log(this.selectedItem)
      // 构建post对象
			let responseData = {
				title: this.form.name,
				scope: this.form.resource === '全体推送' ? 0 :1,
				pushCount:this.currentTagCount,
				email:  this.email,
				type:1,
				mediaId:  this.materListId,
      }
      // 如果是精准推送的话，把所有选中的标签扔进去
			if(responseData.scope == '1') {
        let tagIds = ''
       this.tagList.filter(tag => tag.isActive ) .forEach(tag => {
			  	tagIds  = tagIds + tag.tagId +','
				})
				tagIds = tagIds.substring(0, tagIds.length - 1);

				responseData.tagIds = tagIds;
      }
      console.log(responseData);
     await this.axios.post(api.add.save, responseData)
     .then(res =>{
       if(res.data.code === 0) {
         this.$message({
           message: res.data.message,
           type: 'success'
         })
         this.$router.push({ path: '/home/marketing' })
       }
     })

			// await this.axios
			// 	.post(api.add.save, {
			// 		mediaId: this.currentImgId,
			// 		msgId: '',
			// 		scope: this.form.resource === '全体推送' ? '0' : '1',
			// 		tagArrays: this.form.resource === '全体推送' ? this.tagList : this.tagIdsSave,
			// 		title: this.form.name,
			// 		tmplId: '',
			// 		type: 1,
			// 	})
			// 	.then(res => {
			// 		if (res && res.data && res.data.code === 0) {
			// 			this.$message({
			// 				message: res.data.message,
			// 				type: 'success',
			// 			})
			// 			this.$router.push({ path: '/home/marketing' })
			// 		}
			// 	})
		},
		// tagcount
		async getTagCount() {
			await this.axios
				.post(api.add.tagCount, {
					tagIds: this.tagIds,
					type: '1',
				})
				.then(res => {
					this.isCount = false
					if (res.data) this.currentTagCount = res.data.result
				})
		},
		// all
		async getTagCountAll() {
			await this.axios
				.post(api.add.tagCount, {
					tagIds: this.tagIdsList,
					type: '1',
				})
				.then(res => {
					this.isCount = false
					if (res.data) this.currentTagCount = res.data.result
				})
		},
		// 初始化  taglist
		async getTagList() {
			await this.axios.post(api.add.customerCacheList).then(res => {
        console.log(res);
        this.tagList = res.data;
				this.tagList.forEach(item => {
					this.tagIdsList.push(item.tagId)
				})
				this.isCount = true
				this.getTagCountAll()
			})
		},
		// 图文推送预览人数
		async getViewCount() {
			this.isCount = true
			await this.axios
				.post(api.add.getPreViewCount, {
					tagIds: this.tagIds,
				})
				.then(res => {
					if (res && res.data && res.data.code === 0) {
						if (res.data.result) {
							this.isCount = false
							const { tagNum, followNum, fourthNum } = res.data.result
							this.tagNum = tagNum
							this.followNum = followNum
							this.fourthNum = fourthNum
							this.successNum = (this.followNum - this.fourthNum)-0
						}
					}
				})
		},
	},
}
</script>
<style lang="stylus" scoped>
.two-item:nth-child(1)
	div
		height 161px !important
		margin-bottom 5px
		p
			width 254px !important
			float left
			position relative
			top 123px
			background-color rgba(0,0,0,0.2)
			padding 0 5px !important
		img
			width 259px !important
			height 161px !important
			float left
			margin-top -40px !important
.box-mask
	position absolute
	width 100%
	height 100%
	background-color rgba(0, 0, 0, 0.4)
	text-align center
	display flex
	font-size 16px
	color #fff
	top 0
	left 0
	pointer-event none
	opacity 0
	justify-content center
	align-items center
.box-mask:hover
	opacity 1
.active
	background #0096FF
	color #fff
.step-info
	margin-top 25px
	padding-bottom 20px
	.submit-dialog
		>>>.el-dialog__header
			padding 15px
			border-bottom 1px solid #e5e5e5
			.el-dialog__title
				text-align center
				font-size 18px
				color #73879C
	.el-input
		width 50%
	.step-choose
		margin-top 60px
		.add-material
			width 265px
			height 229px
			border 2px solid #e3e4e9
			color #e3e4e9
			text-align center
			position relative
			cursor pointer
			.add-title
				color #a4a4a4
				.add-plus
					font-size 91px
					font-weight 100
					margin 18px 0
					color #e3e4e9
					text-align center
		>>>.el-dialog__header
			padding 4px 20px 0px
		>>>.el-dialog--center
			text-align left
		>>>.el-dialog__body
			padding 0
		>>>.el-dialog__title
			line-height 24px
			font-size 15px
			color #73879C
		>>>.el-dialog--center .el-dialog__footer
			text-align center
		.add-container
			padding 20px
			.add-content
				border 1px solid #ececec
				margin-bottom 35px
				width 263px
				height 236px
				position relative
				img
					cursor pointer
					width 100%
					height 100%
				// .two-item:nth-child(1)
				// 	div
				// 		border 1px solid
				// 		height 132px !important
        //   	margin-bottom 5px
				// 		p
				// 			width 247px !important
				// 			float left
				// 			border 1px solid red
				// 		img
				// 			border 1px solid
		.add-line
			border-top 1px solid #e5e5e5
	.form-tags
		background-color #eee
		height 100%
		width 100%
		border-radius 4px
		.tag-info
			min-width 80px
			height 25px
			line-height 25px
			text-align center
			margin 15px
			cursor pointer
			border-radius 12px
	.form-button
		width 138px
		height 37px
		border none
		background-color rgba(51, 122, 183, 1)
		border-radius 3px
		color #fff
		font-family 'Arial Normal', 'Arial'
		font-weight 400
		font-style normal
		font-size 13px
		margin-right 15px
	.form-checknum
		color blue
		font-size 32px
	.form-vipnum
		border-left 1px solid red
		height 50px
		display inline-block
		padding-left 26px
		margin-left 26px

.mater-item:hover .mater-wrap {
  // background: black;
  display: block;
}
.mater-wrap {
    left: -2px;
    top: -2px;
    padding-right: 2px;
    padding-bottom: 2px;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
    display: none;
    cursor: pointer;
}
</style>
