<script>
import axios from "axios";
import router from "@/router/index.js";
import Cookies from "js-cookie";
import { ElMessage } from "element-plus";
import CryptoJS from "crypto-js";
import Menu from "@/views/Menu.vue";

import { getConfigFileListService } from "@/api/file.js";
import { addConfigFileService } from "@/api/file.js";
import { deleteConfigFileService } from "@/api/file.js";
import { updateConfigFileService } from "@/api/file.js";

export default {
  data() {
    return {
      ip: "",
      tableData: [],
      search_id: 2002,
      ConfigFileUpdateForm: {},
      keyword: "",
      updateDialogVisible: false,
      addConfigFileVisible: false,
      ConfigFileCurrentPageData: [],
      pageSize: 10,
      currentPage: 1,
      upload_file: null, //文件上传
      file_md5: "", //文件上传的md5
      addForm: {
        file_name: "",
        file_path: "",
      },

      role: "",
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
        id: 2002,
        server: "gep.ljsea.top",
        keyword: "",
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getConfigFileList() {
      let result = {};
      try {
        //判断search_id是字符串还是数字
        let req = {
          token: this.tokenData.token,
          type: "all",
        };
        result = await getConfigFileListService(req);
      } catch (e) {
        console.log(e);
      }
      let data = result.data;
      if (data !== undefined && data !== null) {
        this.tableData = data;
      }
      this.currentPageData();
    },
    addConfigFileV() {
      this.addConfigFileVisible = true;
    },
    handleServerChange() {
      localStorage.setItem("config_file_server", this.tokenData.server);
      this.getConfigFileList();
    },
    async addConfigFile() {
      this.addDialogVisible = false;
      let result = {};
      try {
        let req = {
          token: this.tokenData.token,
          file_name: this.addForm.file_name,
          file_path: this.addForm.file_path,
        };
        result = await addConfigFileService(req);
        if (result.code == 0) {
          ElMessage.success("添加成功");
          this.getConfigFileList();
          this.addConfigFileVidibale = false;
        } else {
          //alert("添加失败");
          ElMessage.error("添加失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async deleteConfigFile(index) {
      // 是否删除
      let isDelete = confirm("是否删除?");
      if (!isDelete) {
        return;
      }
      // alert("删除 index: " + index);
      // return ;
      let is_delete_file = confirm("是否删除文件?");

      let result = {};
      try {
        let req = {
          token: this.tokenData.token,
          id: this.ConfigFileCurrentPageData[index].ID,
          del_file: is_delete_file,
        };
        result = await deleteConfigFileService(req);
        if (result.code == 0) {
          ElMessage.success("删除成功");
          this.getConfigFileList();
        } else {
          ElMessage.error("删除失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateConfigFile(index) {
      console.log("index:", index);
      let cf = this.ConfigFileCurrentPageData[index];
      let req = {
        token: this.tokenData.token,
        id: cf.ID,
        type: "one",
      };
      let result = await getConfigFileListService(req);
      let data = result.data;
      this.ConfigFileUpdateForm = data[0];
      this.updateDialogVisible = true;
    },
    handleAvatarFileUpload(e) {
      this.avatar_file = e.target.files[0];
      //判断文件类型是否为图片
      if (!this.avatar_file.type.startsWith("image/")) {
        ElMessage.error("请选择图片文件");
        this.avatar_file = null;
        return;
      }
      this.uploadAvatarFile();
    },
    readFileAndCalculateMD5() {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          const wordArray = CryptoJS.lib.WordArray.create(event.target.result);
          const md5Hash = CryptoJS.MD5(wordArray);
          const md5Str = md5Hash.toString(CryptoJS.enc.Hex);
          //console.log("onload: " + md5Str);
          this.file_md5 = md5Str;
          resolve(md5Str);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsArrayBuffer(this.avatar_file);
      });
    },
    async uploadFile() {
      if (this.avatar_file == null) {
        alert("请先选择要上传的文件");
        return;
      }

      try {
        let result = {};
        this.file_md5 = await this.readFileAndCalculateMD5(this.avatar_file);
        //console.log("md5:",this.file_md5);
        let md5_result = await GetFileInfoByMd5Service({
          md5: this.file_md5,
          token: this.tokenData.token,
          type: 1,
        });
        if (md5_result.code === 0) {
          result = md5_result;
        } else {
          let formData = new FormData();
          formData.append("file", this.avatar_file);
          //console.log("add file: " + this.file);
          formData.append("upload_type", "1");
          formData.append("md5", this.file_md5);
          formData.append("auth_type", "public");
          //console.log("formData:",formData);

          result = await UploadFileService(formData, this.tokenData.token);
          if (result.code !== 0) {
            ElMessage.error("上传文件失败，请稍后再试");
            return;
          }
        }
        let resp_data = result.data;

        //console.log("resp:",resp_data);
        let url = "https://gep.ljsea.top/tool/file/" + resp_data.FileStoreName;

        this.UserUpdateForm.avatar = url;
        //更新用户信息
        await this.updateUserInfo();
      } catch (error) {
        ElMessage.error("上传文件时出现网络错误，请稍后再试");
        console.error(error);
      }
    },
    async updateConfigFileInfo() {
      let result = {};
      try {
        let req = {
          token: this.tokenData.token,
          id: this.ConfigFileUpdateForm.id,
          content: this.ConfigFileUpdateForm.content,
        };
        for (var key in this.UserUpdateForm) {
          req[key] = this.UserUpdateForm[key];
        }
        result = await updateConfigFileService(req);
        if (result.code === 0) {
          ElMessage.success("更新成功");
          this.updateDialogVisible = false;
        } else {
          ElMessage.error("更新失败");
        }
      } catch (e) {
        console.log(e);
      }
    },

    onSubmit() {
      getConfigFileList();
    },
    currentPageData() {
      this.ConfigFileCurrentPageData = this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPageData();
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.currentPageData();
    },

    async displayMyInfo() {
      await this.getMyUserInfo(this.tokenData.user_id);
      this.updateDialogVisible = true;
    },
    async displayUserInfo(id) {
      await this.getMyUserInfo(id);
      this.updateDialogVisible = true;
    },

    handleMenuSelect(val) {
      router.push(val);
    },
    toVideoList() {
      router.push("/videoList");
    },
    // 修改条纹颜色
    tableRowClassName({ row, rowIndex }) {
      if (row.human === 1) {
        return {
          background: "#488aff",
        };
      } else {
        return "";
      }
    },
  },

  // 生命周期钩子会在组件生命周期的各个不同阶段被调用
  // 例如这个函数就会在组件挂载完成后被调用
  async mounted() {
    let now = new Date();
    if (localStorage.getItem("token") === null) {
      router.push("/login");
    }
    await this.getConfigFileList();
    //await this.getMyUserInfo(localStorage.getItem("userId"));
  },
};
</script>

<template>
  <div>
    <Menu></Menu>
    <el-container style="height: 700px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)"
        >文件</el-header
      >
      <el-container>
        <el-main>
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-form-item>
              <el-dialog
                v-model="updateDialogVisible"
                title="编辑配置文件"
                width="60%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="updateFormRef"
                  :model="ConfigFileUpdateForm"
                  :rules="UserUpdateFormRules"
                  label-width="70px"
                >
                  <!-- row -->
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="ID">
                        <el-input
                          v-model="ConfigFileUpdateForm.id"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="文件名称">
                        <el-input
                          v-model="ConfigFileUpdateForm.file_name"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="32">
                      <el-form-item label="文件路径">
                        <el-input
                          v-model="ConfigFileUpdateForm.file_path"
                          disabled
                          style="width: 512px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="文件内容" prop="device_status">
                        <el-input
                          type="textarea"
                          v-model="ConfigFileUpdateForm.content"
                          style="width: 600px"
                          :autosize="{ minRows: 4, maxRows: 8 }"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="updateConfigFileInfo()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>

            <!-- 表单 -->
            <el-form :inline="true" :model="tokenData" class="demo-form-inline">
              <el-form-item>
                <el-button
                  class="el-button--danger"
                  type="primary"
                  @click="getConfigFileList()"
                  >查询</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button
                  class="el-button--danger"
                  type="primary"
                  @click="addConfigFileV()"
                  >添加配置文件</el-button
                >
              </el-form-item>
              <!-- 选择服务器 -->
              <el-form-item>
                <el-select
                  v-model="tokenData.server"
                  @change="handleServerChange"
                >
                  <el-option label="gep.ljsea.top" value="gep.ljsea.top"
                    >gep.ljsea.xyz</el-option
                  >
                  <el-option label="tx.ljsea.top" value="tx.ljsea.top"
                    >tx.ljsea.top</el-option
                  >
                </el-select>
              </el-form-item>
            </el-form>
          </el-form>

          <el-dialog
            v-model="addConfigFileVisible"
            title="添加配置文件"
            width="50%"
            :before-close="handleClose"
          >
            <!-- 内容主体区域 -->
            <el-form
              ref="addFormRef"
              :model="addForm"
              :rules="addFormRules"
              label-width="70px"
            >
              <el-row>
                <el-form-item label="文件名称" prop="file_name">
                  <el-input
                    v-model="addForm.file_name"
                    autocomplete="on"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="文件路径" prop="file_path">
                  <el-input
                    v-model="addForm.file_path"
                    autocomplete="on"
                  ></el-input>
                </el-form-item>
              </el-row>
            </el-form>
            <!-- 底部区域 -->
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="addConfigFileVidibale = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="addConfigFile()"
                  >确定</el-button
                >
              </span>
            </template>
          </el-dialog>

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table :data="ConfigFileCurrentPageData" width="100%" border>
            :row-style="this.tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="FileName"
              label="文件名称"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="FilePath"
              label="文件路径"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="CreatedAt"
              label="创建时间"
              width="160"
            ></el-table-column>
            <el-table-column
              prop="UpdatedAt"
              label="上次更新"
              width="160"
            ></el-table-column>
            <el-table-column
              prop="AuthID"
              label="创建用户ID"
              width="100"
            ></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="updateConfigFile(scope.$index)"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="deleteConfigFile(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页条 -->
          <!-- Pagination 分页 -->
          <el-pagination
            background
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="10"
          ></el-pagination>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>