<template>
  <div class="teacher">
    <div class="header">
      <el-card style="width: 450px;display: inline-block;margin-right: 10px">
        <div slot="header">
              <span>
                <label>{{detail.type | teacherType}}：</label> {{detail.name}}（T{{detail.squad}}）
              </span>
          <el-button style="float: right;" size="small" type="success" v-if="!$store.state.readonly" plain @click="onAddUser(true)">老师绑定用户</el-button>
        </div>
        <div class="card-content">
          <div class="text item">
            <a :href="detail.qr" target="_blank">
              <img :src="detail.qr"/>
            </a>
          </div>
          <div class="text item">
            <label>微信号：</label> {{detail.alias}}
            <br>
            <label>带班总人数：</label>{{detail.total_join_num}}
            <br>
            <label>老师状态：</label>{{detail.status === 0 ? '正常' : '禁用'}}
          </div>
        </div>
      </el-card>
      <el-card style="width: 450px;display: inline-block;margin-right: 10px" v-if="detail.user_info">
        <div slot="header">
          <span>绑定用户</span>
          <el-button @click="createInviteLink(detail.user_info)" style="float: right;" size="mini" plain type="primary">
            复制专属链接
          </el-button>
        </div>
        <div class="card-content">
          <div class="text item">
            <a :href="detail.user_info.avatar" target="_blank">
              <img class="avatar" :src="detail.user_info.avatar"/>
            </a>
          </div>
          <div class="text item">
            <label>微信号：</label> {{detail.user_info.nickname}}
          </div>
          <div class="text item">
            <label>用户ID：</label> {{detail.user_info.user_id}}
          </div>
        </div>
      </el-card>
      <el-card style="width: 320px;display: inline-block" v-if="task4Data">
        <div slot="header">
          <span>当月销售转化率【{{nowDate}}】</span>
        </div>
        <div class="text item">
          <el-progress type="circle" style="float: left;margin-right: 10px" :percentage="Number(task4Data.trans_rate.split('%')[0])"></el-progress>
        </div>
        <div class="card-content">
          <div class="text item">
            <label>当月带班人数：</label> {{task4Data.total_user_num}}
          </div>
          <div class="text item">
            <label>当月购课人数：</label> {{task4Data.total_sale_num}}
          </div>
          <div class="text item">
            <label>当月累计业绩：</label> {{task4Data.total_money}}
          </div>
        </div>
      </el-card>
    </div>
    <el-tabs type="border-card" v-model="tabs">
      <el-tab-pane label="今日任务" name="task">
        <task :parentDetail="parentDetail"></task>
      </el-tab-pane>
      <el-tab-pane label="期数列表" name="periods" >
        <el-table
          @expand-change="changeRow"
          :data="list"
          style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table
                :data="[scope.row]"
                style="width: 100%">
                <el-table-column
                  label="到课率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.arrive_course_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="看课率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.watch_course_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="完课率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.over_course_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="作业率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.work_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="全勤作业率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.over_work_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="打卡率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.clock_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="全勤打卡率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.over_clock_rate  | percent}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="转化率">
                  <template slot-scope="scope2">
                    <span>{{ scope2.row.transform_rate  | percent}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            prop="periods_title"
            label="期数名称">
          </el-table-column>
          <el-table-column
            prop="class_name"
            label="班级名称">
          </el-table-column>
          <el-table-column
            prop="join_num"
            label="已进班人数">
          </el-table-column>
          <el-table-column
            prop="need_add_teacher_num"
            label="需加好友数">
          </el-table-column>
          <el-table-column
            prop="max_join_num"
            label="最大班级人数">
          </el-table-column>
          <el-table-column
            prop="start_at"
            label="开课时间">
          </el-table-column>
          <el-table-column
            label="操作"  width="280">
            <template slot-scope="scope">
              <el-button @click="showUser(scope.row)" size="mini" plain type="primary">
                班级成员
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <page :total="total" :limit="limit" @pageChange="onPageChange" @sizeChange="onSizeChange"/>
      </el-tab-pane>
      <el-tab-pane label="订单列表" name="order" >
        <el-form ref="form" :model="form" label-width="100px" inline>

          <el-form-item label="用户ID">
            <el-input v-model="form.user_id"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="form.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户手机号">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
          <el-form-item label="收件人手机号">
            <el-input v-model="form.receive_mobile"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-select v-model="form.goods_id" placeholder="请选择" @change="getOrderList" 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 multiple v-model="form.status" placeholder="请选择" @change="getOrderList" clearable>
              <el-option
                v-for="item in orderStatusOption"
                :key="item.id"
                :label="item.value"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交易订单号">
            <el-input v-model="form.out_trade_no"></el-input>
          </el-form-item>
          <el-form-item >
            <el-button type="primary" plain @click="getOrderList">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData"
          style="width: 100%" class="order_list"  fixed>
          <el-table-column
            prop="out_trade_no"
            label="订单号"
          >
          </el-table-column>
          <el-table-column
            label="购买人"
            className="f-c"
            width="150">
            <template slot-scope="scope">
              <img class="avatar" :src="scope.row.user_avatar"/> {{scope.row.user_nickname}}<br>(ID:{{scope.row.user_id}})<br>手机：{{scope.row.user_mobile}}
            </template>
          </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
            width="250"
            prop="invite_id"
            className="f-c"
            label="推广人">
            <template slot-scope="scope">
              <div @click="showSource(scope.row)" v-if="scope.row.invite_earnings > 0 && scope.row.invite_id !== 0" style="width:100%;display: flex;color: #409eff;cursor: pointer">
                <img :src="scope.row.invite_avatar" class="avatar"/>
                类型：{{scope.row.invite_type}} ({{scope.row.invite_name}})
                <br>
                收益：{{scope.row.invite_earnings / 100}}
                <br>
                用户ID:{{scope.row.invite_id}}
                <br>
                昵称：{{scope.row.invite_nickname}}
                <br>
                手机：{{scope.row.invite_mobile}}
              </div>
              <div v-if="scope.row.invite_earnings === 0 && scope.row.invite_id !== 0" style="display: flex;">
                <img :src="scope.row.invite_avatar" class="avatar"/>
                类型：{{scope.row.invite_type}} ({{scope.row.invite_name}})
                <br>
                收益：{{scope.row.invite_earnings / 100}}
                <br>
                用户ID:{{scope.row.invite_id}}
                <br>
                昵称：{{scope.row.invite_nickname}}
                <br>
                手机：{{scope.row.invite_mobile}}
              </div>
              <div v-if="scope.row.invite_id === 0">
                无
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="优惠活动">
            <template slot-scope="scope">
          <span v-if="scope.row.order_coupon_id === 0">
            无
          </span>
              <el-button type="text" v-if="scope.row.order_coupon_id !== 0" @click="showCoupon(scope.row)">
                优惠券
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="付款状态"
            width="80">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.status === 5 || scope.row.status === 3" @click="showRef(scope.row)">{{scope.row.status|status}}</el-button>
              <div v-if="scope.row.status !== 5 && scope.row.status !== 3">{{scope.row.status|status}}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="实付金额"
            width="80">
            <template slot-scope="scope">
              {{scope.row.money | moneytFilter}}
            </template>
          </el-table-column>
          <el-table-column
            label="收货地址">
            <template slot-scope="scope">
              <div v-if="scope.row.user_address_id && scope.row.address_info">
                {{scope.row.address_info.receive_name}}<br>
                {{scope.row.address_info.receive_mobile}}<br>
                {{scope.row.address_info.province_name}}{{scope.row.address_info.city}}{{scope.row.address_info.area}}{{scope.row.address_info.address}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="pay_at"
            label="购买时间" sortable>
          </el-table-column>
          <el-table-column
            prop="created_at"
            label="下单时间" sortable>
          </el-table-column>
          <el-table-column
            prop="desc"
            label="备注">

          </el-table-column>
          <el-table-column
            width="50"
            label="操作"
            v-if="!$store.state.readonly"  fixed="right"
          >
            <template slot-scope="scope">
              <el-popover
                placement="top"
                width="200">
                <div style="text-align: center">
                  <el-button
                    @click="editComment(scope.row.id, scope.row.desc)"
                    type="info"
                    plain
                    size="mini">
                    编辑备注
                  </el-button>
                </div>
                <el-button slot="reference" size="mini" type="text" >操作</el-button>
              </el-popover>

            </template>
          </el-table-column>
        </el-table>
        <page :total="orderListObj.total" :limit="orderListObj.limit" @pageChange="onPageChange2" @sizeChange="onSizeChange2"/>
      </el-tab-pane>
    </el-tabs>
    <source-dialog :dialogObj="sourceDialog"/>
    <refund-detail :dialogObj="refundDetail"/>
    <coupon-dialog :dialogObj="couponDetail"/>

    <user-list :userObj="userObj" @reflash="getTeacherDetail"/>
    <choose-good-dialog :dialogObj="chooseGoodDialogObj" @changeShow="changeShow"/>

    <el-dialog append-to-body :visible.sync="addShow">
      <el-form label-width="90px">
        <!--<el-form-item label="用户id">-->
        <!--<el-input v-model="addId"></el-input>-->
        <!--</el-form-item>-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="ID">
              <el-input v-model="searchFrom.userId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="昵称">
              <el-input v-model="searchFrom.nickName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">
              <el-input v-model="searchFrom.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="16">
            <el-form-item>
              <el-button style="float: right" type="primary" plain @click="getUser">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="userList"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          className="f-c"
          label="用户">
          <template slot-scope="scope">
            <img style="margin-right:5px;width: 50px;height: 50px;border-radius: 50px" :src="scope.row.avatar">{{scope.row.nickname}}(ID:{{scope.row.user_id}})
          </template>
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号">
        </el-table-column>
      </el-table>
      <page :total="userObj.total" :limit="userObj.limit" @pageChange="onPageChange3" @sizeChange="onSizeChange3"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button type="primary" @click="onAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getTeacherDetailApi,getClassStatisticsApi,task4Api,getUserListApi,teacherBindUserApi,getOrderListApi,getGoodsListApi,editOrderDescApi,updateOrderTeacherApi } from "../../service/api";
  import {TEACHERTYPE,ORDERSTATUSOPTION,GOODSTYPE,ORDERSTATUS} from "../../util/wordbook";
  import AddressArray from '../framework/address-picker/addr'
  import task from './task'
  import page from '../framework/page'
  import sourceDialog from './sourceDialog'
  import couponDialog from './couponDialog'
  import refundDetail from './refundDetail'


  import UserList from '../class/userList'
  import chooseGoodDialog from './chooseGoodDialog'
  export default {
    name: "index",
    props:[
      'parentDetail'
    ],
    components:{
      page,
      task,
      UserList,
      chooseGoodDialog,
      couponDialog,
      refundDetail,
      sourceDialog
    },
    data(){
      let nowDate = new Date();
      let month = (nowDate.getMonth()+1);
      if(month < 10)month='0'+month.toString();
      nowDate = nowDate.getFullYear() + '-' + month;
      return {
        tabs:'task',
        nowDate:nowDate,
        searchFrom: {
          user_id:'',
          is_add_teacher: '',
          is_view_course: '',
          start_at:'',
          end_at:''
        },
        form: {
          nickname: '',
          user_id: '',
          status: [1,4,5],
          goods_id: '',
          out_trade_no: '',
          receive_mobile:"",
          mobile:"",
        },
        task4Data:null,
        goodList:[],
        orderStatusOption:ORDERSTATUSOPTION,
        tableData:[],
        userList:[],
        list:[],
        id: '',
        isBindUser:true,
        addShow:false,
        detail: {},
        total: 0,
        limit: 10,
        nowPage: 1,
        userObj:{
          classId:'',
          title:'',
          show:false,
          total: 0,
          limit: 10,
          nowPage: 1,
        },
        addId:'',
        multipleSelection:[],
        chooseGoodDialogObj: {
          show: false,
          code: ''
        },
        orderListObj:{
          total: 0,
          limit: 10,
          nowPage: 1,
        },

        sourceDialog:{
          show:false,
          out_trade_no:''
        },
        couponDetail:{
          show:false,
          order_coupon_id:''
        },
        refundDetail:{
          show:false,
          out_trade_no:''
        },
      }
    },
    methods:{
      getTask4(){
        task4Api(this.id).then(res=>{
          this.task4Data = res
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      onAdd(){
        let json = {
          is_buy: 0
        }
        if(this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择用户!'
          });
          return
        } else if (this.multipleSelection.length !== 1){
          this.$message({
            type: 'error',
            message: '只能选择一个用户!'
          });
          return
        }
        this.addId = this.multipleSelection[0].user_id;
        if (!this.addId) {
          return
        }
        if (!this.isBindUser) {

        } else {
          teacherBindUserApi(this.id, {user_id: this.addId}).then(res=>{
            this.$message({
              type: 'success',
              message: '绑定成功!'
            });
            this.id = this.parentDetail ? this.parentDetail.id : this.$route.params.id;
            this.getTeacherDetail();
            this.getGoodsOption();
            this.addShow = false;
          })
        }

      },
      onAddUser(flag){
        this.isBindUser = flag;
        this.addShow = true;
        this.getUser();
      },
      getUser(){
        let json = {
          page: this.userObj.nowPage,
          limit:  this.userObj.limit,
        };
        if (this.searchFrom.userId) {
          json.user_id = this.searchFrom.userId
        }
        if (this.searchFrom.nickName) {
          json.nickname = this.searchFrom.nickName
        }
        if (this.searchFrom.mobile) {
          json.mobile = this.searchFrom.mobile
        }
        getUserListApi(json).then(res=>{
          this.userList = res.list;
          this.userObj.total = res.total;
        })
      },
      changeRow(data,b){
        if(b.indexOf(data)>-1){
          getClassStatisticsApi(data.periods_id,data.id).then(res=>{
            data.arrive_course_rate = res.arrive_course_rate;
            data.watch_course_rate = res.watch_course_rate;
            data.over_course_rate = res.over_course_rate;
            data.work_rate = res.work_rate;
            data.over_work_rate = res.over_work_rate;
            data.clock_rate = res.clock_rate;
            data.over_clock_rate = res.over_clock_rate;
            data.transform_rate = res.transform_rate;
          })
        }
      },
      showUser(data){
        this.userObj={
          classId:data.id,
          show:true,
          title:`${this.detail.name}班级用户列表`,
          teacherId: data.teacher_id,
          periods_id: data.periods_id,
          goods_id:data.goods_id
        }
      },
      onPageChange3(val){
        this.userObj.nowPage = val;
        this.getUser()
      },
      onSizeChange3(val){
        this.userObj.limit = val;
        this.userObj.nowPage = 1;
        this.getUser();
      },
      onPageChange(val){
        this.nowPage = val;
        this.getTeacherDetail();

      },
      onSizeChange(val){
        this.limit = val;
        this.nowPage = 1;
        this.getTeacherDetail();
      },
      onPageChange2(val){
        this.orderListObj.nowPage = val;
        this.getOrderList()
      },
      onSizeChange2(val){
        this.orderListObj.limit = val;
        this.orderListObj.nowPage = 1;
        this.getOrderList()
      },
      getTeacherDetail(){
        this.searchFrom = {
          user_id:'',
          is_add_teacher: '',
          is_view_course: '',
          start_at:'',
          end_at:''
        };
        let id = this.id;
        let json = {
          limit: this.limit,
          page: this.nowPage
        }
        getTeacherDetailApi(id, json).then((res)=>{
          this.detail = res;
          if (this.detail.class_list) {
            this.detail.class_list.list.forEach(data=>{
              data.arrive_course_rate = 0;
              data.watch_course_rate = 0;
              data.over_course_rate = 0;
              data.work_rate = 0;
              data.over_work_rate = 0;
              data.clock_rate = 0;
              data.over_clock_rate = 0;
              data.transform_rate = 0;
            });
            this.list = this.detail.class_list.list || [];
            this.total = this.detail.class_list.total;
          }
          // this.getOrderList();
        })
      },
      createInviteLink(val){
        this.chooseGoodDialogObj.show = true;
        //类型选择项
        if(this.detail.type == 0 ){
          this.chooseGoodDialogObj.code = `CC-TEACHER-${val.user_id}`;

        }else if(this.detail.type == 1){
          this.chooseGoodDialogObj.code = `CC-XXMM-${val.user_id}`;
        }else{
          this.chooseGoodDialogObj.code = `CC-TEACHER-${val.user_id}`;
        }

      },
      changeShow(){
        this.chooseGoodDialogObj.show = false;
        this.chooseGoodDialogObj.code = '';
      },
      getOrderList(){
        let json = {
          limit: this.orderListObj.limit,
          page: this.orderListObj.nowPage
        };
        if (this.form.nickname) {
          json.nickname = this.form.nickname
        }
        if (this.form.user_id) {
          json.user_id = this.form.user_id
        }
        if (this.form.status) {
          json.status = this.form.status.toString()
        }
        if (this.form.goods_id) {
          json.goods_id = this.form.goods_id
        }
        if (this.form.receive_mobile) {
          json.receive_mobile = this.form.receive_mobile
        }
        if (this.form.out_trade_no) {
          json.out_trade_no = this.form.out_trade_no
        }
        if (this.form.mobile) {
          json.mobile = this.form.mobile
        }
        //  json.invite_id=this.id;
        if(this.detail.user_id !==0){
          json.invite_id=this.detail.user_id;
          getOrderListApi(json).then((res)=>{
            res.list.forEach(i=>{
              i.refundList=[]
            });
            this.tableData = res.list;
            this.orderListObj.total = res.total
          })
        }

      },
      getGoodsOption(){
        let json = {
          page: 1,
          limit: 100,
          course_type:0,
        };
        getGoodsListApi(json).then(res=>{
          this.goodList = res.list;
        })
      },
      editComment(id, desc) {
        this.$prompt('', '编辑备注', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:'textarea',
          inputValue: desc || ''
        }).then(({ value }) => {
          this.$confirm('确定保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            editOrderDescApi(id,'order',{desc: value}).then(res=>{
              this.$message({
                type: 'success',
                message: '编辑备注成功'
              });
              this.getOrderList();
            });
          });
        })
      },
      showRef(data){
        this.refundDetail.show = true;
        this.refundDetail.out_trade_no = data.out_trade_no;
      },
      showCoupon(data){
        this.couponDetail.show = true;
        this.couponDetail.order_coupon_id = data.order_coupon_id;
      },
      showSource(data){
        this.sourceDialog.show = true;
        this.sourceDialog.out_trade_no = data.out_trade_no;
      },
    },
    filters:{
      teacherType(value){
        return TEACHERTYPE[value]
      },
      percent(val){
        return (val * 100).toFixed(2)+'%'
      },
      status(value){
        return ORDERSTATUS[value]
      },
      moneytFilter(val){
        return val = val / 100 + '元'
      },
      filterGoods(val){
        return '[' + GOODSTYPE[val.goods_type] + ']' + '[' +val.current_price / 100 + '元]' + val.name
      }
    },

    mounted(){
      this.id =this.parentDetail ? this.parentDetail.id : this.$route.params.id;
      let data= localStorage.getItem("phoneNum");
      if(data){
        data=JSON.parse(data);
        this.id  = data.id
      }
      this.getTask4();
      this.getTeacherDetail();
      this.getGoodsOption();
    },
    watch:{
      'tabs'(value){
        if( value === 'order'){
          this.getOrderList();
        }
      }
    }
  }
</script>

<style scoped lang="less">
  .b-title {
    padding: 20px;
    color: #666;
  }
  .teacher {
    padding: 20px 0;
  }
  .header {
    padding: 0 20px;
    margin-bottom: 20px;
  }
  .el-row {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #666;
    font-size: 16px;
  }
  .text.item{
    line-height: 40px;
    label{
      width: 120px;
    }
  }
  .el-card{
    /*height: 50px;*/
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .avatar {
      width: 120px;
      margin-right: 10px;
      height: 120px;
      border-radius: 1000px;
    }
    img{
      width: 120px;
      float: left;
      margin-right: 10px;
    }
    label{
      color: #5982e6;
      width: 120px;
    }
  }
  .card-content:after{
    content: '';
    display: block;
    clear: both;
  }
  .order_list{
    .avatar{
      width: 50px;
      min-width: 50px;
      height: 50px;
      margin-right: 5px;
      border-radius: 50%;
    }
  }
</style>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .f-c > .cell {
    display: flex !important;
    flex-flow: row;
    justify-content: flex-start;
    align-items: center;
  }
</style>


