<template >
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      活动管理
    </h2>

    <div class="m-core">
      <el-button
        type="primary"
        style="margin-bottom: 20px"
        v-permission="'/vipNewActive'"
        @click="gotoNewActive"
        >新建</el-button
      >
      <!-- <el-button
        type="primary"
        style="margin-bottom: 20px"
        v-permission="'export/vipGroupActivity'"
        @click="onExport"
        >活动导出</el-button
      > -->
      <save-form
        :inline="true"
        class="searchForm"
        ref="searchForm"
        @submit="search"
        @reset="onReset"
        :model="searchForm"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            placeholder="活动编号、名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            filterable
            style="width: 180px !important"
            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="status">
          <el-select
            filterable
            style="width: 180px !important"
            v-model="searchForm.status"
            clearable
            placeholder="活动状态"
          >
            <el-option label="草稿" :value="'DRAFT'"></el-option>
            <el-option label="正式" :value="'PROGRESS'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="enable">
          <el-select
            filterable
            style="width: 180px !important"
            v-model="searchForm.enable"
            clearable
            @clear="resetEnable"
            placeholder="是否启用"
          >
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="allowOnlineToOffline">
          <el-select
            v-model.trim="searchForm.allowOnlineToOffline"
            placeholder="请选择课程调整方式"
            clearable
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in vipResetTypeList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="applyToStudentType">
          <el-select
            filterable
            style="width: 180px !important"
            v-model="searchForm.applyToStudentType"
            clearable
            placeholder="适用学员"
          >
            <el-option label="新学员" :value="1"></el-option>
            <el-option label="老学员" :value="0"></el-option>
            <el-option label="所有学员" :value="-1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="reset">重置</el-button>
        </el-form-item>
      </save-form>
      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column align="center" prop="id" label="活动编号">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.id }}</copy-text>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="活动名称">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.name }}</copy-text>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="activityType" label="活动类型">
            <template slot-scope="scope">
              <div>
                {{ scope.row.activityType ? "会员活动" : "课程活动" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="type" label="活动购买">
            <template slot-scope="scope">
              <div>
                <p v-if="scope.row.activityType">会员</p>
                <p v-else>{{ scope.row.courseType | courseTypeFormat }}</p>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="type"
            :formatter="fommatterType"
            label="是否赠送"
          ></el-table-column> -->
          <el-table-column align="center" prop="type" label="赠送类型">
            <template slot-scope="scope">
              <div>
                {{ scope.row.giveCourseType | courseTypeFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150px" label="活动持续时间">
            <template slot-scope="scope">
              <div>
                <p>{{ scope.row.startTime }}</p>
                <p>{{ scope.row.endTime }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="活动状态"
            prop="status"
            :formatter="fommatterStatus"
          ></el-table-column>
          <!-- <el-table-column
            align="center"
            prop="vipGroupCategoryNames"
            label="适用课程形式"
          ></el-table-column> -->

          <!-- <el-table-column
            align="center"
            label="适用课时类型"
            :formatter="fommatterCourseType"
          ></el-table-column>
          <el-table-column
            width="135"
            align="center"
            label="课程调整方式"
            :formatter="fommatterResetType"
          ></el-table-column>
          <el-table-column
            align="center"
            label="使用学员"
            :formatter="formatStudentType"
          ></el-table-column> -->

          <!-- <el-table-column label="结算标准">
            <template slot-scope="scope">
              <div>
                <p>{{ scope.row.salarySettlementJson | onlineDesc }}</p>
                <p>{{ scope.row.salarySettlementJson | unonlineDesc }}</p>
              </div>
            </template>
          </el-table-column> -->
          <!-- <el-table-column align="center" label="结算说明">
            <template slot-scope="scope">
              <div>
                <p>{{ scope.row.salarySettlementJson | onlineDesc }}</p>
                <p>{{ scope.row.salarySettlementJson | unonlineDesc }}</p>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            label="是否启用"
            prop="enable"
            :formatter="fommatterEnable"
          ></el-table-column>

          <!-- <el-table-column align="center" width="150px" label="课程安排时间">
            <template slot-scope="scope">
              <div>
                <p>{{ scope.row.coursesStartTime }}</p>
                <p>{{ scope.row.coursesEndTime }}</p>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <div>
                <!--   v-if="scope.row.enable > 0" -->
                <el-button
                  type="text"
                  v-permission="'vipGroupActivity/update'"
                  @click="look(scope.row)"
                  >查看</el-button
                >
                <el-button
                  style="margin-left: 0px"
                  type="text"
                  v-permission="'vipGroupActivity/update'"
                  v-if="!scope.row.enable || scope.row.status == 'DRAFT'"
                  @click="reset(scope.row)"
                  >修改</el-button
                >
                <el-button
                  style="margin-left: 0px"
                  v-if="!scope.row.enable && scope.row.status == 'PROGRESS'"
                  type="text"
                  v-permission="'vipGroupActivity/enable'"
                  @click="resetStatus(scope.row)"
                  >启用</el-button
                >
                <el-button
                  v-if="scope.row.enable && scope.row.status == 'PROGRESS'"
                  style="margin-left: 0px"
                  type="text"
                  v-permission="'vipGroupActivity/enable'"
                  @click="resetStatus(scope.row)"
                  >停用</el-button
                >
                <!-- <el-button type='text'
                @click="remove(scope.row)">删除</el-button>-->
                <el-popover
                  placement="top"
                  width="160"
                  v-permission="'vipGroupActivity/delete'"
                  :ref="scope.$index"
                  v-if="scope.row.status != 'PROGRESS' && !scope.row.enable"
                >
                  <p>确定删除?</p>
                  <div style="text-align: right; margin: 0">
                    <el-button
                      size="mini"
                      type="text"
                      @click="scope._self.$refs[scope.$index].doClose()"
                      >取消</el-button
                    >
                    <el-button type="primary" size="mini" @click="remove(scope)"
                      >确定</el-button
                    >
                  </div>
                  <el-button type="text" slot="reference">删除</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <pagination
          :total.sync="rules.total"
          sync
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>
<script>
const MIN_NUMBER = 1;
const MAX_NUMBER = 999;
import pagination from "@/components/Pagination/index";
import {
  vipGroupActivity,
  removeVipActive,
  enableVipGroupActivity,
} from "@/api/vipSeting";
import qs from "qs";
import { Export } from "@/utils/downLoadFile";
import cleanDeep from "clean-deep";
import { vipResetTypeList } from "@/utils/searchArray";
export default {
  name: "vipActiveList",
  components: { pagination },
  data() {
    return {
      vipResetTypeList,
      labelPosition: "right",
      tableList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      searchForm: {
        organId: null,
        enable: null,
        search: "",
        applyToStudentType: null,
        allowOnlineToOffline: null,
        status: null,
      },
      dialogVisible: false,
    };
  },
  // created() {
  //   this.init();
  // },
  // activated() {
  //   this.init();
  // },
  mounted() {
    this.init();
  },
  filters: {
    onlinePip(val) {
      let obj = JSON.parse(val);
      // debugger;
      if (
        obj &&
        obj.onlineSalarySettlement &&
        obj.onlineSalarySettlement.salarySettlementType
      ) {
        switch (obj.onlineSalarySettlement.salarySettlementType) {
          case "RATIO_DISCOUNT": {
            return "线上:比例结算";
            break;
          }
          case "TEACHER_DEFAULT": {
            return "线上:老师默认";
            break;
          }
          case "FIXED_SALARY": {
            return "线上:固定课酬";
            break;
          }
        }
      }
    },
    unonlinePip(val) {
      let obj = JSON.parse(val);
      if (
        obj &&
        obj.offlineSalarySettlement &&
        obj.offlineSalarySettlement.salarySettlementType
      ) {
        switch (obj.offlineSalarySettlement.salarySettlementType) {
          case "RATIO_DISCOUNT": {
            return "线下:比例结算";
            break;
          }
          case "TEACHER_DEFAULT": {
            return "线下:老师默认";
            break;
          }
          case "FIXED_SALARY": {
            return "线下:固定课酬";
            break;
          }
        }
      }
    },
    onlineDesc(val) {
      let obj = JSON.parse(val);
      // debugger;
      if (
        obj &&
        obj.onlineSalarySettlement &&
        obj.onlineSalarySettlement.salarySettlementType
      ) {
        switch (obj.onlineSalarySettlement.salarySettlementType) {
          case "RATIO_DISCOUNT": {
            if (obj.onlineSalarySettlement.settlementValue) {
              return `线上:比例结算${obj.onlineSalarySettlement.settlementValue}%`;
            } else {
              return "线上:比例结算";
            }
            break;
          }
          case "TEACHER_DEFAULT": {
            return "线上:默认课酬";
            break;
          }
          case "FIXED_SALARY": {
            if (obj.onlineSalarySettlement.settlementValue) {
              return `线上:固定课酬${obj.onlineSalarySettlement.settlementValue}/次`;
            } else {
              return "线上:固定课酬";
            }

            break;
          }
        }
      }
    },
    unonlineDesc(val) {
      let obj = JSON.parse(val);
      if (
        obj &&
        obj.offlineSalarySettlement &&
        obj.offlineSalarySettlement.salarySettlementType
      ) {
        switch (obj.offlineSalarySettlement.salarySettlementType) {
          case "RATIO_DISCOUNT": {
            if (obj.offlineSalarySettlement.settlementValue) {
              return `线下:比例结算${obj.offlineSalarySettlement.settlementValue}%`;
            } else {
              return "线下:比例结算";
            }
            break;
          }
          case "TEACHER_DEFAULT": {
            return "线下:默认课酬";
            break;
          }
          case "FIXED_SALARY": {
            if (obj.offlineSalarySettlement.settlementValue) {
              return `线下:固定课酬${obj.offlineSalarySettlement.settlementValue}/次`;
            } else {
              return "线下:固定课酬";
            }
            break;
          }
        }
      }
    },
  },
  methods: {
    async init() {
      // 获取类型
      await this.$store.dispatch("setVipGroupCategory");
      // 获取分部
      await this.$store.dispatch("setBranchs");

      this.getList();
    },
    // 导出
    async onExport() {
      const { ...rest } = this.searchForm;
      let obj = {
        ...rest,
        page: this.rules.page,
        rows: this.rules.limit,
      };
      await Export(
        this,
        {
          url: "/api-web/export/vipGroupActivity",
          fileName: "活动列表.xls",
          method: "post",
          params: qs.stringify(cleanDeep(obj)),
        },
        "您确定活动列表?"
      );
    },
    loadNumber(event) {
      var el = event.currentTarget;
      var elValue = el.value;
      var reg = /^((?!0)\d{1,2}|100)$/;
      if (!elValue.match(reg)) {
        elValue = "";
        return false;
      } else {
        return true;
      }
    },

    onCheckAllBranch() {
      // 适用所有分部
      this.resetForm.organ = [];
      this.organList.forEach((item) => {
        this.resetForm.organ.push(item.id);
      });
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReset() {
      // this.searchForm = {
      //   enable: null,
      //   search: null,
      //   organId: null,
      // }
      this.$refs["searchForm"].resetFields();
      this.search();
    },
    getList() {
      let enable = this.searchForm.enable;
      let search = this.searchForm.search;
      vipGroupActivity({
        organId: this.searchForm.organId,
        applyToStudentType: this.searchForm.applyToStudentType,
        allowOnlineToOffline: this.searchForm.allowOnlineToOffline,
        rows: this.rules.limit,
        page: this.rules.page,
        status: this.searchForm.status,
        enable,
        search,
      }).then((res) => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.rules.total = res.data.total;
        }
      });
    },
    resetEnable(val) {
      val = null;
    },
    // 格式化活动类型
    fommatterType(row, column) {
      switch (row.type) {
        case "BASE_ACTIVITY": {
          return "基础";
          break;
        }
        case "DISCOUNT": {
          return "折扣";
          break;
        }
        case "GIVE_CLASS": {
          if (row.giveClassPaySalaryFlag) {
            return "买赠(赠课结算)";
          } else {
            return "买赠(不结算)";
          }

          break;
        }
      }
    },
    // 格式化课时类型
    fommatterCourseType(row) {
      let date = JSON.parse(row.salarySettlementJson);
      let str = "";
      if (date && date.onlineSalarySettlement) {
        str += "线上 ";
      }
      if (date && date.offlineSalarySettlement) {
        str += "线下";
      }
      return str;
    },
    fommatterResetType(row) {
      let str = null;
      if (row.allowOnlineToOffline == 1) {
        str = "无限制";
      }
      if (row.allowOnlineToOffline == 0) {
        str = "线上不可转线下";
      }
      if (row.allowOnlineToOffline == 2) {
        str = "线下不可调为线上";
      }
      if (row.allowOnlineToOffline == 3) {
        str = "线上线下不可互调";
      }
      return str;
    },
    formatStudentType(row) {
      let str = null;
      if (row.applyToStudentType == -1) {
        str = "所有学员";
      }
      if (row.applyToStudentType == 0) {
        str = "老学员";
      }
      if (row.applyToStudentType == 1) {
        str = "新学员";
      }
      return str;
    },
    // 格式化启用状态
    fommatterEnable(row) {
      switch (row.enable) {
        case false: {
          return "否";
          break;
        }
        case true: {
          return "是";
          break;
        }
      }
    },
    // 格式化Status
    fommatterStatus(row) {
      switch (row.status) {
        case "PROGRESS": {
          return "正式";
          break;
        }
        case "DRAFT": {
          return "草稿";
          break;
        }
      }
    },
    // 点击列表修改同步状态
    reset(row) {
      this.$router.push({
        path: "/operateManager/vipNewActive?type=reset",
        query: { id: row.id },
      });
    },
    look(row) {
      this.$router.push({
        path: "/operateManager/vipNewActive?type=look",
        query: { id: row.id },
      });
    },
    // 点击确认按钮发送修改请求
    remove(scope) {
      let id = scope.row.id;
      removeVipActive({ id }).then((res) => {
        if (res.code == 200) {
          this.$message.success("恭喜您删除成功");
          this.getList();
        }
        scope._self.$refs[scope.$index].doClose();
      });
    },
    gotoNewActive() {
      // 带参数 searchForm: { organId: null } 搜索条件
      // let rules = JSON.stringify(this.rules);
      // let searchForm = JSON.stringify(this.searchForm);
      this.$router.push({
        path: "/operateManager/vipNewActive?type=create",
        // query: { rules, searchForm },
      });
    },
    closeVipform() {
      this.$refs["vipform"].resetFields();
      this.dialogVisible = false;
    },
    resetForms() {
      this.$refs.form.resetFields();
    },
    handleMinChange() {
      this.$refs.form.validateField("maxCourseNum");
    },
    handleMaxChange() {
      this.$refs.form.validateField("minCourseNum");
    },
    validateCom(rule, value, callback) {
      const one = Number(value);
      if (Number.isInteger(one)) {
        if (one < MIN_NUMBER) {
          return callback(new Error("输入值必须大于0"));
        } else if (one > MAX_NUMBER) {
          return callback(new Error("输入值必须小于999"));
        }
        return callback();
      }
      return callback(new Error("输入值必须为正整数"));
    },
    validateMin(rule, value, callback) {
      const one = Number(value);
      const max = Number(this.courseNumForm.maxCourseNum);
      if (!max || one <= max) {
        return callback();
      }
      return callback(new Error("输入值不得大于最大课时数"));
    },
    validateMax(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.courseNumForm.minCourseNum);
      if (!min || one >= min) {
        return callback();
      }
      return callback(new Error("输入值不得小于最小课时数"));
    },
    resetStatus(row) {
      let tempString = row.enable ? "停用" : "启用";
      this.$confirm(`是否${tempString}该活动?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          enableVipGroupActivity({ id: row.id }).then((res) => {
            if (res.code == 200) {
              this.$message.success("操作成功");
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.activeType {
  .right {
    .el-input {
      width: 150px !important;
    }
  }
}
.activeRange {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .left {
    height: 72px;
    line-height: 72px;
  }
  .right {
    .chioseWrap {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      height: 72px;
      line-height: 72px;
      align-items: center;
      .el-checkbox {
        margin-right: 20px;
      }
      .el-select {
        margin-right: 20px;
      }
    }
  }
}
.activeType {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .left {
    margin-right: 20px;
    p {
      height: 40px;
      line-height: 40px;
    }
  }
  .right {
    > div {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      height: 40px;
      line-height: 40px;
      margin-bottom: 20px;
      .head {
        width: 120px;
        height: 40px;
        line-height: 40px;
        border: 1px solid #ccc;

        text-align: center;
        border-radius: 5px;
        cursor: pointer;
        margin-right: 10px;
      }
      > .head.active {
        background-color: #13817a;
        color: #fff;
        border: none;
      }
      .title {
        line-height: 40px;
        height: 40px;
      }
    }
  }
}
.vipform {
  .el-select {
    width: 400px !important;
    .el-input__inner {
      width: 400px;
    }
  }
}
.ishidden {
  visibility: hidden;
}
</style>
