<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="渠道code">
        <el-input v-model="searchFrom.invite_type" style="width: 110px"></el-input>
      </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
          clearable
          placeholder="请选择"
          style="width: 150px"
          @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="期数名称" prop="periods_title">
        <el-select
          style="width: 480px"
          placeholder="请选择"
          v-model="searchFrom.periods_id"
          @change="onPeriodChange"
          multiple
          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>
        </div>
      </el-form-item>
    </el-form>

    <div class="update-time">最近更新时间：{{updateTime ? updateTime : '-'}}</div>
    <el-table
      border
      :span-method="objectSpanMethod"
      :data="list"
      @sort-change="sortMethod"
      :style="{width: width+'px'}"
      fixed>
      <!--<el-table-column prop="periods_title" label="期数名称"></el-table-column>-->
      <el-table-column label="期数名称" width="170px">
        <template slot-scope="scope">
          <div v-html="periodName(scope.row)"></div>
          <!--{{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="sum_class_num" label="到班数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="sum_friend_num" label="好友数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="friend_num_except_class_num" label="好友率" :render-header="rendertip" sortable='custom'>
        <template slot-scope="scope">
          {{scope.row.friend_num_except_class_num}}%
        </template>
      </el-table-column>
      <el-table-column prop="sum_come_num" label="到课数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="come_num_except_class_num" label="到课率" :render-header="rendertip" sortable='custom'>
        <template slot-scope="scope">
          {{scope.row.come_num_except_class_num}}%
        </template>
      </el-table-column>
      <el-table-column prop="sum_buy_num" label="转化人数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="sum_buy_num_except_class_num" label="转化率" :render-header="rendertip" sortable='custom'>
        <template slot-scope="scope">
          {{scope.row.sum_buy_num_except_class_num}}%
        </template>
      </el-table-column>
      <el-table-column prop="sum_one_buy_num" label="一年课购买人数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="sum_two_buy_num" label="两年课购买人数" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="sum_buy_money" width="120" label="转化总额" :render-header="rendertip" sortable="custom"></el-table-column>
      <el-table-column prop="sum_one_buy_money" label="一年课转化金额" :render-header="rendertip" sortable='custom'></el-table-column>
      <el-table-column prop="sum_two_buy_money" label="两年课转化金额" :render-header="rendertip" sortable='custom'></el-table-column>
    </el-table>
    <page
      :nowPage="nowPage"
      :total="total"
      :limit="limit"
      @pageChange="onPageChange"
      @sizeChange="onSizeChange"
    />
  </div>
</template>
<script>
  import {
    getPeriodsConversionListApi,
    getGoodsListApi,
    getPeriodsOtherListApi,
    getTeacherListApi,
    getUpdateTimeApi
  } from "../../service/api";
  import page from "../framework/page";
  import {GOODSTYPE, CLASSSOURCE} from "../../util/wordbook";
  import {tipArr3} from "../../util/tipArr";

  export default {
    name: "periodsConversionList",
    data() {
      return {
        updateTime: '',
        width: 0,
        nowPage: 1,
        total: 0,
        limit: 20,
        list: [],
        goods_id: null,
        teacherList: [],
        goodsList: [],
        periodList: [],
        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)
            );
          }
        },
        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(val) {
        let str = '';
        if (val.goods_id) {
          str += `【${val.goods_id}】`
        }
        if (val.periods_title) {
          str += `${val.periods_title}<br>`
        } else {
          str += `<br>`
        }
        if (val.watch_num) {
          str += `${val.watch_num}课时`
        }
        if (val.start_at) {
          str += `（${val.start_at.slice(5).replace('-', '')}）`
        }
        if (val.has_watch_num || val.has_watch_num == 0) {
          str += `-d${val.has_watch_num}`
        }
        return str
      },
      rendertip(h, {column}) {
        // console.log(h)
        return h("span", [
          h("span", column.label),
          h(
            "el-tooltip",
            {
              props: {
                effect: "dark",
                content: tipArr3[column.label],
                placement: "top"
              }
            },
            [
              h("i", {
                class: "el-icon-question",
                style: "color:#409eff;display:block;"
              })
            ]
          )
        ]);
      },
      sortMethod(data) {
        this.searchFrom.sort_key = data.prop
        if (data.order == 'ascending') {
          this.searchFrom.sort_value = 'asc'
        } else {
          this.searchFrom.sort_value = 'desc'
        }
        this.getChannelTransList()
      },
      getTeacherList() {
        let json = {
          page: 1,
          limit: 500
        };
        getTeacherListApi(json).then(res => {
          this.teacherList = res.list;
        });
      },
      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);
      },

      objectSpanMethod(data) {
        // if (this.propertyList.indexOf(data.column.property) > -1) {
        //   if (
        //     data.rowIndex === 0 ||
        //     data.row.cur_date !== this.list[data.rowIndex - 1].cur_date
        //   ) {
        //     let rowspan = 1;
        //     for (let i = data.rowIndex + 1; i < this.list.length; i++) {
        //       if (data.row.cur_date === this.list[i].cur_date) {
        //         rowspan++;
        //       } else {
        //         break;
        //       }
        //     }
        //     return {
        //       rowspan: rowspan,
        //       colspan: 1
        //     };
        //   } else {
        //     return {
        //       rowspan: 0,
        //       colspan: 0
        //     };
        //   }
        // } else {
        //   return {
        //     rowspan: 1,
        //     colspan: 1
        //   };
        // }
        // if (data.columnIndex === 0) {
        //   //用于设置要合并的列
        //   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();
      },
      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;
          console.log(320)
        });
      },
      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.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;
          }
        }
        getPeriodsConversionListApi(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;
                  }
                }

                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.getPeriodsList();
      this.getGoodsList();
      this.getPeriodsOtherList();
      this.getTeacherList();
      this.getUpdateTime()
    }
  };
</script>
<style lang="less" scope>
  .channel-trans-list {
    padding: 20px 0;
  }

</style>

