<template>
  <div class="createMassMsg" v-loading="loading">
    <div class="backBox" @click="$router.go(-1)">
      <div class="back">
        <i class="el-icon-back"></i>
        <span>返回</span>
      </div>
    </div>
    <div v-if="!loading" class="bg-ffffff" style="padding: 15px;">
      <h3 class="bigTitle">朋友圈类型 </h3>
      <div class="self-hint" style="margin-top:10px;width:730px">
        <i class="el-icon-message-solid"></i>
        <div v-if="fc_type==1">管理员可创建客户朋友圈发表任务，成员确认内容后即可发布到朋友圈中，每位客户的朋友圈每个月最多展示4条企业发表的内容电脑上暂不支持发送企微朋友圈。 </div>
        <div v-if="fc_type==0">管理员可创建客户朋友圈发表任务，成员确认内容后即可发布到朋友圈中，每位客户的朋友圈每天最多展示3条个人发表的内容。电脑上暂不支持发送企微朋友圈。 </div>
      </div>
      <div class="regulations">
        <label>朋友圈类型:</label>
        <div>
          <div style="display:flex">
            <el-radio v-model="fc_type" :label="1">企业发表</el-radio>
            <el-radio v-model="fc_type" :label="0">个人发表</el-radio>
          </div>
        </div>
      </div>
      <div class="line" style="margin-top:20px"></div>

      <h3 class="bigTitle">编辑朋友圈</h3>
      <div class="regulations">
        <label><em>*</em>朋友圈主题</label>
        <el-input placeholder="例：活动推送/拉新等" style="width:300px" v-model.trim="themeName" clearable size="small"></el-input>
      </div>
      <div class="regulations">
        <label><em>*</em>发表成员:</label>
        <div>
          <div style="display:flex">
            <el-radio :disabled="!editFlag" v-model="is_for_all" :label="1">全部员工</el-radio>
            <el-radio :disabled="!editFlag" v-model="is_for_all" :label="0">部分员工</el-radio>
          </div>
          <self-customerservice-f-c :disabled="!editFlag" v-if="is_for_all==0" title='' width="300px" :afferent_users='user_id_list' @customerDefine="(val)=>{user_id_list=val;}" style="margin-top: 10px"></self-customerservice-f-c>
        </div>
      </div>
      <div class="regulations">
        <label><em>*</em>选择客户</label>
        <div>
          <div>
            <el-radio v-model="customer_filter" :disabled="!editFlag" :label="0" @change="changeEvent">全部客户</el-radio>
            <el-radio v-model="customer_filter" :disabled="!editFlag" :label="1" @change="changeEvent">筛选客户</el-radio>
          </div>
          <div class="" v-if="customer_filter==1">
            <enterprise-tag title="" width="300px" :disabled="!editFlag" :afferent_obj='afferent_tag_obj' :reset='resetFlag' @tagDefine="tagDefine" style="margin:0;margin-top: 10px"></enterprise-tag>
          </div>
          <div class="customer_all">将群发消息给{{customer_filter==0?'全部客户的':customer_filter==1?'筛选客户的':''}}
            <span @click="massMsg_customerMatchCount" v-if="isLookCount" class="pointer"><i class="el-icon-loading" v-if="customerMatchCountLoading"></i> {{!customerMatchCountLoading?'查看':''}}</span>
            <span v-else>{{msg_count}}</span>
            个客户
          </div>
        </div>
      </div>
      <div class="regulations">
        <label>消息内容1</label>
        <el-input
          class="contentOne"
          style="width: 50%"
          type="textarea"
          rows="6"
          autocomplete="off"
          placeholder="请输入消息内容"
          v-model="content1"
          show-word-limit
          maxlength="1000"></el-input>
      </div>
      <div class="regulations">
        <label>消息内容2</label>
        <div style="width: 100%">
          <div style="display:flex">
            <el-radio v-model="con_type" :label="0" style="width: 60px">图片</el-radio>
            <el-radio v-model="con_type" :label="1" style="width: 60px">视频</el-radio>
            <el-radio v-model="con_type" :label="2" >图文链接</el-radio>
          </div>
          <conTwo :conType="con_type"></conTwo>
        </div>
      </div>

      <div class="line" style="margin-top:20px"></div>
      <h3 class="bigTitle" style="margin-top:20px">高级设置: </h3>
      <div class="regulations">
        <label><em>*</em>发布方式:</label>
        <div>
          <div style="display:flex">
            <el-radio v-model="send_type" :label="1">立即发送</el-radio>
            <el-radio v-model="send_type" :label="0">定时发送</el-radio>
          </div>
          <div style="margin-top:15px;" v-if="send_type==0">
            <el-date-picker v-model="send_time.date" :picker-options="pickerOptions" :disabled="!editFlag" size="small" value-format="yyyy-MM-dd" type="date" style="width:160px" placeholder="选择日期"></el-date-picker>
            <el-time-picker v-model="send_time.time" :disabled="!editFlag" size="small" format="HH:mm" value-format="HH:mm:ss" placeholder="请输入时间" style="width:130px"></el-time-picker>
          </div>
        </div>
      </div>

      <div class="regulations regulations2">
        <label></label>
        <div class="operationProcess">
          <div class="process-title">
            <h3>企业发表朋友圈的操作流程</h3>
            <div class="zhankai" @click="processFlag=!processFlag">展开 <i :class="['el-icon-arrow-down',processFlag?'reversalAnimation':'']"></i></div>
          </div>
          <p class="process-hint">1、创建完朋友圈后，员工将在企业微信上收到【客户朋友圈】新消息通知</p>
          <p class="process-hint">2、员工点击【客户朋友圈】，点击待发送的朋友圈，可一键将朋友圈内容发表</p>
          <img v-if="processFlag" src="@/assets/img/exterprise-mass-send.png" class="img" alt="">
        </div>
      </div>
      <button class="button" @click="welcomeMsg_set">通知成员发送</button>
    </div>
  </div>
