<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
      style="position: relative;"
    >
      <el-form-item label="手机号">
        <el-input
          v-model="dataForm.tel"
          placeholder="请输入手机号"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="
            pageIndex = 1;
            getDataList();
          "
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="addHandle()"
          >报名</el-button
        >
      </el-form-item>
      <el-form-item style="position: absolute; right: 0; top: 0; margin-right: 0;">
        <el-button
          type="primary"
          @click="handleExport()">
          导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="60">
      </el-table-column>
      <el-table-column label="报名时间" align="center" prop="createTime" width="170" sortable="custom" :sort-orders="['ascending', 'descending']">
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderSn"></el-table-column>
      <el-table-column label="培训姓名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.user.name ? scope.row.user.name : "暂无姓名" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center">
        <template slot-scope="scope">{{ scope.row.user.tel||'-' }}</template>
      </el-table-column>
      <el-table-column label="用户身份" align="center">
        <template slot-scope="scope">
          {{ splitIdentity(scope.row.identity).type }}
        </template>
      </el-table-column>
      <el-table-column label="费用" align="center">
        <template slot-scope="scope">
          {{ splitIdentity(scope.row.identity).price ? `¥${splitIdentity(scope.row.identity).price}` : '' }}
        </template>
      </el-table-column>
     
      <el-table-column label="支付方式" align="center">
        <template slot-scope="scope">{{ scope.row.payMethod }}：{{ scope.row.realMoney }}</template>
      </el-table-column>
      <el-table-column label="积分抵扣" align="center">
        <template slot-scope="scope">积分：{{ scope.row.jfDeduction }}</template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog
      :visible.sync="addVisible"
      title="添加用户"
      class="dialog_box"
      @close="cancleClose"
      width="600px"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRule"
        label-width="100px"
      >  
        <el-form-item label="手机号/邮箱" prop="userKey" style="width: 530px;">
          <el-input v-model="addForm.userKey" placeholder="请输入手机号/邮箱" clearable @input="handleSearch"></el-input>
          <div class="data-list" v-if="showSearch" v-loading="searchListLoading">
            <span v-for="(v,i) in searchList" :key="i" @click="checkTitle(v)">{{ v.tel }}</span>
          </div>
        </el-form-item>
        <el-form-item label="用户身份" v-if="infoStatus">
          {{ info.identity }}
        </el-form-item>
        <el-form-item label="最终价格" v-if="infoStatus">
          {{ info.fee }}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleClose">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      trainingId: null,
      trainingTitle: '',
      dataForm: {
        tel: ''
      },
      addForm: {
        userId: '',
        userKey: ''
      },
      editId: "",
      addFormRule: {
        userKey: [
          {
            required: true,
            message: "请输入手机号/邮箱",
          },
        ]
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      searchListLoading: false,
      addVisible: false,
      //新增-模糊查询
      showSearch: false,
      searchList: [],
      sortParams: {        // 排序参数
        field: 'date',    // 默认排序字段
        order: 'desc'     // 默认降序
      },
      //获取身份和价格
      infoStatus: false,
      info: {},
      //日期排序
      sortParams: {
        date: ''
      }
    };
  },
  activated(){
    this.trainingId = this.$route.query.id;
    this.trainingTitle = this.$route.query.title;
    this.getDataList();
  },
  methods: {
    splitIdentity(identity) {
      const match = identity.match(/([^\d：]+)(：)([\d.]+)/);
      return {
        type: match ? match[1].trim() : identity,
        price: match ? match[3] : ''
      };
    },
    //排序变化事件
    handleSortChange({ column, prop, order }) {
      this.sortParams.date = order 
          ? (order === 'ascending' ? '2' : '1') 
          : null;
      this.getDataList();
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/master/trainingClass/trainingClassUserList"),
        method: "post",
        data: this.$http.adornData({
          current: this.pageIndex,
          limit: this.pageSize,
          trainingId: this.trainingId,
          tel: this.dataForm.tel,
          createTimeSort: this.sortParams.date
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.trainingClassUserList.records;
          this.totalPage = data.trainingClassUserList.total;
        }
        this.dataListLoading = false;
      });
    },
    //添加用户
    addHandle(){
      this.addVisible = true;
      this.$refs["addFormRef"].resetFields();
      this.addForm = {
        userId:'',
        userKey: ''
      }
      this.infoStatus = false;
      this.info = {};
    },
    //取消
    cancleClose(){
      this.addVisible = false;
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    //模糊查询
    handleSearch(val){
      if(val){
        this.showSearch = true;
        this.searchListLoading = true;
        this.infoStatus = false;
        this.info = {}
        this.$http({
          url: this.$http.adornUrl("/book/user/getUserList"),
          method: "post",
          data: this.$http.adornData({
            page: 1,
            limit: 9999,
            key: val
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            if(data.user.records&&data.user.records.length>0){
              this.searchList = data.user.records;
            }else{
              this.searchList = [];
            }
            this.searchListLoading = false;
          }
        });
      }else{
        console.log('输入框已被清空');
        this.infoStatus = false;
        this.info = {}
      }
    },
    //选中模糊值
    checkTitle(v){
      this.addForm.userId = v.id;
      this.addForm.userKey = v.tel;
      this.showSearch = false;
      this.getFinalPriceByUser();
    },
    //获取角色和价格
    getFinalPriceByUser(){
      this.$http({
        url: this.$http.adornUrl("/common/trainingClass/getFinalPriceByUser"),
        method: "post",
        data: this.$http.adornData({
          userId: this.addForm.userId,
          classId: Number(this.trainingId)
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if(data.info){
            this.infoStatus = true;
            this.info = data.info;
          }else{
            this.infoStatus = false;
          }
        }else{
          this.$message.error(data.msg);
        }
      });
    },
    //添加用户
    addCate(){
      this.$refs["addFormRef"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/master/trainingClass/addUserToTrainingClass"),
            method: "post",
            data: this.$http.adornData({
              userId: this.addForm.userId,
              trainingId: this.trainingId,
              identity: this.info.identity+'：'+this.info.fee
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.addVisible = false;

              this.getDataList();
            }else{
              this.$message.error(data.msg);
            }
          });
        }
      })
    },
    //删除
    deleteHandle(row){
      this.$confirm("确定要删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(() => {
        this.$http({
          url: this.$http.adornUrl("/master/trainingClass/delUserToTrainingClass"),
          method: "post",
          data: this.$http.adornData({
            id: row.id
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
                message: "操作成功",
                type: "success"
              });

              this.getDataList();
          }
        });
      })
      .catch(() => {});
    },
    //导出
    handleExport() {
      this.dataListLoading = true;
      try {
        this.$http({
          url: this.$http.adornUrl("/master/trainingClass/exportTrainingClassUser"),
          method: "post",
          data: this.$http.adornData({
            trainingId: this.trainingId,
            tel: this.dataForm.tel,
            createTimeSort: this.sortParams.date
          }),
          responseType: "blob"
        }).then(res => {
          const blob = new Blob([res.data], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          });

          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = '['+ this.trainingTitle +']-用户数据文件';
          link.click();

          window.URL.revokeObjectURL(link.href); // 释放内存
          this.dataListLoading = false;
          this.$message({
            message: "培训班用户数据文件下载完成,请注意查看！",
            type: "success",
            duration: 3000,
            showClose: true
          });

        });
      } catch (err) {
        this.$message.error("文件下载失败!");
        this.dataListLoading = true;
      }
    },
  },
};
</script>

<style lang="less" >
::v-deep.custom-height {
  height: 370px;
}
.avatar-uploader {
  height: 1px;
}
.general_editor {
  height: 420px;
  width: 1060px !important;
}
.editor_form {
  height: 500px;
}

.dialog_box {
  .el-form-item__content {
    width: calc(100% - 90px) !important;
  }
  .form_item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-form-item {
      width: 290px;
    }
  }
}

.data-list{
  min-height: 200px;
  width: 100%;
  border-radius: 4px;
  background: #fff;
  position: absolute;
  z-index: 99;
  top: 40px;
  left: 0;
  padding: 10px 20px;
  cursor: pointer;
  max-height: 280px;
  overflow-y: scroll;

  span{
    color: #606266;
    line-height: 36px;
    font-size: 14px;
    display: block;
  }
}
</style>
