<template>
  <div class="content-box">
    <div class="left">
      <el-icon :size="23" class="camera"><UserFilled /></el-icon>
      <span class="cameratxt">用户管理</span>
    </div>
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>姓名 </span>
          <el-input
            clearable
            v-model="searchData.input1"
            class="w-50 m-2"
            placeholder="请输入姓名"
            style="width: 150px"
          />
        </div>
        <div class="condition">
          <span>账号 </span>
          <el-input
            clearable
            v-model="searchData.input2"
            class="w-50 m-2"
            placeholder="请输入账号"
            style="width: 150px"
          />
        </div>
        <div class="condition">
          <span>联系方式 </span>
          <el-input
            clearable
            v-model="searchData.input3"
            class="w-50 m-2"
            placeholder="请输入联系方式"
            style="width: 180px"
          />
        </div>
        <div class="condition">
          <span>角色 </span>
          <el-select
            style="width: 120px"
            v-model="searchData.input4"
            class="m-2"
            placeholder="请选择角色"
          >
            <el-option label="管理员" value="2" />
            <el-option label="超级管理员" value="1" />
          </el-select>
        </div>

        <div class="condition">
          <span>创建时间 </span>
          <el-date-picker
            v-model="searchData.input5"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <el-button type="primary" class="search" @click="search">搜索</el-button>
        <el-button type="primary" plain @click="resetInput">重置</el-button>
      </div>

      <!-- 按钮列表 -->

      <div class="gongneng">
        <el-button type="primary" plain @click="addlist">新增</el-button>
        <el-button type="success" plain @click="importExcel">导入</el-button>
        <el-button type="warning" plain @click="downLoad">导出</el-button>
        <el-button type="danger" plain @click="allDel">删除</el-button>
      </div>

      <!-- 编辑/新增管理员 -->
      <el-dialog
        v-model="centerDialogVisible"
        :title="dialongTitle"
        width="30%"
        align-center
        :before-close="editClose"
      >
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="region">
            <el-select
              v-model="ruleForm.region"
              style="width: 180px"
              placeholder="请选择性别"
            >
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="账号" prop="date1">
            <el-input v-model="ruleForm.date1" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="date2" v-show="dialongTitle == '新增用户'">
            <el-input v-model="ruleForm.date2" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="类别" prop="resource">
            <el-select v-model="ruleForm.resource" placeholder="请选择类别">
              <el-option label="超级管理员" value="1" />
              <el-option label="管理员" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 导入用户按钮 -->
      <el-dialog
        v-model="importByExcelDialog"
        title="导入用户信息"
        width="45%"
        align-center
        custom-class="importExecl"
      >
        <el-steps :active="active" align-center finish-status="success">
          <el-step title="下载模板 1" :icon="Pointer" />
          <el-step title="执行上传 2" :icon="Upload" />
          <el-step title="导入完成 3" :icon="Select" />
        </el-steps>
        <div class="cont">
          <div class="download">
            <el-icon :size="30"><Pointer /></el-icon><span>请按照数据模板导入数据</span>
          </div>
          <el-button type="primary">
            <a href="/video/videoManage/userProfile.xlsx" style="color: #fff">下载模板</a>
          </el-button>
          <div class="upload">
            <div class="download">
              <el-icon :size="30"><Upload /></el-icon
              ><span>将文件上传(用户上传的excel文件需要符合规定的格式)</span>
            </div>
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="none"
              :limit="1"
              :multiple="false"
              :auto-upload="false"
              :on-change="changeUpload"
              :before-remove="beforeRemove"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅允许上传一个文件</div>
              </template>
            </el-upload>
          </div>
          <div class="accomplish">
            <el-button
              type="primary"
              :disabled="active == 1"
              style="margin-top: 12px"
              @click="next"
              >完成导入</el-button
            >
          </div>
        </div>
      </el-dialog>
    </div>
    <div class="footer">
      <el-table
        :row-class-name="tableRowClassName"
        :data="tableData.list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="80" />
        <el-table-column align="center" prop="name" label="姓名" width="100" />
        <el-table-column align="center" width="100" prop="sex" label="性别" />
        <el-table-column align="center" prop="username" label="用户名(账号)" />
        <el-table-column align="center" prop="adminType" label="类别" />
        <el-table-column align="center" prop="phone" label="手机号码" />
        <el-table-column align="center" width="300" prop="createTime" label="创建时间" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleUp(scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" size="small" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      v-model:page-size="pageSize"
      v-model:current-page="currentPage"
      layout="total, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { Select, Pointer, Upload } from "@element-plus/icons-vue";
import { JSEncrypt } from "jsencrypt"; // 加密密码
import { ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import axios from "axios";
import lodash from "lodash";
import adminApi from "@/api/admin.js";
const router = useRouter();

// 搜索框数据
const searchData = reactive({
  input1: "",
  input2: "",
  input3: "",
  input4: "",
  input5: "",
});
// 表格数据
const tableData = reactive({ list: [] });
const dialongTitle = ref(""); // 弹窗标题
const pageSize = ref(13);
const currentPage = ref(1); // 当前页
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据
const centerDialogVisible = ref(false); // 控制新增或修改弹窗开关

const importByExcelDialog = ref(false); // 控制导入弹窗
const active = ref(1); // 导入步骤计数
const fileList = ref(); // 上传的文件

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();

const ruleForm = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  phone: "",
  resource: "",
  id: "",
});
// 表单验证
const rules = reactive({
  region: [
    {
      required: true,
      message: "请选择性别",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "blur",
    },
  ],
  date1: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  date2: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入电话号码",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  resource: [
    {
      required: true,
      message: "请选择类别",
      trigger: "blur",
    },
  ],
});
// 路由
const handleSelect = (key, keyPath) => {
  router.push({
    path: `/vidicons/${key}`,
  });
};
// 获取管理员列表
const getList = (curPage) => {
  adminApi
    .adminList({ pageSize: 13, curPage })
    .then((res) => {
      console.log(res);
      total.value = res.data.totalCount;
      res.data.list.forEach((item) => {
        if (item.sex == 0) {
          item.sex = "女";
        } else if (item.sex == 1) {
          item.sex = "男";
        }
        if (item.adminType == "1") {
          item.adminType = "超级管理员";
        } else if (item.adminType == "2") {
          item.adminType = "管理员";
        }
      });

      tableData.list = res.data.list;
    })
    .catch((err) => {
      console.log(err);
    });
};

