<template>
  <div class="channel-trans-list">
    <el-form ref="searchFrom" :model="searchFrom" label-width="100px" inline>
      <!--<el-form-item label="更新时间">
        {{updateTime ? updateTime : '-'}}
      </el-form-item>-->
      <el-form-item label="进量日期">
        <el-date-picker
          v-model="searchFrom.payTime"
          type="datetimerange"
          range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="{shortcuts:[today,yesterday,last7Day,last30Day]}"
          :default-time="['00:00:00','23:59:59']"
          @change="getChannelTransList"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="开结课日期">
        <el-date-picker
          v-model="searchFrom.classTime"
          type="datetimerange"
          range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="{shortcuts:[classToday,classYesterday,classLast7Day,classLast30Day]}"
          :default-time="['00:00:00','23:59:59']"
          @change="getChannelTransList"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="商品课时数">
        <!-- <el-input v-model="searchFrom.watch_num" style="width: 80px"></el-input> -->
        <el-select
          v-model="searchFrom.watch_num"
          filterable
          placeholder="请选择"
          style="width: 150px"
          clearable
          @change="selectChange">
          <el-option
            v-for="(data,index) in watchList"
            :key="index"
            :label="data.title"
            :value="data.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道类别">
        <el-select
          v-model="searchFrom.type_id"
          filterable
          placeholder="请选择"
          style="width: 150px"
          @change="getChannelTransList"
          clearable>
          <el-option
            v-for="(data,index) in typeList"
            :key="index"
            :label="data.value"
            :value="data.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道code">
        <el-input v-model="searchFrom.invite_type" style="width: 110px"></el-input>
      </el-form-item>
      <el-form-item label="期数名称" prop="periods_title">
        <el-select
          :popper-class="'refresh-select-multi width-480'"
          style="width: 480px"
          placeholder="请选择"
          v-model="searchFrom.periods_id"
          @change="onPeriodChange"
          multiple
          clearable
          filterable>
          <el-option v-for="item in periodList" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="组ID">
        <el-input v-model="searchFrom.squad" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="老师">
        <el-select
          v-model="searchFrom.teacher_id"
          filterable
          placeholder="请选择"
          @change="changeTeacher"
          clearable
          style="width: 100px">
          <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>
        <div class="flexRow">
          <el-button type="primary" plain @click="seachData">搜索</el-button>
          <el-button type="primary" plain @click="exportDataTable" v-if="false">导出</el-button>
        </div>
      </el-form-item>
    </el-form>

    <div class="update-time">最近更新时间：{{updateTime ? updateTime : '-'}}</div>
    <el-table border :span-method="objectSpanMethod" :data="list" :style="{width: width+'px'}" fixed>
      <!-- <div
        class="no-data"
        v-if="list.length == 0"
        style="background:#fff;textAlign: center;color: #909399;padding: 10px 0;"
      >暂无数据</div>-->
      <el-table-column prop="cur_date" label="进量日期"></el-table-column>
      <el-table-column prop="invite_type" label="渠道类型"></el-table-column>
      <!-- <el-table-column prop="watch_num" label="商品课时数"></el-table-column> -->
      <el-table-column prop="goods_name" label="商品名称" width="180"></el-table-column>
      <el-table-column prop="periods_title" label="期数名称">
        <!--<template slot-scope="scope">
          {{periodName(scope.row)}}
        </template>-->
      </el-table-column>
      <el-table-column
        prop="duration_over_at" label="开课看课时间"
        style="font-size:12px;" width="200">
        <template slot-scope="scope">
          开课日期：{{scope.row.start_at}}
          <br>
          结课日期：{{scope.row.over_at}}
        </template>
      </el-table-column>
      <el-table-column prop="squad" label="组ID"></el-table-column>
      <el-table-column prop="teacher_name" label="老师名称"></el-table-column>
      <el-table-column prop="total_num" label="购买人数"></el-table-column>
      <el-table-column prop="class_num" label="班级人数"></el-table-column>
      <el-table-column prop="teacher_friend_num" label="老师主动添加好友人数"></el-table-column>
      <el-table-column prop="user_friend_num" label="用户主动添加好友人数"></el-table-column>
      <el-table-column prop="come_num" label="到课人数"></el-table-column>
      <el-table-column prop="one_buy_num" label="一年课购买人数"></el-table-column>
      <el-table-column prop="two_buy_num" label="两年课购买人数"></el-table-column>
      <el-table-column prop="one_buy_money" label="一年课转化金额"></el-table-column>
      <el-table-column prop="two_buy_money" label="两年课转化金额"></el-table-column>
    </el-table>
    <page
      :nowPage="nowPage"
      :total="total"
      :limit="limit"
      @pageChange="onPageChange"
      @sizeChange="onSizeChange"
    />
  </div>
