/**
* Created by wang on 18/10/31.
*/
<template>
  <div class="index">
    <el-form ref="searchFrom" :model="searchFrom" label-width="80px" inline>
          <el-form-item label="领取时间">
            <el-date-picker
              v-model="searchFrom.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="{shortcuts:[today,yesterday,last7Day,last30Day]}"
              :default-time="['00:00:00','23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="激活时间">
            <el-date-picker
              v-model="searchFrom.active_time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="{shortcuts:[today,yesterday,last7Day,last30Day]}"
              :default-time="['00:00:00','23:59:59']">
            </el-date-picker>
          </el-form-item>
           <el-form-item label="是否激活">
          <el-select
          clearable
          @change="initPage"
              v-model="searchFrom.user_buy"
              size="medium"
            >
            <el-option label="已激活" :value="1"></el-option>
            <el-option label="未激活" :value="0"></el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="沟通状态">
          <el-select
          clearable
          @change="initPage"
              v-model="searchFrom.status"
              size="medium"
            >
            <el-option label="已激活" :value="1"></el-option>
            <el-option label="假号" :value="2"></el-option>
            <el-option label="没兴趣" :value="3"></el-option>
            <el-option label="待激活" :value="0"></el-option>
            </el-select>
            </el-form-item>
          <el-form-item label="来源">
            <el-input v-model="searchFrom.source" placeholder="名称"></el-input>
          </el-form-item>
       <el-form-item label="昵称">
        <el-input v-model="searchFrom.nickname" style="width: 110px"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchFrom.mobile" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-select v-model="searchFrom.goods_id" filterable placeholder="请选择" style="width: 150px" @change="initPage" clearable>
          <el-option v-for="(data,index) in goodList" :key="index" :label="data | filterGoods" :value="data.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="老师">
        <el-select v-model="searchFrom.teacher_id" filterable placeholder="请选择" @change="initPage" clearable filterable style="width: 180px">
          <el-option label="未指定" value="0">
          </el-option>
          <el-option v-for="(data,index) in teacherList" :key="index" :label="data.name" :value="data.id">
          </el-option>
        </el-select>
      </el-form-item>
          <el-form-item>
            <el-button type="primary" plain  @click="initPage">
              搜索
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain v-if="$store.state.export" @click="doExport">
              导出
            </el-button>
          </el-form-item>
          <!-- <el-button
            @click="editComment"
            type="primary"
            plain
            >
            批量编辑备注
          </el-button> -->
    </el-form>
    <div></div>
    <div style="position: relative">
      <el-tabs v-model="searchFrom.course_type" type="card" style="background: white;padding-top: 10px" @tab-click="initPage">
        <el-tab-pane label="全部" name="-1"/>
        <el-tab-pane label="月课" name="0"/>
        <el-tab-pane label="日课" name="1"/>
      </el-tabs>
      <div style="position: absolute;top: 10px;right: 10px;font-size: 14px" v-if="$store.state.distribution">
        老师:
        <el-select size="small" v-model="teacherId" placeholder="请选择" clearable style="width: 150px" filterable>
          <el-option label="暂不分配" value="0">
          </el-option>
          <el-option v-for="(data,index) in teacherList" :key="index" :label="data.name" :value="data.id">
          </el-option>
        </el-select>
        <el-button size="small"  type="success" @click="pullAll">批量分配</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
       @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column prop="nickname" label="领取人">
        <template slot-scope="scope">
          <div v-if='scope.row.user_id !== 0' >
            <img class="avatar" :src="scope.row.avatar" />
            <div>{{scope.row.nickname}}<br>(ID:{{scope.row.user_id}})</div>
          </div>
          <div v-if='scope.row.user_id === 0'>
            暂未绑定用户
          </div>
        </template>
      </el-table-column>
       <el-table-column prop="name" label="宝宝昵称">
      </el-table-column>
      <el-table-column prop="telephone" label="领取电话">
      </el-table-column>
      <!-- <el-table-column prop="source" label="来源">
      </el-table-column> -->
      <el-table-column prop="periods_title" label="期数">
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名称">
      </el-table-column>
     <el-table-column prop="source" label="来源">
        <template slot-scope="scope">
          {{scope.row.source}}({{scope.row.invite_name}})
        </template>
      </el-table-column>
      <el-table-column prop="teacher_name" label="班级老师">
      </el-table-column>
      <el-table-column prop="status" :formatter="externalLaunchStatus" label="沟通状态" width="120">
        
      </el-table-column>
      <el-table-column prop="active_at" label="激活时间" width="90">
        <template slot-scope="scope">
          {{scope.row.active_at === '0000-00-00 00:00:00'?'未激活':scope.row.active_at}}
        </template>
      </el-table-column>
      <el-table-column prop="create_at" label="领取时间" width="90">
      </el-table-column>
      <el-table-column prop="desc" label="备注">
      </el-table-column>
      <el-table-column label="操作" fixed="right" v-if="!$store.state.readonly" width="180">
        <template slot-scope="scope">
          <el-button @click="editNote(scope.row.id, scope.row.desc)" size="mini" plain type="primary">编辑备注</el-button>
        </template>
      </el-table-column>
    </el-table>
    <page :total="total" :limit="limit" @pageChange="onPageChange" @sizeChange="onSizeChange"/>
    <el-dialog
      title="编辑备注"
      center
      append-to-body
      :visible.sync="showCommentDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="600px">
      <div>
        <el-form ref="commentFrom" :model="commentForm">
          <el-form-item prop="desc">
            <el-input type="textarea" v-model="commentForm.desc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button @click="showCommentDialog = false;commentForm={}">取 消</el-button>
            <el-button type="primary" @click="saveComment">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
  import page from '../framework/page'
  import CommonJs from '../../util/common';
  import {getAdsInnerListApi,updateAdsInnerApi,updateAdsInnerPlApi,getTeacherListApi,getGoodsListApi,adsTeacherApi} from "../../service/api";
  import {
  GOODSTYPE,
  externalLaunchStatusParams
} from "../../util/wordbook";
  export default {
    name: "index",
    components:{
      page
    },
    data(){
      return {
        today:{
          text:'今天',
          onClick:(vm)=>{
            vm.$emit('pick', [this.formatTime(new Date())+' 00:00:00',this.formatTime(new Date())+' 23:59:59'])
          }
        },
        yesterday:{
          text:'昨天',
          onClick:(vm)=>{
            let preDate = this.formatTime(new Date(new Date().getTime() - 24*60*60*1000));
            vm.$emit('pick', [preDate+' 00:00:00',preDate+' 23:59:59'])
          }
        },
        last30Day:{
          text:'过去30天',

          onClick:(vm)=>{
            let preDate = this.formatTime(new Date(new Date().getTime() - 30*24*60*60*1000));
            vm.$emit('pick', [preDate+' 00:00:00',this.formatTime(new Date())+' 23:59:59']);
          }
        },
        last7Day:{
          text:'过去7天',
          onClick:(vm)=>{
            let preDate = this.formatTime(new Date(new Date().getTime() - 7*24*60*60*1000));
            vm.$emit('pick', [preDate+' 00:00:00',this.formatTime(new Date())+' 23:59:59']);
          }
        },
        teacherId:null,
        secId:[],
        total:0,
        nowPage:1,
        limit: 10,
        searchFrom: {
          source:'',
          course_type:'-1',
        },
        tableData:[],
        commentForm: {},
        showCommentDialog: false,
        teacherList:[],
        goodList: [],
      }
    },
    filters: {
    filterStatus: function(value) {
      let msg = "";
      if (value === 0) {
        msg = "未绑定";
      } else {
        msg = "已绑定";
      }
      return msg;
    },
    filterGoods(val) {
      return (
        "[" +
        val.id +
        "]" +
        "[" +
        GOODSTYPE[val.goods_type] +
        "]" +
        "[" +
        val.current_price / 100 +
        "元]" +
        val.name
      );
    }
  },
    created(){
      this.initPage()
      this.getGoodsOption();
      this.getTeacherList()
    },
    methods:{
      externalLaunchStatus(row){
        return externalLaunchStatusParams[row.status]
      },
      formatTime(date){
        console.log(date)
      let year = date.getFullYear();
      let Month = date.getMonth()+1;
      if(Month < 10){
        Month = `0${Month}`
      }
      let Day = date.getDate();
      if(Day<10)Day = `0${Day}`;
      return `${year}-${Month}-${Day}`;
    },
      getGoodsOption() {
      let json = {
        page: 1,
        limit: 100,
        goods_type:'1,2'
      };
      getGoodsListApi(json).then(res => {
        this.goodList = res.list;
      });
    },
      pullAll(){
      if(this.secId.length < 1){
        this.$message('请选择订单');
        return false;
      }
      if(!this.teacherId){
        this.$message('请选择老师');
        return false;
      }
      let json = {
        order_ids:[]
      };
      this.secId.forEach(i=>{
        json.order_ids.push(i)
      });
      this.$confirm(`是否确定将这${json.order_ids.length}笔订单分配给该老师?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adsTeacherApi(this.teacherId,{ids:json.order_ids.join(',')}).then(res=>{
          // this.secId = [];
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.initPage();
        })
      }).catch(() => {
      });
    },
     getTeacherList() {
      let json = {
        page: 1,
        limit: 200
      };
      getTeacherListApi(json).then(res => {
        this.teacherList = res.list;
      });
    },
      handleSelectionChange(val){
        this.secId = []
        val.forEach(element => {
          this.secId.push(element.id)
        });
        // console.log(this.secId)
      },
      initPage(){
        let json = {
          limit: this.limit,
          page: this.nowPage
        }
        // if (this.searchFrom.time) {
        //   json.time = this.searchFrom.time
        // }
        if (this.searchFrom.source) {
          json.source = this.searchFrom.source
        }
        if (this.searchFrom.mobile) {
        json.mobile = this.searchFrom.mobile;
      }
      if (this.searchFrom.status) {
        json.status = this.searchFrom.status;
      }
      if (this.searchFrom.course_type !== '-1') {
        json.course_type = this.searchFrom.course_type;
      }
       if (this.searchFrom.nickname) {
         debugger
        json.nickname = this.searchFrom.nickname;
      }
       if (this.searchFrom.user_id) {
        json.user_id = this.searchFrom.user_id;
      }
      if (this.searchFrom.teacher_id) {
        json.teacher_id = this.searchFrom.teacher_id;
      }
      if (this.searchFrom.goods_name) {
        json.goods_name = this.searchFrom.goods_name;
      }
      if (this.searchFrom.user_buy != -1) {
        json.user_buy = this.searchFrom.user_buy;
      }
      if (this.searchFrom.order_id) {
        json.order_id = this.searchFrom.order_id;
      }
      if (this.searchFrom.goods_id) {
        json.goods_id = this.searchFrom.goods_id;
      }
        if(this.searchFrom.time && this.searchFrom.time.length ==2 ){
          json.start_at = this.searchFrom.time[0];
          json.end_at = this.searchFrom.time[1]
        }
        if(this.searchFrom.active_time && this.searchFrom.active_time.length ==2 ){
          json.active_start_at = this.searchFrom.active_time[0];
          json.active_end_at =this.searchFrom.active_time[1]
        }
        getAdsInnerListApi(json).then((res)=>{
          this.tableData = res.list;
          this.total = res.total
        })
      },
      onPageChange(val){
        this.nowPage = val
        this.initPage()
      },
      onSizeChange(val){
        this.nowPage = 1
        this.limit = val
        this.initPage()
      },
      doExport(){
        let query = `?type=export`;
        if(this.searchFrom.source){
          query = query + '&source=' + this.searchFrom.source
        }
        if(this.searchFrom.mobile){
          query = query + '&mobile=' + this.searchFrom.mobile
        }
         if(this.searchFrom.status){
          query = query + '&status=' + this.searchFrom.status
        }
        if(this.searchFrom.course_type !== '-1'){
          query = query + '&course_type=' + this.searchFrom.course_type
        }
        if(this.searchFrom.user_buy !== '-1'){
          query = query + '&user_buy=' + this.searchFrom.user_buy
        }
         if(this.searchFrom.nickname){
          query = query + '&nickname=' + this.searchFrom.nickname
        }
         if(this.searchFrom.user_id){
          query = query + '&user_id=' + this.searchFrom.user_id
        }
         if(this.searchFrom.teacher_id){
          query = query + '&teacher_id=' + this.searchFrom.teacher_id
        }
         if(this.searchFrom.goods_name){
          query = query + '&goods_name=' + this.searchFrom.goods_name
        }
         if(this.searchFrom.order_id){
          query = query + '&order_id=' + this.searchFrom.order_id
        }
         if(this.searchFrom.goods_id){
          query = query + '&goods_id=' + this.searchFrom.goods_id
        }
        if(this.searchFrom.time && this.searchFrom.time.length ==2){
          query = query + '&start_at=' +  this.searchFrom.time[0];
          query = query + '&end_at=' +  this.searchFrom.time[1]
        }
        if(this.searchFrom.active_time && this.searchFrom.active_time.length ==2){
          query = query + '&active_start_at=' +  this.searchFrom.active_time[0];
          query = query + '&active_end_at=' +  this.searchFrom.active_time[1]
        }
        window.open(`/api/admin/ads/export/all${query}`)
      },
      saveComment(){
        // let id = this.commentForm.id;
        let id 
        if(this.commentForm.id){
          id = this.commentForm.id
        }else{
          id = this.secId.join(',')
        }
        
        let desc = this.commentForm.desc ? this.commentForm.desc : '';
        if(!desc) return;
        this.$confirm('确认编辑备注', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateAdsInnerPlApi({ids:id,desc:desc}).then(res=>{
            this.$message({
              type: 'success',
              message: '编辑备注成功'
            });
            this.showCommentDialog = false
            this.initPage();
          });
        })
      },
      editNote(id, desc){
        this.showCommentDialog = true;
        this.commentForm = {
            id: id,
            desc: desc
          };
      },
      editComment(id, desc) {
        if(this.secId.length>0){
          this.showCommentDialog = true;
          // this.commentForm = {
          //   id: id,
          //   desc: desc
          // };
        }else{
          this.$message({
              type: 'warning',
              message: '请选择'
            });
        }
        
      },
    }
  }
</script>

<style scoped lang="less">
  .index {
    padding: 20px 0;
  }
  .sms {
  padding: 20px 0;
}
.avatar {
  width: 50px;
  min-width: 50px;
  margin-right: 10px;
  height: 50px;

  border-radius: 50%;
}
</style>