// 搜索按钮
const search = lodash.debounce(() => {
  let startTime = "";
  let endTime = "";
  if (searchData.input5 == []) {
    startTime = "";
    endTime = "";
  } else {
    startTime = searchData.input5[0];
    endTime = searchData.input5[1];
  }

  let data = {
    pageSize: 13,
    curPage: 1,
    name: searchData.input1,
    username: searchData.input2,
    phone: searchData.input3,
    adminType: searchData.input4,
    startTime,
    endTime,
  };
  adminApi
    .adminList(data)
    .then((res) => {
      console.log(res);
      total.value = res.data.totalCount;
      res.data.list.forEach((item) => {
        if (item.sex == 0) {
          item.sex = "女";
        } else {
          item.sex = "男";
        }
        if (item.adminType == "1") {
          item.adminType = "超级管理员";
        } else {
          item.adminType = "管理员";
        }
      });
      ElMessage({
        type: "success",
        showClose: true,
        message: "搜索成功",
        center: true,
      });
      currentPage.value = 1;
      tableData.list = res.data.list;
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "error",
        showClose: true,
        message: "搜索失败",
        center: true,
      });
    });
}, 300);
// 重置搜索框
const resetInput = lodash.debounce(() => {
  searchData.input1 = "";
  searchData.input2 = "";
  searchData.input3 = "";
  searchData.input4 = "";
  searchData.input5 = "";
  currentPage.value = 1;
  getList(1);
}, 300);
// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};

