<style lang="scss">
  .stuList .q-table__bottom {
    min-height: 0;
  }

  .stulistNum {
    display: inline-block;
    width: 25px;
    height: 25px;
    text-align: center;
    line-height: 23px;
    border: 1px solid #2961fe;
    border-radius: 50%;
    cursor: pointer;
    color: #2961fe;
  }

  .stuListTable {
    width: 200px;
    text-align: center;
  }

  .stuListTable tr td {
    height: 40px;
  }

  .stuListTable tr th {
    height: 40px;
    background-color: rgb(238, 238, 239);
  }

  .stulistNumber {
    display: inline-block;
    width: 25px;
    height: 25px;
    text-align: center;
    line-height: 22px;
    border: 1px solid #2961FE;
    border-radius: 50%;
    cursor: pointer;
    color: #2961FE;
  }

  .OCourseTable {
    width: 600px;
    text-align: center;
  }

  .OCourseTable tr td {
    height: 40px;
  }

  .OCourseTable tr th {
    height: 40px;
    background-color: rgb(238, 238, 239);
  }
</style>
<template>
  <div class="stuList">
    <q-table :pagination="pageMsg" :loading="loading" no-data-label="暂无相关数据" flat
      :selection="pushMode ? 'multiple' : 'single'" :selected.sync="selection"
      class="sticky-right-column-table sticky-tow-column-table" separator="none" :data="dataList" :columns="columns"
      row-key="StuId" hide-bottom>
      <template v-slot:top>
        <div class="col-2 q-table__title">学员信息</div>
        <q-space />
        <div class="page-option" v-if="!pushMode">
          <q-btn color="accent" v-if="IsTrasferAll()" outline class="q-mr-md" size="sm" icon="swap_horiz" label="批量转交"
            @click="pushMode = true" />
          <q-btn color="accent" outline class="q-mr-md" size="sm" icon="swap_horiz" label="推送课程顾问"
            v-if="userInfo.IsCourseConsultant == 0" @click="pushMode = true" />
          <q-btn color="accent" class="q-mr-md" size="sm" icon="swap_horiz" label="转订单"
            :disable="selection.length === 0" @click="transferOrder" />
          <q-btn color="accent" class="q-mr-md" size="sm" icon="swap_horiz" label="转留学"
            :disable="selection.length === 0" @click="transferAbroad" />
          <q-btn color="accent" class="q-mr-md" size="sm" icon="add" label="新增学员" @click="EditStudent(null)" />
          <q-btn v-if="authObj&&authObj.isShowDownload" color="accent" class="q-mr-md" size="sm" icon="download"
            label="下载" @click="downloadStudent" />
        </div>
        <div class="page-option" v-if="pushMode">
          <q-btn color="accent" unelevated class="q-mr-md" size="sm" icon="swap_horiz" label="转交"
            @click="isShowTrans = true">
            <q-popup-proxy :offset="[10, 10]">
              <q-banner v-if="isShowTrans">
                <q-select style="margin-top:20px;" filled v-model="transMsg.CreateBy" @filter="filterEmployee" use-input
                  :options="myEmployeeList" option-label="EmployeeName" option-value="Id" emit-value map-options />
                <q-btn label="保存" style="float:right;margin-top:15px" color="accent q-mb-lg" size="sm"
                  @click="saveTransForm" />
              </q-banner>
            </q-popup-proxy>
          </q-btn>
          <q-btn color="accent" unelevated class="q-mr-md" size="sm" icon="swap_horiz" label="立即推送" :loading="pushing"
            @click="assistBatchHandler" />
          <q-btn color="accent" outline size="sm" label="退出" :disable="pushing" @click="
              pushMode = false;
              selection = [];
            " />
        </div>
      </template>
      <template v-slot:body-cell-StuIcon="props">
        <q-td auto-width :props="props">
          <q-avatar size="md" v-if="props.value">
            <img :src="props.value" />
          </q-avatar>
          <q-avatar size="md" color="teal-10" text-color="white" v-if="!props.value">
            {{ props.row.StuName.substring(0, 1) }}</q-avatar>
        </q-td>
      </template>
      <template v-slot:body-cell-StuName="props">
        <q-td :props="props">
          <div class="text-blue cursor-pointer" @click="getStuRight(props.row,1)">
            {{ props.value }}
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-StuSex="props">
        <q-td :props="props">
          <q-badge :color="props.value == 1 ? 'negative' : 'primary'" :label="props.value == 1 ? '女' : '男'" />
        </q-td>
      </template>
      <template v-slot:body-cell-CreateTypeStr="props">
        <q-td :props="props">
          <div v-if="IsShowStuSourceIdName(props.row)">
            {{ props.row.CreateTypeStr }}
          </div>
          <div v-else>
            -
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-StuSourceIdName="props">
        <q-td :props="props">
          <div v-if="IsShowStuSourceIdName(props.row)">
            <span v-if="props.row.CreateType == 2 && props.row.EnterpriseName">{{props.row.EnterpriseName}}:</span>
            {{ props.row.StuSourceIdName }}
          </div>
          <div v-else>
            -
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-StuChannelName="props">
        <q-td :props="props">
          <div v-if="IsShowStuSourceIdName(props.row)">
            {{ props.row.StuChannelName }}
          </div>
          <div v-else>
            -
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-AdvisorWinRate="props">
        <q-td :props="props">{{props.row.AdvisorWinRate}}%</q-td>
      </template>
      <template v-slot:body-cell-AdvisorList="props">
        <q-td auto-width :props="props">
          <template v-if="props.row.AdvisorList">
            <template v-if="props.row.AdvisorList.length>0">
              {{props.row.AdvisorList[0].AdvisorStatusName}}
              <span class="stulistNumber">
                {{props.row.AdvisorList.length}}
                <q-popup-proxy>
                  <q-banner>
                    <table class="OCourseTable" style="border-collapse:collapse;">
                      <tr>
                        <th>跟进状态</th>
                        <th>跟进日期</th>
                        <th>跟进比例</th>
                        <th>跟进备注</th>
                      </tr>
                      <tr v-for="(sItem,sIndex) in props.row.AdvisorList" style="border-bottom:1px dashed #d1d1d1;"
                        :key="sIndex">
                        <td>{{sItem.AdvisorStatusName}}</td>
                        <td>{{sItem.AdvisorDate}}</td>
                        <td>{{sItem.AdvisorRate}}</td>
                        <td style="width:300px;text-align:left;">{{sItem.AdvisorRemark}}</td>
                      </tr>
                    </table>
                  </q-banner>
                </q-popup-proxy>
              </span>
            </template>
            <template v-if="props.row.AdvisorList.length==0">
              无
            </template>
          </template>
        </q-td>
      </template>
      <template v-slot:body-cell-CurseManager="props">
        <q-td :props="props" v-html="getCurseManager(props.row)"></q-td>
      </template>
      <template v-slot:body-cell-OrderCount="props">
        <q-td :props="props" v-if="props.row.OrderCount == 0" class="text-grey-4">未报名</q-td>
        <q-td :props="props" v-if="props.row.OrderCount > 0" class="bg-negative text-white"
          style="cursor:pointer;text-decoration:underline;" @click="getStuRight(props.row,3)">
          已报名{{ props.row.OrderCount }}单</q-td>
      </template>
      <template v-slot:body-cell-TeacherManager="props">
        <q-td :props="props" v-html="getTeacherManager(props.row)"></q-td>
      </template>
      <template v-slot:body-cell-AssistList="props">
        <q-td auto-width :props="props">
          <template v-if="props.row.AssistList">
            <template v-if="assistListFormat[props.pageIndex].length == 1">
              {{ assistListFormat[props.pageIndex][0].AssistName }}
            </template>
            <template v-if="assistListFormat[props.pageIndex].length > 1">
              {{ assistListFormat[props.pageIndex][0].AssistName }}：
              <span class="stulistNum">
                {{ assistListFormat[props.pageIndex].length }}
                <q-popup-proxy>
                  <q-banner>
                    <div style="max-height:600px;overflow-y:auto;">
                      <table class="stuListTable" style="border-collapse:collapse;">
                        <tr>
                          <th>角色</th>
                          <th>协同人</th>
                        </tr>
                        <tr v-for="(sItem, sIndex) in assistListFormat[
                            props.pageIndex
                          ]" style="border-bottom:1px dashed #d1d1d1;" :key="sIndex">
                          <td>{{ sItem.AssistTypeName }}</td>
                          <td>{{ sItem.AssistName }}</td>
                        </tr>
                      </table>
                    </div>
                  </q-banner>
                </q-popup-proxy>
              </span>
            </template>
            <template v-if="props.row.AssistList.length == 0">
              无
            </template>
          </template>
        </q-td>
      </template>
    </q-table>
    <student-form v-if="isShowStuForm" :save-obj="stuOption" @close="closeStuForm" @success="refreshStuList">
    </student-form>
    <studentRight-form v-if="isShowStuRight" :isJudgeTrans="isJudgeTrans" :BelongType="BelongType"
      :checkType="checkType" :save-obj="stuOption" @close="closeStuForm" @success="refreshStuList"
      @reload="referDataHandler">
    </studentRight-form>
    <studentAdd-form v-if="isShowAdd" :save-obj="stuOption" @close="closeStuForm" @success="refreshStuList">
    </studentAdd-form>
    <transfer-order v-if="isShowTransfer" :select="selection" @close="closeStuForm" @success="refreshStuList">
    </transfer-order>
    <abroad-form v-if="isShowAbroad" :select="selection" @close="closeStuForm" @success="refreshStuList"></abroad-form>
  </div>
