<template>
  <div class="mod-config">
    
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
   
      <el-form-item label="">
        <el-form-item
          label="湖分分类"
          
          prop="user"
          class="form_item"
        >
          <div>
            <el-select  size="small"
            clearable
              :show-all-levels="false"
              v-model="selectLabelId"
              :options="cateOptions"
              placeholder="湖分分类"
              @change="handleChange"
            >
              <el-option
                v-for="item in cateOptions"
                :key="item.id"
                    :label="item.dictValue"
                    :value="item.dictType"
              >
              </el-option
            ></el-select></div
        ></el-form-item>
        <!-- <el-form-item label="证书名称">
          <el-input
            v-model="dataForm.title"
            placeholder="请输入证书名称"
            clearable
          >
          </el-input>
        </el-form-item> -->
        <!-- <el-form-item label="">
        <el-input v-model="dataForm.userInfo" placeholder="用户手机/邮箱/姓名" clearable>
        </el-input>
      </el-form-item> -->

        <!-- <el-select v-model="dataForm.expire" placeholder="证书分类" 
        @change="
        pageIndex = 1;
            getDataList();">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button  size="small"
          @click="
            pageIndex = 1;
            getDataList();
          "
          >查询</el-button
        >
        <!-- <el-button
          @click="
            dataForm = {};
            selectLabelId=[]
            
          "
          >重置</el-button
        > -->
      </el-form-item>
      <el-form-item>
        <el-button @click="showAddD" type="primary"  size="small">充值</el-button>
      </el-form-item>
      <el-form-item style="float:right">
        <div v-if="user.id" class="flexbox userInfo" style="margin-bottom: 0;">
          <div>
            用户信息：{{ user.name }}{{ user.tel ? user.tel : user.email }}
          </div>
          <!-- <div>
            <span v-if="user.vip == 0">（普通用户）</span>
            <span v-else-if="user.vip == 2">（吴门医述VIP）</span>
            <span v-else-if="user.vip == 1">（超级VIP）</span>
            <span v-else-if="user.vip == 3">（众妙之门VIP）</span>
          </div> -->
         
        </div>
      </el-form-item>
    </el-form>
    <!-- <div style="color: rgb(22, 170, 104);font-weight: bold;text-align: right;">总湖分：{{ user.jf }}</div> -->
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;"
    >
      <el-table-column
        label="序号"
        width="100"
        align="center"
        prop="certificateNo"
      >
        <template slot-scope="scope">
          {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="title"
        header-align="center"
        align="center"
        width="140"
        label="湖分类型"
        ><template slot-scope="scope">
          <span>{{ getPointsType(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="score" width="140"
        header-align="center"
        align="center"
        label="湖分"
      >
      </el-table-column>
      <el-table-column
        prop="detail"
        header-align="center"
        align="center"
        label="描述"
      >
      </el-table-column>

      <!-- <el-table-column
                header-align="center"
                align="center"
                label="课程图"
                width="140"
              >
                <template slot-scope="scope">
                  <img
                    v-if="scope.row.image != ''"
                    :src="scope.row.image"
                    width="25"
                    height="35"
                    class="tableImg"
                  />
                </template>
              </el-table-column> -->

      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        width="180"
        label="创建日期"
      >
      </el-table-column>
    <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作"
      >
        <template slot-scope="scope">
         
          <el-button type="danger" @click="dataFormDelete(scope.row)" plain size="mini"
            >删除</el-button
          >
        </template>
      </el-table-column> 
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[50, 100, 200]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog
      title="充值湖分"
      :close-on-click-modal="false"
      :visible.sync="youVisible"
      append-to-body
      width="60%"
      @close="dialogClose"
    >
      <el-form
        style="width:100%"
        :model="youForm"
        label-width="100px"
        ref="youForm"
        :rules="youFormRule"
      >
        <el-form-item label="用户">
          {{ user.tel }} <span v-if="user.name != ''">{{ user.name }}</span>
          <span v-if="user.vip == 0">普通用户</span>
          <span v-else-if="user.vip == 2">（吴门医述VIP）</span>
          <span v-else-if="user.vip == 1">（超级VIP）</span>
          <span v-else-if="user.vip == 3">（众妙之门VIP）</span>
        </el-form-item>

        <el-form-item label="充值原因：" prop="come" style="width: 400px">
          <el-input
            v-model="youForm.come"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button @click="submit" type="primary">确认开通</el-button>
      </span>
    </el-dialog>
    <addCertificate
      @refresh="
        pageIndex = 1;
        getDataList();
      "
      ref="addCertificate"
      :data="addCertificateForm"
      pageType="user"
      :dataInfo="user"
    ></addCertificate>
  </div>
</template>

<script>
import debounce from "lodash/debounce"; //导入lodash中的debounce
import addCertificate from "@/views/modules/points/addPoints.vue";
// import AddOrUpdate from './user-add-or-update'
export default {
  data() {
    return {
      cateOptions: [],
      selectLabelId: "",
      dataForm: {
        key: "",
        expire: "",
        userInfo: ""
      },
      statusOptions: [
        {
          value: "0",
          label: "有效"
        },
        {
          value: "-1",
          label: "已过期"
        }
      ],

      userId: this.$route.query.id,
      user: {},
      pointFormRules: {
        pointAmount: [
          { required: true, message: "请输入金额", trigger: "blur" }
        ],
        pointType: {
          required: true,
          message: "请选择操作类型",
          trigger: "blur"
        }
      },
      youFormRule: {
        catalogueId: [
          { required: true, message: "请选择开通的分部", trigger: "blur" }
        ],
        days: [{ required: true, message: "请选择开通时长", trigger: "blur" }]
      },
      options: [],
      timeOptions: [
        // 开通时长
        {
          value: "30",
          label: "30天"
        },
        {
          value: "60",
          label: "60天"
        },
        {
          value: "90",
          label: "90天"
        },
        {
          value: "120",
          label: "120天"
        },
        {
          value: "150",
          label: "150天"
        },
        {
          value: "180",
          label: "180天"
        },
        {
          value: "365",
          label: "365天"
        },
        {
          value: "730",
          label: "730天"
        }
      ],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      total: 0,
      totalLaoding: false,
      dataListLoading: false,
      dataListSelections: [],

      youVisible: false,
      linshiids: [],

      youForm: {
        courseId: null,
        cate: [],
        catalogueId: "",
        days: "",
        come: "" //管理员开通(原因)
      },
      linshilist: [
        {
          title: "1"
        },
        {
          title: "2"
        },
        { title: "3" }
      ]
    };
  },
  components: {
    addCertificate
    // AddOrUpdate
  },
  created() {
    this.userId = this.$route.query.id;
    console.log(this.$route.query);
    console.log(this.userId, "onsole.log(this.$route.query)");
    this.init();
  },
  activated() {
    this.userId = this.$route.query.id;
    this.init();
    // this.getDataList()
    // this.getcourpeList()
  },
  methods: {
    getPointsType(type) {
      var str = "";
      //在线教学 01 学术期刊 03 太湖讲堂 05 创作技术 07 注册邀请 11 课程邀请 13
      this.cateOptions.forEach(item => {
        if (item.dictType == type) {
          str = item.dictValue;
        }
      });
      return str;
    },
    dataFormDelete: debounce(async function(row, deleteType) {
      console.log("row at line 515:", row);
      this.$confirm(
        `确定要删除${deleteType != "all" ? "该" : "所有"}湖分嘛?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          // var lableIds = row[0].bookLabelId;
          var productIds = row.id;

          await this.$http
            .request({
              url: this.$http.adornUrl(`/master/userContribution/delUserContribution`),
              method: "POST",
              data: {
                id: productIds
                // marketId: this.addForm.id
              },
              header: {
                //默认 无 说明：请求头
                "Content-Type": "application/json"
              }
            })
            .then(async ({ data }) => {
              if (data && data.code === 0) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(data.msg);
              }
              this.$nextTick(() => {
                // this.$refs.commonShop.selectShopArr = [];
               this.getDataList()
              });
            });
        })
        .catch(() => {});
    }, 200),
    getCateList() {
      this.$http({
        url: this.$http.adornUrl(
          "/master/userContribution/getUserContributionLabelList"
        ),
        method: "post",
        data: this.$http.adornData({})
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cateOptions = data.labelList;
        } else {
          this.cateOptions = [];
        }
        this.totalLaoding = false;
        if (data.code !== 0) return this.$message.error(data.msg);
      });
    },
    delay(val) {
      this.$nextTick(() => {
        this.$refs.addCertificate.init("edit", { val });
      });
    },
    delaySubmit(data) {
      this.$http({
        url: this.$http.adornUrl("/master/userCourseBuy/delayUserCourseBuy"),
        method: "post",
        data: this.$http.adornData(data)
      })
        .then(({ data }) => {
          if (data && data.code == 0) {
            this.$message.success("操作成功!");
            this.getDataList();
          } else {
            this.$message.error("操作失败!");
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },

    submit() {
      console.log(this.youForm, "youForm");
      this.youForm.catalogueId = this.linshiids.join(",");
      this.$refs["youForm"].validate(valid => {
        if (valid) {
          let data = {
            userId: this.userId,
            ...this.youForm
          };
          delete data.cate;
          console.log("data", data);
          this.$http({
            url: this.$http.adornUrl(
              "/master/userCourseBuy/insertUserCourseBuy"
            ),
            method: "post",
            data: this.$http.adornData(data)
          })
            .then(({ data }) => {
              if (data.code !== 0) return this.$message.error(data.msg);
              this.$message.success("开课成功!");
              this.getDataList();
              this.dialogClose();
            })
            .catch(e => {
              console.log("表单提交报错");
            });
        }
      });
    },
    dialogClose() {
      this.youVisible = false;
      this.linshiids = [];
      this.$nextTick(() => {
        this.youForm.cate = [];
        this.options = [];

        this.$refs["youForm"].resetFields();
        console.log(this.youForm, "youForm");
      });
      console.log(this.youForm, "youForm");
    },
    selectChange(val) {
      console.log("options", this.options);
      this.getCate(val);
    },
    remoteMethod(query) {
      console.log(query, "query", this.youForm.key);
      // return false
      if (this.youForm.key !== "") {
        let data = {
          // page: this.pageIndex,
          // limit: this.pageSize,
          title: query //关键字
          // medicalId: "",
          // sociologyId: "",
          // type: 0
        };
        this.totalLaoding = true;
        this.$http({
          url: this.$http.adornUrl("/master/userManage/courseAndChildrenList"),
          method: "post",
          data: this.$http.adornData(data)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.options = data.list;
          } else {
            this.options = [];
          }
          this.totalLaoding = false;
          if (data.code !== 0) return this.$message.error(data.msg);
        });
      } else {
        this.options = [];
        this.totalLaoding = false;
      }
    },
    showAddD() {
      this.$nextTick(() => {
        this.$refs.addCertificate.init("add", {});
      });
    },

    init() {
      this.getCateList();
      // if (!this.userId) {
      //   setTimeout(() => {
      //     this.init();
      //   }, 1000);
      // }
      this.$http({
        url: this.$http.adornUrl(`/book/user/info/${this.userId}`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code !== 0) return this.$message.error(data.msg);

        this.user = data.user;
        this.getDataList();
      });
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        // url: this.$http.adornUrl('/book/user/list'),
        url: this.$http.adornUrl("/master/userContribution/listByPage"),
        method: "post",
        data: this.$http.adornData({
          current: this.pageIndex,
          limit: this.pageSize,
          userId: this.userId, //用户id
          userName: "",
          // "userId": "",
          tel: "",
          email: "",
          type: this.selectLabelId //课程名
        })
      }).then(({ data }) => {
        if (data && data.code !== 0) return this.$message.error(data.msg);
        console.log(data, "data");
        this.dataList = data.result.records;
        this.totalPage = data.result.pages;
        this.total = data.result.total;
        this.dataListLoading = false;
      });
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // // 多选
    // selectionChangeHandle(val) {
    //   this.dataListSelections = val
    // },
    // 新增 / 修改
    closeDia() {
      this.adc = false;
      this.$refs.pointForm.resetFields();
      // this.pointForm.pointType == 0
    },
    getCate(id) {
      this.linshiids = [];

      this.$http({
        url: this.$http.adornUrl("/master/userManage/catalogueListByCourse"),
        method: "post",
        data: this.$http.adornData({
          courseId: id
        })
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            console.log("data", "data++++++++++++++++++++");
            this.youForm.cate = data.list;
            // this.youForm.cate
          } else {
            this.youForm.cate = [];
            this.linshiids = [];
          }
        })
        .catch(e => {
          console.log("数据报错");
        });
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .width100 .el-input__inner {
  width: 100%;
}
.flexbox {
  display: flex;
}
.userInfo {
  margin-bottom: 20px;
}
.userInfo * {
  font-size: 16px;
}
</style>