</template>
<script>
import selfCustomerserviceFC from '@/components/assembly/screen/customerServiceFC.vue'
import editCon from '@/components/assembly/editCon.vue'
import welcomEdit from '@/components/assembly/welcom_edit.vue'
import enterpriseTag from '@/components/assembly/screen/enterpriseTag.vue'
import datePicker from '@/components/assembly/screen/datePicker.vue'
import conTwo from '@/components/assembly/conTwo.vue'
export default {
  name:'createFriendsCircle',
  components: { selfCustomerserviceFC, editCon, welcomEdit, enterpriseTag, datePicker, conTwo },
  data () {
    return {
      loading: false,
      user_id_list: [],
      fc_type: 0,
      editFlag: true,
      is_day_parting: false,
      name: '',
      deleteTimeIntervalList: [],//删除的分时段列表
      timeIntervalList: [],//分时段列表
      init_welcom_con: {
        is_day_parting: 1,//是否为分时段欢迎语 0:否 1:是
        weeks: [1, 2, 3, 4, 5, 6, 0],
        start_time: '',
        end_time: '',
        content: '',
        attachments: [],
      },
      main_msg_data: {
        "is_day_parting": 0,
        "weeks": [],
        "start_time": "",
        "end_time": "",
        "content": '',
        "attachments": []
      },
      dataInfo: {},
      is_for_all: 1,
      customer_filter: 0,
      gender: 3,
      customerMatchCountLoading: false,
      isLookCount: true,//是否查看群发的客户数
      msg_count: '',

      afferent_tag_obj: {
        tag_id_list: [],
        tag: 1
      },
      resetFlag: false,
      send_type:1,
      processFlag: false,
      send_time: {
        date: '',
        time: ''
      },

      pickerOptions: {
        disabledDate (time) {
          return time < Date.now() - 8.64e7;
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '明天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周后',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      content1:'',
      con_type:0,
      themeName:''
    }
  },
  created () {
    if (this.$route.params.rule_id) {//详情
      this.detail()
    } else {
      this.loading = false;
    }
  },
  methods: {
    changeEvent () {
      this.isLookCount = true
    },
    tagDefine (data) {//标签选择回调
      this.isLookCount = true
      if (data.tag == 1 || data.tag == 2) {
        if (data.tag_id_list && data.tag_id_list.length != 0) {
          this.tag_info = {
            tag_id_list: data.tag_id_list,
            tag_type: data.tag
          }
        } else {
          this.tag_info = {
            tag_id_list: [],
            tag_type: 0
          }
        }
      } else {
        this.tag_info = {
          tag_id_list: [],
          tag_type: data.tag
        }
      }
    },
    massMsg_customerMatchCount () {//群发规则匹配客户数查询
      if (this.customerMatchCountLoading) return;
      this.customerMatchCountLoading = true;
      let params = {
        senders: this.is_for_all == 0 ? this.user_id_list.join(',') : '',
        customer_filter: this.customer_filter
      }
      // if (this.customer_filter == 1) {//筛选客户
      //   params.gender = this.gender;
      //   params.add_time_start = this.afferent_time && this.afferent_time.length > 1 ? this.afferent_time[0] : '';
      //   params.add_time_end = this.afferent_time && this.afferent_time.length > 1 ? this.afferent_time[1] : '';
      //   params.tag_screen_type = this.tag_info && this.tag_info.tag_type ? this.tag_info.tag_type : 0;
      //   params.tag_list = this.tag_info && this.tag_info.tag_id_list ? this.tag_info.tag_id_list.join(',') : '';
      //   params.exclude_tag_list = this.exclude_tag_info && this.exclude_tag_info.tag_id_list ? this.exclude_tag_info.tag_id_list.join(',') : '';
      // }
      this.$axios.get(this.URL.BASEURL + this.URL.massMsg_customerMatchCount, {
        params
      }).then((res) => {
        var res = res.data
        this.customerMatchCountLoading = false
        this.isLookCount = false
        if (res && res.errno == 0) {
          this.msg_count = res.rst.total;
        } else if (res.errno != 4002) {
          this.$message({
            message: res.err,
            type: "warning"
          })
        }
      }).catch((err) => {
        this.customerMatchCountLoading = false
      });
    },
    detail () {//详情
      this.loading = true
      this.$axios.get(this.URL.BASEURL + this.URL.welcomeMsg_detail, {
        params: {
          rule_id: this.$route.params.rule_id
        }
      }).then((res) => {
        var res = res.data
        this.loading = false
        if (res && res.errno == 0) {
          this.dataInfo = res.rst;
          this.fc_type = res.rst.fc_type;
          this.user_id_list = res.rst.users ? res.rst.users.split(',') : [];
          this.name = res.rst.name;
          let msg_list = res.rst.msg_list;
          msg_list.forEach((item) => {
            // item.content = item.content ? item.content.replace('%NICKNAME%', '「客户昵称」') : '';
            item.attachments = item.attachments && item.attachments != '' ? JSON.parse(item.attachments) : [];
            item.weeks = item.weeks ? item.weeks.split(',') : []
          })
          let main_msg_data = msg_list.filter((v) => {//特定有一个主欢迎语内容
            return v.is_day_parting == 0
          })
          this.main_msg_data = main_msg_data && main_msg_data.length > 0 ? main_msg_data[0] : {};

          this.timeIntervalList = msg_list.filter((v) => {//分时段欢迎语内容
            return v.is_day_parting == 1
          })

          if (msg_list.length > 1) {
            this.is_day_parting = true
          }
        } else if (res.errno != 4002) {
          this.$message({
            message: res.err,
            type: "warning"
          })
        }
      }).catch((err) => {
        this.loading = false
      });
    },
    getAttachment (val) {
      this.main_msg_data.attachments = val;
    },
    getWelcomEdit (val, index) {//分时段编辑
      this.$set(this.timeIntervalList, index, val)
    },
    deleteWelcomCon (index) {//删除分时段
      if (this.$route.params.rule_id && this.timeIntervalList[index].msg_id) {//删除的分时段内容
        let obj = JSON.parse(JSON.stringify(this.timeIntervalList[index]))
        obj.operate = 'del';
        this.deleteTimeIntervalList.push(obj)
      }
      this.timeIntervalList.splice(index, 1)
    },
    addWelcom () {//添加分时段
      this.timeIntervalList.push(this.init_welcom_con)
    },

    welcomeMsg_set () {//保存
      if (this.name == '') {
        this.$message({
          message: '请输入欢迎语标题！',
          type: "warning"
        })
        return
      }
      if (this.fc_type == 0 && (!this.user_id_list || this.user_id_list.length == 0)) {
        this.$message({
          message: '请选择使用成员！',
          type: "warning"
        })
        return
      }
      if (this.main_msg_data.content == '' && (!this.main_msg_data.attachments || this.main_msg_data.attachments == '' || this.main_msg_data.attachments.length == 0)) {
        this.$message({
          message: '请输入【主】欢迎语内容！',
          type: "warning"
        })
        return
      }
      if (this.main_msg_data.content != '' && this.$getStrBytes(this.main_msg_data.content) > 4000) {
        this.$message({
          message: '请检查【主】欢迎语内容，最多4000个字节，已超出！',
          type: "error"
        })
        return
      }
      let msg_data = []
      if (this.is_day_parting) {//开启分段欢迎语
        for (let i = 0; i < this.timeIntervalList.length; i++) {
          let item = this.timeIntervalList[i];
          if (item.content == '' && (!item.attachments || item.attachments == '' || item.attachments.length == 0)) {
            this.$message({
              message: `请输入【时段${i + 1}】欢迎语内容！`,
              type: "warning"
            })
            return
          }
          if (item.content != '' && this.$getStrBytes(item.content) > 4000) {
            this.$message({
              message: `请检查【时段${i + 1}】欢迎语内容，最多4000个字节，已超出！`,
              type: "error"
            })
            return
          }
          if (!item.weeks || item.weeks.length == 0) {
            this.$message({
              message: `请选择【时段${i + 1}】发送日期！`,
              type: "warning"
            })
            return
          }
          if (!item.start_time || item.start_time == '') {
            this.$message({
              message: `请输入【时段${i + 1}】发送开始时间！`,
              type: "warning"
            })
            return
          }
          if (!item.end_time || item.end_time == '') {
            this.$message({
              message: `请输入【时段${i + 1}】发送结束时间！`,
              type: "warning"
            })
            return
          }
          if (this.$date_compatible(('2020-04-01 ' + item.start_time)).getTime() > this.$date_compatible(('2020-04-01 ' + item.end_time)).getTime()) {
            this.$message({
              message: `请正确输入【时段${i + 1}】发送时间！`,
              type: "warning"
            })
            return
          }
        }
        msg_data = msg_data.concat(this.timeIntervalList)
      } else {//关闭分段欢迎语
        let delete_arr = JSON.parse(JSON.stringify(this.timeIntervalList));
        delete_arr = delete_arr.filter((v) => {
          return v.msg_id
        })
        delete_arr.forEach((item) => {
          item.operate = 'del'
        })
        this.deleteTimeIntervalList = this.deleteTimeIntervalList.concat(delete_arr)
      }
      msg_data = msg_data.concat(this.deleteTimeIntervalList);//删除的分时段内容

      msg_data.push(this.main_msg_data)
      msg_data.forEach((item) => {
        item.weeks = item.weeks.join(',');
        // item.content = item.content.replace('「客户昵称」', '%NICKNAME%')
        item.attachments = item.attachments == '' || item.attachments.length == 0 ? '' : JSON.stringify(item.attachments)
      })

      this.$loading(this.$loadingConfig)
      this.$axios.post(this.URL.BASEURL + this.URL.welcomeMsg_set, {
        rule_id: this.$route.params.rule_id ? this.$route.params.rule_id : '',
        name: this.name,
        fc_type: this.fc_type,
        users: this.fc_type == 0 ? this.user_id_list.join(',') : '',
        msg_data: msg_data
      }).then((res) => {
        var res = res.data
        this.$loading(this.$loadingConfig).close()
        if (res && res.errno == 0) {
          this.$router.go(-1)
        } else if (res.errno != 4002) {
          this.$message({
            message: res.err,
            type: "warning"
          })
        }
      }).catch((err) => {
        this.$loading(this.$loadingConfig).close()
      });
    }
  }
}
</script>
<style lang="scss">
.contentOne{
  .el-textarea__inner{
    background-color: #fafafa;
  }
}
</style>
<style lang="scss" scoped>
@import "./create.scss";
.reversalAnimation {
  transform: rotate(180deg);
}
.button {
  width: 178px;
  height: 40px;
  background: #00b38a;
  border-radius: 5px;
  color: #ffffff;
  font-size: 14px;
  border: none;
  margin: 40px 100px;
}
.add_welcom_hint {
  color: #00b38a;
  font-size: 16px;
  font-weight: bold;
  margin-left: 90px;
  margin-top: 10px;
  margin-bottom: 20px;
  cursor: pointer;
  display: inline-block;
}
.screeningCustomers {
  width: 659px;
  background: #fafafa;
  border: 1px solid #e9e9e9;
  padding: 15px;
  padding-bottom: 0;
  margin-top: 15px;
  .screeningItem {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    label {
      width: 100px;
      color: #666666;
      font-size: 14px;
      line-height: 20px;
      display: inline-block;
      text-align: right;
      line-height: 30px;
    }
    .screening-hint {
      color: #777777;
      font-size: 14px;
      line-height: 20px;
      margin-top: 10px;
    }
  }
}
.customer_all {
  background: #edf8fd;
  color: #383e47;
  font-size: 14px;
  line-height: 21px;
  padding: 6px 15px;
  margin-top: 10px;
  span {
    color: #43b083;
    font-weight: bold;
  }
}

.operationProcess {
  width: 710px;
  background: #fafafa;
  padding: 15px;
  .process-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    h3 {
      color: #333333;
      font-size: 15px;
      font-weight: bold;
    }
    .zhankai {
      color: #666;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.5s;
    }
  }
  .process-hint {
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.45);
    line-height: 20px;
    margin-bottom: 8px;
  }
  .img {
    width: 100%;
  }
}
</style>