// 删除多选IP
const allDel = () => {
  console.log(selectData.list);
  ElMessageBox.confirm("此操作将永久删除所选用户，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let idIP = [];
      selectData.list.forEach((item) => {
        idIP.push(item.id);
      });
      console.log(idIP);
      let res = await adminApi.adminDel(idIP);
      if (res.success) {
        if (
          tableData.list.length - selectData.list.length == 0 &&
          currentPage.value != 1
        ) {
          currentPage.value = currentPage.value - 1;
        }
        ElMessage({
          type: "success",
          showClose: true,
          message: "删除成功",
          center: true,
        });
        getList(currentPage.value);
      } else {
        ElMessage({
          type: "warning",
          showClose: true,
          message: "删除失败",
          center: true,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 重置表单
const resetForm = (formEl) => {
  formEl.resetFields();
  console.log("重置表单");
  ruleForm.phone = "";
  ruleForm.date1 = "";
  ruleForm.resource = "";
  // ruleForm.password=,
  ruleForm.region = "";
  ruleForm.name = "";
  ruleForm.date2 = "";
  // if (!formEl) return;

  // formEl.resetFields();
};

//新增按钮
const addlist = () => {
  dialongTitle.value = "新增用户";
  ruleForm.phone = "";
  ruleForm.date1 = "";
  ruleForm.resource = "";
  // ruleForm.password=,
  ruleForm.region = "";
  ruleForm.name = "";
  ruleForm.date2 = "";
  centerDialogVisible.value = true;
};
//修改按钮
const handleUp = (row) => {
  console.log(row);
  ruleForm.id = row.id;
  ruleForm.phone = row.phone;
  ruleForm.date1 = row.username;
  ruleForm.name = row.name;
  ruleForm.date2 = row.password;
  ruleForm.region = row.sex;
  ruleForm.resource = row.adminType;
  dialongTitle.value = "修改用户";
  centerDialogVisible.value = true;
};

// 关闭新增/修改页面
const editClose = (done) => {
  ruleFormRef.value.resetFields();
  ruleForm.phone = "";
  ruleForm.date1 = "";
  ruleForm.resource = "";
  // ruleForm.password=,
  ruleForm.region = "";
  ruleForm.name = "";
  ruleForm.date2 = "";
  centerDialogVisible.value = false;
  done();
};
// 确定表单
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      if (dialongTitle.value == "新增用户") {
        let publicKey =
          "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMOcPB06u5yKyQsPjfVWiWgbEIrd14kiXNNihciaVKb6HnkQvq7zpQuZ80WEX94spnUMI3iOAl/GmIvHrpGwcbB4hJbznm+PajiwnUSPuCCXA68YJF640cJKb/8KeM7WVz69OFkIEPHhVxOy4FFF5QWe/kt6zOZ19HmE+ak+5x/QIDAQAB";
        let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
        encryptor.setPublicKey(publicKey); // 设置公钥
        let rsaPassWord = encryptor.encrypt(ruleForm.date2); // 对密码进行加密
        let data = {
          phone: ruleForm.phone,
          username: ruleForm.date1,
          adminType: ruleForm.resource,
          password: rsaPassWord,
          sex: ruleForm.region,
          name: ruleForm.name,
          createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };
        if (data.sex == "女") {
          data.sex = 0;
        } else if (data.sex == "男") {
          data.sex = 1;
        }
        if (data.adminType == "超级管理员") {
          data.adminType = 1;
        } else if (data.adminType == "管理员") {
          data.adminType = 2;
        }
        adminApi
          .adminAdd(data)
          .then((res) => {
            console.log(tableData.list.length);
            if (res.success) {
              if (tableData.list.length == 13) {
                currentPage.value = currentPage.value + 1;
              }
              ElMessage({
                type: "success",
                showClose: true,
                message: res.message,
                center: true,
              });
              getList(currentPage.value);
              ruleFormRef.value.resetFields();
              centerDialogVisible.value = false;
            } else {
              ElMessage({
                type: "warning",
                showClose: true,
                message: res.message,
                center: true,
              });
            }
          })
          .catch((err) => {
            console.log(err);
            ElMessage({
              type: "error",
              showClose: true,
              message: "添加失败",
              center: true,
            });
          });
      } else {
        // let publicKey =
        //   "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMOcPB06u5yKyQsPjfVWiWgbEIrd14kiXNNihciaVKb6HnkQvq7zpQuZ80WEX94spnUMI3iOAl/GmIvHrpGwcbB4hJbznm+PajiwnUSPuCCXA68YJF640cJKb/8KeM7WVz69OFkIEPHhVxOy4FFF5QWe/kt6zOZ19HmE+ak+5x/QIDAQAB";
        // let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
        // encryptor.setPublicKey(publicKey); // 设置公钥
        // let rsaPassWord = encryptor.encrypt(ruleForm.date2); // 对密码进行加密

        let data = {
          phone: ruleForm.phone,
          username: ruleForm.date1,
          adminType: ruleForm.resource,
          sex: ruleForm.region,
          name: ruleForm.name,
          id: ruleForm.id,
          createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };
        if (data.sex == "女") {
          data.sex = 0;
        } else if (data.sex == "男") {
          data.sex = 1;
        }
        if (data.adminType == "超级管理员") {
          data.adminType = 1;
        } else if (data.adminType == "管理员") {
          data.adminType = 2;
        }
        adminApi
          .adminUpdate(data)
          .then((res) => {
            console.log(res);
            if (res.success) {
              ElMessage({
                type: "success",
                showClose: true,
                message: res.message,
                center: true,
              });
              getList(currentPage.value);
              ruleFormRef.value.resetFields();
              centerDialogVisible.value = false;
            } else {
              ElMessage({
                type: "warning",
                showClose: true,
                message: res.message,
                center: true,
              });
            }
          })
          .catch((err) => {
            console.log(err);
            ElMessage({
              type: "error",
              showClose: true,
              message: res.message,
              center: true,
            });
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 删除按钮
const handleDel = (row) => {
  console.log("click");
  ElMessageBox.confirm("此操作将永久删除所选中的IP，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let idIP = [];
      selectData.list.forEach((item) => {
        idIP.push(item.id);
      });
      console.log(idIP);
      adminApi
        .adminDel([row.id])
        .then((res) => {
          console.log(tableData.list.length);
          if (tableData.list.length == 1 && currentPage.value != 1) {
            currentPage.value = currentPage.value - 1;
          }
          ElMessage({
            type: "success",
            showClose: true,
            message: "删除成功",
            center: true,
          });
          getList(currentPage.value);
        })
        .catch((err) => {
          console.log(err);
          ElMessage({
            type: "warning",
            showClose: true,
            message: "删除失败",
            center: true,
          });
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 导出按钮
const downLoad = lodash.debounce(() => {
  let startTime = searchData.input5[0];
  let endTime = searchData.input5[1];
  let data = {
    name: searchData.input1,
    username: searchData.input2,
    phone: searchData.input3,
    adminType: searchData.input4,
    startTime,
    endTime,
  };
  adminApi
    .download(data)
    .then((res) => {
      let name = "用户管理列表";
      var content = res;
      // var data = new Blob([content], { type: "application/octet-stream;charset=utf-8" });
      var data = new Blob([content], { type: "application/vnd.ms-excel;charset=utf-8" });
      var downloadUrl = window.URL.createObjectURL(data);
      var anchor = document.createElement("a");
      anchor.href = downloadUrl;
      anchor.download = name + ".xlsx";
      anchor.click();
      window.URL.revokeObjectURL(data);
      console.log(res);
      ElMessage({
        type: "success",
        showClose: true,
        message: "导出成功",
        center: true,
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "error",
        showClose: true,
        message: "导出失败",
        center: true,
      });
    });
}, 300);
// 导入按钮
const importExcel = () => {
  importByExcelDialog.value = true;
};

// 上传文件
const changeUpload = (file, fileList) => {
  // fileList.value = [];
  if (file) {
    fileList.value = file;
  }
  active.value = 2;
};
// 移出文件前的回调
const beforeRemove = (file) => {
  console.log(file);
  active.value = 1;
};

// 步骤条功能
const next = async () => {
  console.log(fileList.value);
  let formData = new FormData();
  formData.append("file", fileList.value[0].raw);
  let res = await axios({
    method: "post",
    url: "/video/transcoding/videoAdmin/importByExcel",
    data: formData,
    headers: {
      admin_token: sessionStorage.getItem("admin_token"),
    },
  });
  // console.log(res);
  if (res.data.success) {
    setTimeout(() => {
      importByExcelDialog.value = false;
      fileList.value = "";
      active.value = 1;
    }, 1000);
    ElMessage({
      type: "success",
      showClose: true,
      message: "导入成功",
      center: true,
    });
    active.value = 3;
    currentPage.value = 1;
    getList(1);
  } else {
    ElMessage({
      type: "warning",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 分页
const handleCurrentChange = (value) => {
  currentPage.value = value;
  getList(value);
};
onBeforeMount(() => {
  getList(1);
});
</script>

<style scoped lang="scss">
.content-box {
  width: 97.5%;
  height: 90%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;

  .left {
    width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
  }
  .middle {
    width: 96%;
    margin: 0 auto;

    color: #000;
    border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
    }
    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }
    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }
    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }
    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }
    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }
  .footer {
    width: 96%;
    height: 562px;
    margin: 20px auto 30px;
    .el-table--fit {
      height: 100%;

      :deep(.el-table__row) {
        height: 40px;
      }
      :deep(.el-table__row td) {
        padding: 0;
      }
      // 输出链接弹窗样式
      :deep(.link .el-dialog__header) {
        text-align: left;
        font-size: 20px;
        font-weight: 600;
      }
      :deep(.link .el-dialog__body) {
        padding: 10px 20px;
        height: 100px;
        margin-bottom: 10px;
      }
      .link {
        .linkcontent {
          text-align: left;
          height: 100px;
          border: 1px solid #ccc;
          p {
            margin: 5px 10px;
          }
        }
      }

      :deep(.playVideo .el-dialog__header) {
        text-align: left;
        font-size: 20px;
        font-weight: 600;
        background-color: #ccc;
        margin-right: 0;
      }
      :deep(.playVideo .el-dialog__body) {
        height: 600px;
      }

      .el-button--primary {
        margin-left: 5px;
      }
      :deep(.el-table__body .even) {
        background-color: #fff;
      }
      :deep(.el-table__body .odd) {
        background-color: #f5f8fc;
      }
    }
  }
  .el-pagination {
    // width: 1600px;
    width: 96%;
    margin: 0 auto 18px;
    justify-content: flex-end;
    :deep(.el-pagination__total) {
      color: #000;
    }
    :deep(.el-pagination__goto) {
      color: #000;
    }
    :deep(.el-pagination__classifier) {
      color: #000;
    }

    :deep(.el-pager li) {
      margin: 0 3px;
    }
    :deep(.btn-prev) {
      margin-right: 3px;
    }
    :deep(.btn-next) {
      margin-left: 3px;
    }
  }
}
.el-input {
  width: 192px;
}
</style>