</template>
<script>
  import studentForm from "./student-form";
  import studentRightForm from "./studentRight-form";
  import studentAddForm from "./studentAdd-form";
  import transferOrder from "./transfer-order";
  import abroadForm from "./abroad-form";
  import {
    mapGetters
  } from "vuex";
  import {
    SetStudentAssistBatch,
    BatchForwardStudent
  } from "../../../api/sale/sale";
  import {
    EduDownLoad
  } from "../../../api/common/common";
  import {
    queryEmployee
  } from "../../../api/users/user";

  export default {
    props: {
      //数据列表
      dataList: {
        type: Array,
        default: null
      },
      //是否显示转交按钮
      isJudgeTrans: {
        type: Number,
        default: null
      },
      loading: {
        type: Boolean,
        default: false,
      },
      //权限验证
      authObj: {
        type: Object,
        default: null,
      },
      //查询参数
      queryMsg: {
        type: Object,
        default: null,
      }
    },
    components: {
      studentForm,
      studentRightForm,
      studentAddForm,
      transferOrder,
      abroadForm
    },
    data() {
      return {
        columns: [{
            name: "StuIcon",
            label: "",
            field: "StuIcon",
            align: "left"
          },
          {
            name: "StuName",
            required: true,
            label: "昵称",
            align: "left",
            field: row => row.StuName
          },
          {
            name: "CurseManager",
            label: "课程顾问",
            align: "left"
          },
          {
            name: "TeacherManager",
            label: "协助老师",
            align: "left"
          },
          {
            name: "OrderCount",
            label: "是否报名",
            align: "left"
          },
          {
            name: "VisitCount",
            label: "到访次数",
            field: "VisitCount",
            align: "left"
          },
          {
            name: "TrialLessonCount",
            label: "试听次数",
            field: "TrialLessonCount",
            align: "left"
          },
          {
            name: "StuSex",
            label: "性别",
            field: "StuSex",
            align: "left"
          },
          {
            name: "StuTel",
            label: "电话",
            field: "StuTel",
            align: "left"
          },
          {
            name: "QQ",
            label: "QQ",
            field: "QQ",
            align: "left"
          },
          {
            name: "WeChatNo",
            label: "微信",
            field: "WeChatNo",
            align: "left"
          },
          {
            name: "StuTypeName",
            label: "客户类型",
            field: "StuTypeName",
            align: "left"
          },
          {
            name: "StuStageName",
            label: "客户阶段",
            field: "StuStageName",
            align: "left"
          },
          {
            name: "StuNeedsName",
            label: "客户需求",
            field: "StuNeedsName",
            align: "left"
          },
          {
            name: "AdvisorExpectDate",
            label: "期望达成协议日期",
            field: "AdvisorExpectDate",
            align: "left"
          },
          {
            name: "AdvisorStatusName",
            label: "目前状态",
            field: "AdvisorStatusName",
            align: "left"
          },
          {
            name: "AdvisorWinRate",
            label: "胜率",
            field: "AdvisorWinRate",
            align: "left"
          },
          {
            name: "AdvisorList",
            label: "跟踪记录",
            field: "AdvisorList",
            align: "left"
          },
          {
            name: "StuProfession",
            label: "职业",
            field: "StuProfession",
            align: "left"
          },
          {
            name: "StuEducationName",
            label: "学历",
            field: "StuEducationName",
            align: "left"
          },
          {
            name: "StuPurposeName",
            label: "目的",
            field: "StuPurposeName",
            align: "left"
          },
          {
            name: "AssistList",
            label: "其他服务人员",
            align: "left",
            field: "AssistList"
          },
          {
            name: "CreateTypeStr",
            label: "客户来源",
            field: "CreateTypeStr",
            align: "left"
          },
          {
            name: "StuSourceIdName",
            label: "来源关联人",
            field: "StuSourceIdName",
            align: "left"
          },
          {
            name: "StuChannelName",
            label: "收客渠道",
            field: "StuChannelName",
            align: "left"
          },
          {
            name: "CreateTimeStr",
            label: "创建时间",
            field: "CreateTimeStr",
            align: "left"
          },
          {
            name: "CreateByName",
            label: "负责人",
            align: "left",
            field: "CreateByName"
          }
        ],
        pageMsg: {
          rowsPerPage: 12
        },
        isShowStuForm: false,
        resetLoading: false,
        isShowStuRight: false,
        stuOption: null,
        isShowAdd: false,
        selection: [],
        isShowTransfer: false, //是否显示转订单弹窗
        BelongType: 1,
        pushMode: false, //是否显示推送按钮
        pushing: false,
        assistListFormat: [],
        checkType: 1, //打开右侧弹窗类型
        isShowAbroad: false, //是否显示转留学就业订单弹窗
        userInfo: {}, //当前登录人员
        isShowTrans: false,
        transMsg: {
          StuIds: '',
          CreateBy: ''
        },
        //员工列表
        employeeList: [],
        myEmployeeList: [],
      };
    },
    watch: {
      dataList: {
        handler(val) {
          this.selection = [];
          this.formatAssistList();
        },
        deep: true
      }
    },
    created() {
      this.userInfo = this.getLocalStorage();
      this.formatAssistList();
    },
    mounted() {
      this.getEmployeeList();
    },
    computed: {
      ...mapGetters(["logo", "name"])
    },
    methods: {
      //是否有查看客户来源和来源关联人权限
      IsShowStuSourceIdName(item) {
        var isHaveAuth = false;
        if (this.userInfo && this.userInfo.ActionMenuList && this.userInfo.ActionMenuList.length >
          0) {
          this.userInfo.ActionMenuList.forEach((x) => {
            if (x.FunctionCode == "Look_StuSourceId") {
              isHaveAuth = true;
            }
          });
        }
        if (item.CreateBy == this.userInfo.Id || isHaveAuth) {
          return true;
        } else {
          return false;
        }
      },
      //是否有批量转移权限
      IsTrasferAll(){
        var isHaveAuth = false;
        if (this.userInfo && this.userInfo.ActionMenuList && this.userInfo.ActionMenuList.length >
          0) {
          this.userInfo.ActionMenuList.forEach((x) => {
            if (x.FunctionCode == "IsTranserAll") {
              isHaveAuth = true;
            }
          });
        }
        return isHaveAuth
      },
      //下载文件
      downloadStudent() {
        var msg = JSON.parse(JSON.stringify(this.queryMsg));
        EduDownLoad(
          "/User/DownLoadStudent",
          msg,
          "客户资料.xls"
        );
      },
      //服务人员转化
      formatAssistList() {
        this.assistListFormat = [];
        this.dataList.forEach(x => {
          let tempArr = [];
          if (x.AssistList && x.AssistList.length > 0) {
            x.AssistList.forEach(y => {
              if (y.AssistType != 2 && y.AssistType != 4) {
                tempArr.push(y);
              }
            });
          }
          this.assistListFormat.push(tempArr);
        });
      },
      //创建账号
      createAccount(id) {
        let that = this;
        createStudentAccount({
          StuId: id
        }).then(res => {
          that.$q
            .dialog({
              title: "创建账号",
              message: res.Message,
              persistent: true,
              ok: {
                label: "确认",
                flat: true,
                focus: true
              }
            })
            .onOk(() => {
              that.getStudent();
            })
            .onCancel(() => {
              that.getStudent();
            });
        });
      },
      resetPw(id) {
        let that = this;
        this.$q
          .dialog({
            title: "重置密码",
            message: "你正在进行重置密码行为，是否确认执行",
            persistent: true,
            cancel: {
              label: "取消",
              flat: true
            },
            ok: {
              label: "确认重置",
              flat: true,
              focus: true
            }
          })
          .onOk(() => {
            that.resetLoading = true;
            resetPassword({
                AccountType: 4,
                AccountId: id
              })
              .then(res => {
                that.resetLoading = false;
                that.$q.dialog({
                  title: "密码重置成功",
                  message: res.Message,
                  persistent: true,
                  ok: {
                    label: "确认",
                    flat: true,
                    focus: true
                  }
                });
              })
              .catch(() => {
                that.resetLoading = false;
              });
          });
      },
      //删除客户资料
      deleteStudentInfo(obj) {
        let that = this;
        var str = obj.Status == 1 ? "【禁用】" : "【启用】";
        this.$q
          .dialog({
            title: str + "学员",
            message: "你正在进行" + str + "学员行为，一旦执行无法找回，是否确认执行？",
            persistent: true,
            cancel: {
              label: "取消",
              flat: true
            },
            ok: {
              label: "确认",
              flat: true,
              focus: true
            }
          })
          .onOk(() => {
            that.resetLoading = true;
            deleteStudent({
              StuId: obj.StuId,
              Status: obj.Status
            }).then(res => {
              this.$q.notify({
                icon: "iconfont icon-chenggong",
                color: "accent",
                timeout: 2000,
                message: "数据操作成功！",
                position: "top"
              });
              this.getStudent();
            });
          })
          .onCancel(() => {
            obj.Status = obj.Status == 1 ? 0 : 1;
          });
      },
      //刷新列表
      refreshStuList() {
        this.$emit("success");
        this.selection = [];
      },
      EditStudent(obj) {
        if (obj) {
          this.stuOption = obj;
        } else {
          this.stuOption = null;
        }
        this.isShowAdd = true;
      },
      closeStuForm() {
        this.isShowStuForm = false;
        this.isShowStuRight = false;
        this.isShowAdd = false;
        this.isShowTransfer = false;
        this.isShowAbroad = false;
      },
      //点击学生姓名弹出
      getStuRight(obj, type) {
        if (obj) {
          this.stuOption = obj;
          this.BelongType = obj.BelongType;
          this.checkType = type;
        } else {
          this.stuOption = null;
        }
        this.isShowStuRight = true;
      },
      //转订单
      transferOrder() {
        const firstId = this.selection[0].CustomerId;
        const flag = this.selection.every(e => {
          return e.CustomerId == firstId;
        });
        if (!flag) {
          this.$q.notify({
            type: "negative",
            position: "top",
            message: `所属同行不一致，请重新选择`
          });
          return;
        }
        this.isShowTransfer = true;
      },
      //转留学
      transferAbroad() {
        this.isShowAbroad = true;
      },
      getCurseManager(row) {
        let managerName = "<span class='text-grey-4'>暂未推送</span>";
        if (row.AssistList && row.AssistList.length > 0) {
          row.AssistList.forEach(y => {
            if (y.AssistType == 2) {
              managerName = `<span class='text-dark'>${y.AssistName}</span>`;
            }
          });
        }
        return managerName;
      },
      getTeacherManager(row) {
        let managerName = "<span class='text-grey-4'>暂无</span>";
        if (row.AssistList && row.AssistList.length > 0) {
          row.AssistList.forEach(y => {
            if (y.AssistType == 4) {
              managerName = `<span class='text-dark'>${y.AssistName}</span>`;
            }
          });
        }
        return managerName;
      },
      assistBatchHandler() {
        if (this.pushing) return;
        this.pushing = true;
        if (this.selection.length > 0) {
          let msg = "";
          let parameter = {
            stuIds: ""
          };
          this.selection.forEach(x => {
            parameter.stuIds += "," + x.StuId;
            if (x.AssistList && x.AssistList.length > 0) {
              x.AssistList.forEach(y => {
                if (y.AssistType == 2) {
                  msg = `客户${x.StuName}：已存在课程顾问：${y.AssistName}，无法再次推送。`;
                }
              });
            }
          });
          if (msg == "") {
            SetStudentAssistBatch(parameter).then(r => {
              this.refreshStuList();
              this.selection = [];
              this.pushMode = false;
            });
          } else {
            this.pushing = false;
            this.errorMsg(msg);
          }
        } else {
          this.pushing = false;
          this.errorMsg("请选择要推送的学员");
        }
      },
      referDataHandler() {
        this.$emit("reload");
      },
      errorMsg(msg) {
        this.$q.notify({
          type: "negative",
          position: "top",
          message: msg
        });
      },
      //获取员工列表
      getEmployeeList() {
        queryEmployee({
          IsLeave: 1
        }).then(res => {
          this.employeeList = res.Data;
          this.myEmployeeList = res.Data;
        });
      },
      //筛选员工
      filterEmployee(val, update, abort) {
        update(() => {
          this.myEmployeeList = this.employeeList.filter(
            v => v.EmployeeName.indexOf(val) > -1
          );
        });
      },
      //保存批量转交
      saveTransForm() {
        if (this.selection.length == 0) {
          this.$q.notify({
            type: "negative",
            position: "top",
            message: '请选择推送学员'
          });
          return;
        }
        if (this.transMsg.CreateBy == "") {
          this.$q.notify({
            type: "negative",
            position: "top",
            message: '请选择接收人员!'
          });
          return;
        }
        let newArr = []
        this.selection.forEach(x => {
          newArr.push(x.StuId);
        })
        this.transMsg.StuIds = newArr.toString();
        BatchForwardStudent(this.transMsg).then(res => {
          if (res.Code == 1) {
            this.refreshStuList();
            this.selection = [];
            this.transMsg.StuIds = "";
            this.transMsg.CreateBy = "";
            this.pushMode = false;
            this.$q.notify({
              type: "iconfont icon-chenggong",
              position: "top",
              message: r.Message
            });
          }
        });

      }
    }
  };
</script>