</template>
<script>
import {
  getTeacherListApi,
  getchannelTransListApi,
  getPeriodsApi,
  getGoodsListApi,
  exportExcelApi,
  getPeriodsOtherListApi,
  getConfigListApi,
  getUpdateTimeApi
} from "../../service/api";
import page from "../framework/page";
import { GOODSTYPE, CLASSSOURCE } from "../../util/wordbook";

export default {
  name: "channelTransList",
  data() {
    return {
      updateTime: '',
      typeList:[],
      width: 0,
      nowPage: 1,
      limit: 20,
      list: [],
      goods_id: null,
      teacherList: [],
      goodsList: [],
      periodList: [],
      total: 0,
      today: {
        text: "今天",
        onClick: () => {
          this.searchFrom.payTime = [
            this.formatTime(new Date()) + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      yesterday: {
        text: "昨天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
          );
          this.searchFrom.payTime = [
            preDate + " 00:00:00",
            preDate + " 23:59:59"
          ];
        }
      },
      last30Day: {
        text: "过去30天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)
          );
          this.searchFrom.payTime = [
            preDate + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      last7Day: {
        text: "过去7天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000)
          );
          this.searchFrom.payTime = [
            preDate + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      classToday: {
        text: "今天",
        onClick: () => {
          this.searchFrom.classTime = [
            this.formatTime(new Date()) + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      classYesterday: {
        text: "昨天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
          );
          this.searchFrom.classTime = [
            preDate + " 00:00:00",
            preDate + " 23:59:59"
          ];
        }
      },
      classLast30Day: {
        text: "过去30天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)
          );
          this.searchFrom.classTime = [
            preDate + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      classLast7Day: {
        text: "过去7天",
        onClick: () => {
          let preDate = this.formatTime(
            new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000)
          );
          this.searchFrom.classTime = [
            preDate + " 00:00:00",
            this.formatTime(new Date()) + " 23:59:59"
          ];
        }
      },
      spanArr: [],
      contentSpanArr: [],
      searchFrom: {
        payTime: [],
        classTime:[],
        start_at: "",
        end_at: "",
        invite_type: "",
        invite_name: "",
        watch_num: "",
        periods_id: "",
        squad: "",
        teacher_id: "",
        periods_title: ""
      },
      propertyList: [],
      watchList: [
        { id: 0, title: 5 },
        { id: 1, title: 6 },
        { id: 2, title: 10 },
        { id: 3, title: 20 }
      ]
    };
  },
  components: { page },
  methods: {
    periodName(row) {
      //return `【${row.goods_id}】${row.periods_title}${row.watch_num}课时（${row.start_at.slice(5).replace('-', '')}）-d${this.title.has_watch_num}`
      //return `【${row.goods_id}】${row.periods_title}${row.watch_num}课时（${row.start_at.slice(5).replace('-', '')}）`
    },
    seachData() {
      this.total = 0;
      this.nowPage = 1;
      this.getChannelTransList();
    },
    onPeriodChange(value) {
      let str = "";
      if (value.length > 1) {
        str = value.join(",");
      } else {
        str = value[0];
      }
      this.periods_id = str;
      console.log(str);
    },
    exportDataTable() {
      let json = {};
      if(this.searchFrom.sort_value){
        json.sort_value = this.searchFrom.sort_value;
        json.sort_key = this.searchFrom.sort_key;
      }
      if (
        this.searchFrom.start_at.length > 0 &&
        this.searchFrom.end_at.length > 0
      ) {
        json.start_at = this.searchFrom.start_at;
        json.end_at = this.searchFrom.end_at;
      }
      if (this.searchFrom.teacher_id) {
        json.teacher_id = this.searchFrom.teacher_id;
      }
      if (this.searchFrom.type_id) {
        json.type_id = this.searchFrom.type_id;
      }
      if (this.searchFrom.invite_type.length > 0) {
        json.invite_type = this.searchFrom.invite_type;
      }
      if (this.periods_id) {
        json.periods_ids = this.periods_id;
      }
      if (this.searchFrom.squad) {
        json.squad = this.searchFrom.squad;
      }
      if (this.searchFrom.watch_num) {
        json.watch_num = this.searchFrom.watch_num;
      }
      exportExcelApi("/api/admin/channel/class/list/export", json);
    },
    objectSpanMethod(data) {
      // if (data.columnIndex === 0) {
      //   //用于设置要合并的列s
      //   const _row = this.spanArr[data.rowIndex];
      //   const _col = _row > 0 ? 1 : 0;
      //   return {
      //     rowspan: _row, //合并的行数
      //     colspan: _col //合并的列数
      //   };
      // } else {
      //   return false;
      // }
    },
    handleItemChange(val) {
      getPeriodsApi({ goods_id: val[0], limit: 100 }).then(res => {
        res.list.forEach(i => {
          i.name = i.title;
        });
        this.goodsList.find(i => {
          return i.id === val[0];
        }).children = res.list;
      });
    },
    changePeriods(data) {
      if (data.length > 1) {
        this.goods_id = data[0];
        let nowGoods = this.goodsList.find(i => {
          return i.id === data[0];
        });
        this.periods = nowGoods.children.find(i => {
          return i.id === data[1];
        });
        this.searchFrom.periods_id = this.periods.id;
        this.getChannelTransList();
      }
    },
    changeTeacher(value) {
      this.searchFrom.teacher_id = value;
      this.getChannelTransList();
    },
    selectChange(value) {
      this.searchFrom.watch_num = this.watchList[value].title;
      this.getChannelTransList();
    },
    formatTime(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}`;
    },
    onPageChange(val) {
      this.nowPage = val;
      this.getChannelTransList();
    },
    onSizeChange(val) {
      this.nowPage = 1;
      this.limit = val;
      this.getChannelTransList();
    },
    getTeacherList() {
      let json = {
        page: 1,
        limit: 200
      };
      getTeacherListApi(json).then(res => {
        this.teacherList = res.list;
      });
       getConfigListApi({page:1, limit: 100,key:'code_rule_type'}).then(res=>{
        this.typeList = res.list
      })
    },
    getGoodsList() {
      let json = {
        page: 1,
        limit: 100,
        goods_type: "1,2"
      };
      getGoodsListApi(json).then(res => {
        res.list.forEach(i => {
          i.name =
            "[" +
            i.id +
            "]" +
            "[" +
            GOODSTYPE[i.goods_type] +
            "]" +
            "[" +
            i.current_price / 100 +
            "元]" +
            i.name;
          i.children = [];
        });
        this.goodsList = res.list;
      });
    },
    getPeriodsOtherList() {
      let json = { limit: 1000,page:1,max_watch_num:20 };
      getPeriodsOtherListApi(json).then(res => {
        res.list.forEach(val=>{
          val.label = `【${val.goods_id}】${val.title}${val.watch_num}课时（${val.start_at.slice(5).replace('-', '')}）-d${val.has_watch_num}`
        })
        this.periodList = res.list;
      });
    },
    getChannelTransList() {
      let json = {
        limit: this.limit,
        page: this.nowPage
      };
      // 搜索筛选
      if (this.searchFrom.invite_type) {
        json.invite_type = this.searchFrom.invite_type;
      }
      if(this.searchFrom.sort_value){
        json.sort_value = this.searchFrom.sort_value;
        json.sort_key = this.searchFrom.sort_key;
      }
      if (this.searchFrom.squad) {
        json.squad = this.searchFrom.squad;
      }
      if (this.searchFrom.watch_num) {
        json.watch_num = this.searchFrom.watch_num;
      }
      if (this.periods_id) {
        json.periods_ids = this.periods_id;
      }
      if (this.searchFrom.type_id) {
        json.type_id = this.searchFrom.type_id;
      }
      if (this.searchFrom.teacher_id) {
        json.teacher_id = this.searchFrom.teacher_id;
      }
      if (this.searchFrom.payTime&&this.searchFrom.payTime.length > 0) {
        if (
          this.searchFrom.payTime[0] &&
          this.searchFrom.payTime[0].length > 0
        ) {
          this.searchFrom.start_at = this.searchFrom.payTime[0];
          json.start_at = this.searchFrom.start_at;
        }
        if (
          this.searchFrom.payTime[1] &&
          this.searchFrom.payTime[1].length > 0
        ) {
          this.searchFrom.end_at = this.searchFrom.payTime[1];
          json.end_at = this.searchFrom.end_at;
        }
      }
      if (this.searchFrom.classTime&&this.searchFrom.classTime.length > 0) {
        console.log(this.searchFrom.classTime)
        if (
          this.searchFrom.classTime[0] &&
          this.searchFrom.classTime[0].length > 0
        ) {
          this.searchFrom.class_start_at = this.searchFrom.classTime[0];
          json.class_start_at = this.searchFrom.class_start_at;
        }
        if (
          this.searchFrom.classTime[1] &&
          this.searchFrom.classTime[1].length > 0
        ) {
          this.searchFrom.class_end_at = this.searchFrom.classTime[1];
          json.class_end_at = this.searchFrom.class_end_at;
        }
      }
      getchannelTransListApi(json).then(res => {
        if (res) {
          if (res.list && res.list.length > 0) {
            this.total = res.total;
            this.list = res.list.map((item, index) => {
              item.index = index;
              if (index == 0) {
                this.spanArr.push(1);
                this.pos = 0;
              } else {
                if (item.cur_date == res.list[index - 1].cur_date) {
                  this.spanArr[this.pos] += 1;
                  this.spanArr.push(0);
                } else {
                  this.spanArr.push(1);
                  this.pos = index;
                }
              }
              item.squad = "T" + item.squad;
              let name =
                item.invite_name && item.invite_name.length > 0
                  ? `(${item.invite_name})`
                  : "";
              let goods_id =
                item.goods_id && item.goods_id > 0
                  ? `【${item.goods_id}】`
                  : "";
              let watch_num =
                item.watch_num && item.watch_num > 0
                  ? `【${item.watch_num}个课时】`
                  : "";
              item.invite_type = `${item.invite_type}${name}`;
              item.goods_name = `${goods_id}${item.goods_name}${watch_num}`;
              return item;
            });
            for (let key in this.list[0]) {
              this.propertyList.push(key);
            }
            this.width = document.documentElement.clientWidth - 200;
          }
          if (res.list && res.list.length === 0) {
            this.list = [];
          }
        } else {
          this.list = [];
        }
      });
    },
    getUpdateTime() {
      getUpdateTimeApi().then(res => {
        if (res.time) {
          this.updateTime = res.time
        }
      })
    }
  },
  mounted() {
    this.getChannelTransList();
    this.getTeacherList();
    // this.getPeriodsList();
    this.getGoodsList();
    this.getPeriodsOtherList();
    this.getUpdateTime();
  }
};
</script>
<style lang="less" scope>
.channel-trans-list {
  padding: 20px 0;
}

</style>

