<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      乐团会员列表
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        :model="searchForm"
        ref="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="乐团/学员名称编号"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            @keyup.enter.native="search"
            placeholder="学员姓名/编号"
          ></el-input>
        </el-form-item> -->
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            filterable
            v-model.trim="searchForm.organId"
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="hasMember">
          <el-select
            class="multiple"
            v-model.trim="searchForm.hasMember"
            placeholder="会员状态"
          >
            <el-option label="已过期" value="0"></el-option>
            <el-option label="即将过期" value="1"></el-option>
            <el-option label="待生效" value="2"></el-option>
            <el-option label="生效中" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="visitTime">
          <el-date-picker
            v-model.trim="searchForm.visitTime"
            style="width: 410px"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="{
              firstDayOfWeek: 1,
            }"
            range-separator="至"
            start-placeholder="回访开始日期"
            end-placeholder="回访结束日期"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item prop="isActive">
          <el-select
            class="multiple"
            v-model.trim="searchForm.isActive"
            clearable
            placeholder="会员是否即将过期"
          >
            <el-option label="是" value="true"></el-option>
            <el-option label="否" value="false"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <el-button native-type="reset" type="danger">重置</el-button>
        </el-form-item>
      </save-form>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
        >
          <el-table-column
            align="center"
            prop="userId"
            label="学员编号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="username"
            label="学员姓名"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="phone"
            label="手机号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="organName"
            label="所属分部"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="musicGroupName"
            label="所属乐团"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="gotoMusic(scope.row.musicGroupName)"
              >
                {{ scope.row.musicGroupName }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="studentId" label="会员状态">
            <template slot-scope="scope">
              <div>
                {{ scope.row.hasMember | hasMemberFilter }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="memberDay"
            label="会员有效期剩余天数"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.memberDay >= 0 ? scope.row.memberDay : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="memberDay" label="回访日期">
            <template slot-scope="scope">
              <div>
                {{ scope.row.visitTime | dayjsFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="studentId" label="操作">
            <template slot-scope="scope">
              <div>
                <!-- addVisit -->
                <auth :auths="'visit/add/4465'">
                  <el-button type="text" @click="addVisit(scope.row)"
                    >新增回访</el-button
                  >
                </auth>
                <auth :auths="'visit/queryPage'" v-if="scope.row.visitTime">
                  <el-button type="text" @click="lookVisit(scope.row)"
                    >查看回访</el-button
                  >
                </auth>

                <auth :auths="'musicGroupQuit/directQuitMusicGroup4463'">
                  <el-button type="text" @click="quitTeam(scope.row)"
                    >退团退费</el-button
                  >
                </auth>
                <auth :auths="'musicGroupQuit/directQuitMusicGroup4462'">
                  <el-button type="text" @click="quieTeams(scope.row)"
                    >退团</el-button
                  >
                </auth>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 退团弹窗 -->
    <el-dialog title="退团信息确认" width="660px" :visible.sync="quitVisible">
      <quiteTeam :quitForm="quitForm" :activeRow="activeRow" ref="quitForm" />
       <p style="color:red;paddingLeft:150px">退费金额暂不进入账户余额</p>
      <span slot="footer" class="dialog-footer question">
        <div>
          <el-popover placement="right" width="500" trigger="click">
            <div class="popoverWrap">
              <p>乐团退团退费规则：</p>
              <p>退还云教练费用：报名缴费时缴费的云教练费用</p>
              <p>退还课程费用：缴费总额-已结束课时单价之和</p>
              <p>退还乐器费用：报名缴费时缴纳的乐器费用（团购、租金）</p>
              <p>退还教辅费用：报名缴费时缴费的教辅费用</p>
              <p v-if="tenantId == 1">退还乐保费用：报名缴费时缴费的乐保费用</p>

            </div>
            <el-button
              type="text"
              icon="el-icon-question"
              slot="reference"
              style="color: red"
              >退团退费说明</el-button
            >
          </el-popover>
        </div>
        <div>
          <el-button @click="quitVisible = false">取 消</el-button>
          <el-button type="primary" @click="chioseType">确 定</el-button>
        </div>
      </span>
    </el-dialog>
    <!-- 新增回访 -->
    <el-dialog
      title="新增回访"
      width="500px"
      :visible.sync="visitVisible"
      append-to-body
    >
      <visit
        v-if="visitVisible && activeRow"
        :detail="activeRow"
        :username="activeRow.username"
        @close="visitVisible = false"
        @submited="getList"
        :useVisitType="['其它', '会员续费']"
      />
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import quiteTeam from "@/views/teamDetail/components/modals/quite-team";
import { StudentQuit } from "@/api/buildTeam";
import load from "@/utils/loading";
import { getMusicMemberList } from "./api";
import visit from "@/views/withdrawal-application/modals/visit";
import { getTimes } from "@/utils";
export default {
  components: { pagination, quiteTeam, visit },
  data() {
    return {
      searchForm: {
        search: null,
        organId: null,
        hasMember: '0',
        visitTime: [],
      },

      tableList: [{}],
      organList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      quitForm: {
        // 退团信息确认
        studentName:null,
        musicGroupName:null,
        isRefundCourseFee: null,
        isRefundInstrumentFee: null,
        isRefundTeachingAssistantsFee: null,
        isMaintenanceFee: null,
        cloudTeacherAmount: null,
        isCloudTeacherAmount: null,
        isRefundMemberFee: null,
        maintenanceFee: 0,
        reason: "",
      },
      quitVisible: false,
      activeRow: null,
      visitVisible: false,
      tenantId:''
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部
    this.tenantId = this.$helpers.tenantId;
    this.$store.dispatch("setBranchs");
    this.init();
  },
  methods: {
    init() {
      if (this.$route.query.hasMember) {
        this.$set(this.searchForm, "hasMember", this.$route.query.hasMember);
      }
      this.getList();
    },
    async getList() {
      // 设置时间
      let { visitTime, ...rest } = this.searchForm;
      try {
        const res = await getMusicMemberList({
          ...rest,
          ...getTimes(visitTime, ["visitStartTime", "visitEndTime"]),
          page: this.rules.page,
          rows: this.rules.limit,
        });
        this.tableList = res.data.rows;
        this.rules.total = res.data.total;
      } catch (e) {
        console.log(e);
      }
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
       this.$refs["searchForm"].resetFields();
       this.search()
    },
    quitTeam(row) {
      this.activeRow = row;
      this.quitVisible = true;
      this.quitForm.cloudTeacherAmount = row.cloudTeacherAmount;
       this.quitForm.studentName = row.username
       this.quitForm.musicGroupName = row.musicGroupName
    },
    quieTeams(row) {
      this.$prompt("请输入退团原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入退团原因",
        type: "warning",
      })
        .then((val) => {
          // 发请求 退团
          StudentQuit({
            musicGroupId: row.musicGroupId,
            userId: row.userId,
            reason: val.value,
            isRefundCourseFee: false,
            isRefundInstrumentFee: false,
            isRefundTeachingAssistantsFee: false,
            isRefundMemberFee: false,
          }).then((res) => {
            this.quitForm = {
              // 退团信息确认
              isRefundCourseFee: null,
              isRefundInstrumentFee: null,
              isRefundTeachingAssistantsFee: null,
              isMaintenanceFee: null,
              cloudTeacherAmount: null,
              isCloudTeacherAmount: null,
              isRefundMemberFee: null,
              maintenanceFee: 0,
              reason: "",
            };
            if (res.code == 200) {
              this.$message.success("退团成功");
              this.getList();
              this.quitVisible = false;
            }
          });
        })
        .catch(() => {});
    },
    chioseType() {
      this.$refs["quitForm"].$refs["quitForm"].validate((res) => {
        if (res) {
          this.$confirm("确定退团?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let row = this.activeRow;
              let params = {
                musicGroupId: row.musicGroupId,
                userId: row.userId,
                reason: this.quitForm.reason,
                isRefundCourseFee: this.quitForm.isRefundCourseFee,
                isRefundInstrumentFee: this.quitForm.isRefundInstrumentFee,
                isRefundTeachingAssistantsFee:
                  this.quitForm.isRefundTeachingAssistantsFee,
                maintenanceFee: this.quitForm.maintenanceFee,
                isRefundMemberFee: this.quitForm.isRefundMemberFee,
              };
              // 退还云教练费用
              if (this.quitForm.isRefundMemberFee) {
                params.cloudTeacherAmount = this.quitForm.cloudTeacherAmount;
              } else {
                params.cloudTeacherAmount = 0;
              }
              // 发请求 退团
              StudentQuit(params).then((res) => {
                this.quitForm = {
                  // 退团信息确认
                  isRefundCourseFee: null,
                  isRefundInstrumentFee: null,
                  isRefundTeachingAssistantsFee: null,
                  isMaintenanceFee: null,
                  cloudTeacherAmount: null,
                  isCloudTeacherAmount: null,
                  isRefundMemberFee: null,
                  maintenanceFee: 0,
                  reason: "",
                };
                if (res.code == 200) {
                  this.$message.success("退团成功");
                  this.getList();
                  this.quitVisible = false;
                }
              });
            })
            .catch(() => {});
        } else {
        }
      });

      // row.typeVisible = false;
    },
    addVisit(row) {
      this.visitVisible = true;
      this.activeRow = row;
    },
    gotoMusic(str) {
      this.$router.push({ path: "/teamList", query: { search: str } });
    },
    lookVisit(row) {
      this.$router.push({
        path: "/studentManager/returnVisitList",
        query: { search: row.userId,typeList:['其它', '会员续费'] },
      });
    },
  },
  watch: {
    quitVisible(val) {
      if (!val) {
        this.quitForm = {
          // 退团信息确认
          isRefundCourseFee: null,
          isRefundInstrumentFee: null,
          isRefundTeachingAssistantsFee: null,
          isMaintenanceFee: null,
          cloudTeacherAmount: null,
          isCloudTeacherAmount: null,
          maintenanceFee: 0,
          reason: "",
        };
        this.$refs["quitForm"].$refs["quitForm"].resetFields();
      }
    },
  },
  filters:{
    hasMemberFilter(val){
    const arr =  ['已过期','即将过期','待生效','生效中']
    return arr[val]
    }
  }
};
</script>
<style lang='scss' scoped>
</style>
