<template>
  <div>
    <div class="headerRow headerRowLeftRight">
      <div class="headerRow">
        <el-input placeholder="请输入用户名或账号搜索" v-model="searchKeyLin" @keyup.enter.native="onSubmit" style="width: 260px">
          <el-button slot="append" icon="el-icon-search" @click="onSubmit"></el-button>
        </el-input>

        <el-select v-model="value" @change="onSubmit" placeholder="用户状态" style="width: 120px" class="mrl">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>

        <el-select v-model="groupValue" @change="onSubmit" placeholder="年级选择" style="width: 120px" class="mrl">
          <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id">
          </el-option>
        </el-select>

        <el-button class="ml10" icon="el-icon-refresh" @click="reset"></el-button>
        <el-button class="ml10" type="primary" icon="el-icon-plus" @click="exportUser">批量导入</el-button>
        <el-button v-if="systemVersion != 'lan'" class="ml10" type="primary" icon="el-icon-s-check"
          @click="allUserCheck">一键审核</el-button>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="petName" label="用户名称" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="账号" width="auto" align="center">
      </el-table-column>
      <el-table-column prop="gender" label="性别" align="center" :formatter="sexFormat"></el-table-column>
      <el-table-column prop="birthday" label="生日" width="auto" align="center">
      </el-table-column>
      <!-- <el-table-column prop="institutionName" label="所属学校" width="auto" align="center">
      </el-table-column> -->
      <el-table-column prop="profession" label="职业" align="center">
      </el-table-column>
      <el-table-column prop="gid" label="年级名称" align="center">
      </el-table-column>
      <el-table-column prop="userStatus" label="用户状态" align="center" :formatter="statusFormat">
      </el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <!--        <template slot-scope="scope">-->
        <!--          <el-button type="primary" v-if="scope.row.userStatus=='1'" size="small" @click="editUser(scope.row)">审核通过-->
        <!--          </el-button>-->
        <!--        </template>-->
        <template slot-scope="scope">
          <!-- <el-button
            type="primary"
            size="small"
            @click="getUserInfoDetail(scope.row)"
            style="margin-top: 10px"
            >查看详情
          </el-button> -->
          <el-button type="primary" size="small" @click="handleResetPwd(scope.$index, scope.row)">重置密码
          </el-button>
          <!--          <el-dialog title="重置密码" :visible.sync="personalSecurityDialog" width="40%">-->
          <!--            <el-form :model="updatePersonalSecurity" status-icon :rules="personalSecurityRules" ref="ruleFormSecurity">-->
          <!--              <el-form-item label="输入密码：" prop="userpwd">-->
          <!--                <el-input type="password" v-model="updatePersonalSecurity.userpwd" autocomplete="off"-->
          <!--                          style="width: 50%"></el-input>-->
          <!--              </el-form-item>-->
          <!--              <el-form-item label="确认密码：" prop="checkPass">-->
          <!--                <el-input type="password" v-model="updatePersonalSecurity.checkPass" autocomplete="off"-->
          <!--                          style="width: 50%"></el-input>-->
          <!--              </el-form-item>-->
          <!--              <el-form-item>-->
          <!--                <el-button type="primary" @click="handleEditSecurity('ruleFormSecurity')">提交</el-button>-->
          <!--                <el-button @click="resetFormForPersonalSecurity('ruleFormSecurity')">取消</el-button>-->
          <!--              </el-form-item>-->
          <!--            </el-form>-->
          <!--          </el-dialog>-->
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
          <el-button type="primary" v-if="scope.row.userStatus != '2' && scope.row.userStatus != '4'" size="small"
            @click="editUser(scope.row)">审核通过
          </el-button>
        </template>
        <!--        &lt;!&ndash;<template slot-scope="scope">-->
        <!--          &lt;!&ndash; <el-popconfirm-->
        <!--            confirm-button-text='确定'-->
        <!--            cancel-button-text='取消'-->
        <!--            icon="el-icon-info"-->
        <!--            icon-color="red"-->
        <!--            title="你确定要删除此签名信息吗？"-->
        <!--          >-->
        <!--            <el-button slot="reference" type="text" @click="deleteUser(scope.$index,scope.row)"  class="button-table-font">删除</el-button>-->
        <!--          </el-popconfirm> &ndash;&gt;-->

        <!--          <el-button type="text" v-if="scope.row.userStatus=='1'"  size="small" @click="editUser(scope.row)">审核通过</el-button>-->
        <!--        </template>&ndash;&gt;-->
      </el-table-column>
    </el-table>
    <div class="txt-center" style="margin-top: 20px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="addUserEditFlag" :visible.sync="addUser" width="40%" center :close-on-click-modal="false">
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form :inline="true" :model="ruleForm" label-position="left" :rules="rules" ref="ruleForm"
            class="demo-form-inline demo-ruleForm">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="签字" prop="signature">
                  <el-input v-model="ruleForm.signature" placeholder="签字"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签名类型" prop="type">
                  <el-select v-model="ruleForm.type" placeholder="请选择签名">
                    <el-option label="报告签名" value="report"></el-option>
                    <el-option label="审核签名" value="audit"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="24">
              <el-col :span="12"> -->
            <el-form-item label="请选择签名照" prop="signature">
              <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- 	</el-col>
            </el-row> -->
          </el-form>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-row :gutter="20">
          <el-col :span="2">
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-button type="primary" @click="addUser = false">确 定</el-button>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-button @click="addUser = false">取 消</el-button>
            </div>
          </el-col>
        </el-row>
      </span>
    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog :close-on-click-modal="false" title="批量导入" :visible.sync="dialogTableVisible">
      <el-upload class="txt-center" :action="uploadUrl" multiple :before-upload="uploadVa" :limit="3"
        :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadFail" :file-list="fileList" :data="{
          institutionNo: institutionNo,
          userId:createUserId,
        }">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">请上传.xls,.xlsx类型的文件</div>
      </el-upload>
      <div class="mt20 txt-center" @click="downloadTemplete">
        <el-link type="primary">点击下载模板</el-link>
      </div>
      <el-table v-if="userList.length > 0" :data="userList">
        <el-table-column property="date" label="日期" width="150"></el-table-column>
        <el-table-column property="name" label="姓名" width="200"></el-table-column>
        <el-table-column property="address" label="地址"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "UserInfoDetail",
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.updatePersonalSecurity.checkPass !== "") {
          this.$refs.ruleFormSecurity.validateField("checkPass");
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.updatePersonalSecurity.userpwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      systemVersion: process.env.VUE_APP_VERSION,
      //年级过滤条件
      groupValue: "",
      //年级信息
      groupOptions: [],

      searchKeyLin: "", //查询条件
      searchKey: "", //查询条件
      institutionNo: "", //学校编码
      moreUser: false,
      addUser: false,
      addUserEditFlag: "",
      imageUrl: "",
      formInline: {
        user: "",
        region: "",
      },
      ruleForm: {
        signature: "", //签字
        type: "", //签名类型
      },
      options: [
        {
          value: "2",
          label: "已审核",
        },
        {
          value: "1",
          label: "未审核",
        },
        {
          value: "3",
          label: "待登录",
        },
        {
          value: "4",
          label: "待补充",
        },
      ],
      value: "",
      currentPage: 1,
      total: 0,
      pageSize: 10,
      createUserId: '',
      updatePersonalSecurity: {},
      rules: {
        signature: [
          { required: true, message: "请输入被监护人", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        type: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      tableData: [],
      personalSecurityDialog: false,

      personalSecurityRules: {
        userpwd: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      dialogTableVisible: false,
      userList: [],
      fileList: [],
      uploadUrl: baseUrl + "/userImport",
    };
  },
  created() {
    this.institutionNo = sessionStorage.getItem(
      "f7a42fe7211f98ac7a60a285ac3a9527"
    );
    this.createUserId = sessionStorage.getItem(
      "b80bb7740288fda1f201890375a60c8f"
    );
    this.getData();
    this.groupFun();
  },

  methods: {
    //查询年级信息
    groupFun() {
      this.$http.get(
        // "/group/find?institutionNo=" + this.institutionNo,
        `/group/find?institutionNo=${this.institutionNo}&userId=${this.createUserId}`,

        {},
        (response) => {
          this.groupOptions = response.data;
          // this.tableData = response.data;
          // console.log(response.data)
        }
      );
    },

    uploadVa(file) {
      console.log(file);
      let q = file.name.split(".");
      if (!(q[1] === "xls" || q[1] === "xlsx")) {
        this.$message.error("请选择xls或xlsx");
        return false;
      }
    },
    sexFormat(row) {
      if (row.gender == 0) {
        return "男";
      } else {
        return "女";
      }
    },
    PersonalSecurityJump() {
      this.updatePersonalSecurity = {};
      this.personalSecurityDialog = true;
    },
    handleDelete(index, row) {
      this.$confirm("您确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //delete方法不用$qs就可以，按照下面的方法传参即可
        this.$http.post(`/user/delete/${row.id}`, {}, (res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          } else {
            this.$message({
              type: "info",
              message: "未成功删除",
            });
          }
        });
      });
    },
    handleResetPwd(index, row) {
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     this.$confirm('您确定要提交, 是否继续?', '提示', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning'
      //     }).then(() => {
      //       //delete方法不用$qs就可以，按照下面的方法传参即可
      //       this.$refs[formName].validate((valid) => {
      //         if (valid) {
      //
      //           this.$http.post(`/user/resetPassword`,
      //               this.updatePersonalSecurity
      //           ).then(response => {
      //             if (response.data.code == 200) {
      //               this.$message({
      //                 type: 'success',
      //                 message: '重置成功!'
      //
      //               });
      //               this.personalSecurityDialog = false;
      //               this.getData()
      //             }
      //           })
      //         } else {
      //           console.log('error submit!!');
      //           this.arrangeClassDialog = false;
      //           return false;
      //         }
      //       });
      //
      //     }).catch(() => {
      //       this.$message({
      //         type: 'info',
      //         message: '重置失败'
      //       });
      //     });
      //
      //
      //   } else {
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });

      this.$confirm("您确定要重置该用户的密码吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //delete方法不用$qs就可以，按照下面的方法传参即可
        this.$http.post(`user/resetPassword/${row.id}`, {}, (res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "重置成功!重置后密码为：123456",
            });
            this.getData();
          } else {
            this.$message({
              type: "error",
              message: "重置失败",
            });
          }
        });
      });
    },
    resetFormForPersonalSecurity() {
      // this.$refs[formName].resetField();
      this.updatePersonalSecurity = {};
      this.personalSecurityDialog = false;
    },
    // 刷新列表
    reset() {
      this.currentPage = 1;
      this.searchKey = "";
      this.value = "";
      this.groupValue = "";
      this.getData();
    },
    // 批量导入用户
    exportUser() {
      this.dialogTableVisible = true;
    },

    // 批量导入成功
    uploadSuccess(res) {
      this.reset();
      // this.$message.success(res.msg);
      // window.location.href = `${baseUrl}/download/userImportResult?filePath=${res.data}`;
      this.getData();

      //部分未成功也会在此提示
      this.$alert(`${res.msg}`, '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        center: true,
        callback: action => {
          // this.$message({
          //   type: 'info',
          //   message: `action: ${ action }`
          // });
        }
      });
    },

    // 批量导入失败
    uploadFail(res) {
      // this.$message.error(res.msg);
      this.$alert(`${res.msg}`, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        center: true,
        callback: action => {
          // this.$message({
          //   type: 'info',
          //   message: `action: ${ action }`
          // });
        }
      });
    },

    // 下载模板
    downloadTemplete() {
      window.location.href = `${baseUrl}/download/userTemplateDownload`;
    },
    statusFormat(row) {
      if (row.userStatus == 2) {
        return "已审核";
      } else if (row.userStatus == 1) {
        return "未审核";
      } else if (row.userStatus == 3) {
        return "待登录";
      } else if (row.userStatus == 4) {
        return "待补充";
      } else {
        return "--";
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    //lxh 用户信息
    getUserInfoDetail(row) {
      this.$router.push({
        path: "/ContainerSys/UserInfoDetail",
        query: {
          phone: row.phone,
        },
      });
    },

    //编辑用户
    editUser(row) {
      this.$http.get(
        "/user/updateStatus?bid=" + row.id + "&status=2",
        {},
        () => {
          this.getData();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        }
      );
      // this.addUser=true;
      // //设置标题
      // this.addUserEditFlag="编辑用户";
      // //1.点击编辑先置空
      // this.ruleForm=[];
      // //2.接下来进行赋值
    },
    //一键审核所有用户
    allUserCheck() {

      this.$confirm('此操作将所有待审核用户一键通过审核, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get("/user/updateStatusAll?institutionNo=" + this.institutionNo, {}, (res) => {

          if (res && res.code == '200') {
            this.getData();
            this.$message({
              type: "success",
              message: "一键审核成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: "一键审核失败!",
            });
          }

        });
        // this.$message({
        //   type: 'success',
        //   message: '审核成功!'
        // });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        });
      });

    },
    //添加单个用户
    // addSingleUser(){
    // 	this.addUser=true;
    // 	//设置弹出框表题
    // 	this.addUserEditFlag="添加用户";
    // 	//1.点击添加先把之前填的置空
    // 	this.ruleForm=[];
    // },
    //删除用户
    deleteUser() { },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    getData() {
      this.searchKeyLin = this.searchKey;
      this.$http.get(
        "/user/getUserListByInstitutionNo?institutionNo=" +
        this.institutionNo +
        "&searchKey=" +
        this.searchKey +
        "&pageNum=" +
        this.currentPage +
        "&pageSize=" +
        this.pageSize +
        "&status=" +
        this.value +
        "&groupId=" +
        this.groupValue +
        "&userId=" +
        this.createUserId,
        {},
        (response) => {
          this.total = response.data.allNum;
          this.tableData = response.data.data;
          console.log(this.tableData);
        }
      );
    },
    onSubmit() {
      this.currentPage = 1;
      this.searchKey = this.searchKeyLin;

      //点击搜索时需要将值赋值给搜索的按钮
      this.getData();
    },
  },
};
</script>
<style>
.bg-purple-dark {
  background: white;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.mainTable {
  /*width: 80%;*/
  margin-top: 20px;
}
</style>
