<template>
  <div>
    <div id="buttomContain">
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入关键词进行搜索"
          prefix-icon="el-icon-search"
          clearable
          size="small"
          style="width: 450px; margin-right: 15px;"
          @input="handleSearch"
        ></el-input>
      </div>
      <div class="search-container">
      <el-button id="buttonStyle" size="small" @click="addRow()"
        >添加任务</el-button
      >
      <el-button id="buttonStyle" size="small" @click="addXml()"
        >导入xml文件</el-button
      ></div>
    </div>
    <el-table
      id="tableStyle"
      :data="filteredData"
      :height="720"
      stripe
      border
      highlight-current-row
      header-cell-class-name="sinCl"
      :default-sort = "{prop: 'date', order: 'descending'}"
    >
      <el-table-column type="index" label="序号" width="60" ></el-table-column>
      <el-table-column
        prop="taskName"
        label="任务名称"
        sortable
        min-width="85"
      ></el-table-column>
      <el-table-column
        prop="databaseName"
        label="数据库名称"
        sortable
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="introduction"
        label="任务备注"
        sortable
        min-width="85"
      ></el-table-column>
      <el-table-column
        prop="operator"
        label="操作人员"
        sortable
        min-width="85"
      ></el-table-column>
      <el-table-column min-width="90" filterable label="是否已创库" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.hasCreateTables == true">已创库 </span>
          <span v-else>未创库</span>
        </template>
      </el-table-column>
      <el-table-column min-width="110" filterable label="是否及时审核">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isReviewerRestricted"
            active-color="#9DBBE7"
            @change="
              changeRestricted(scope.row.id, scope.row.isReviewerRestricted)
            "
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="90"
        sortable
      ></el-table-column>
      <el-table-column
        prop="modifyTime"
        label="修改时间"
        min-width="90"
        sortable
      ></el-table-column>

      <el-table-column width="290" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.hasCreateTables == true"
            type="text"
            size="small"
            @click.native.prevent="getRow(scope.row.id)"
            >查看任务</el-button
          >
          <el-button
            v-else
            @click.native.prevent="editRow(scope.row.id)"
            type="text"
            size="small"
            >编辑任务</el-button
          >
<!--          <el-button-->
<!--            @click.native.prevent="deleteRow(scope.$index)"-->
<!--            type="text"-->
<!--            size="small"-->
<!--            >删除任务</el-button-->
<!--          >-->
          <el-button
            @click.native.prevent="taskCreat(scope.row.id)"
            type="text"
            size="small"
            >任务创库</el-button
          >
          <el-button
            @click.native.prevent="downloadXml(scope.row.id)"
            type="text"
            size="small"
            >下载xml文件</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-dialogDrag
      class="taskDialog"
      title="新建任务"
      :visible.sync="DialogVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="138px">
        <el-form-item>
          <span slot="label"
            >任务名称
            <el-tooltip
              class="item"
              effect="dark"
              content="任务的中文名称"
              placement="top-end"
              ><i class="el-icon-info"></i
            ></el-tooltip>
          </span>
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item>
          <span slot="label"
            >数据库名称
            <el-tooltip
              class="item"
              effect="dark"
              content="任务在创建数据库时进行存储的数据库名称(英文)"
              placement="top-end"
              ><i class="el-icon-info"></i
            ></el-tooltip>
          </span>
          <el-input v-model="form.key"></el-input>
        </el-form-item>

        <el-form-item>
          <span slot="label"
            >任务上传时间
            <el-tooltip
              class="item"
              effect="dark"
              content="用于任务每日统计的截止日期，在该时间会统计每个用户的具体上传数量"
              placement="top-end"
              ><i class="el-icon-info"></i
            ></el-tooltip>
          </span>
          <el-time-picker
            v-model="form.taskUploadTime"
            value-format="HH:mm"
            format="HH:mm"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59',
            }"
          ></el-time-picker>
        </el-form-item>
        <el-form-item>
          <span slot="label"
            >任务备注
            <el-tooltip
              class="item"
              effect="dark"
              content="任务的描述，将在移动端进行展示"
              placement="top-end"
              ><i class="el-icon-info"></i
            ></el-tooltip>
          </span>
          <el-input v-model="form.introduction"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="small" @click="Upload()">确认</el-button>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      class="taskDialog"
      title="上传xml文件"
      :visible.sync="xmlDialogVisible"
      :close-on-click-modal="false"
    >
      <div style="text-align: left">
        <el-form ref="xmlform" :model="xmlform" label-width="138px">
          <el-form-item label="任务名称">
            <el-input v-model="xmlform.xmlname"></el-input>
          </el-form-item>
          <el-form-item label="数据库名称(英文)">
            <el-input v-model="xmlform.xmlkey"></el-input>
          </el-form-item>
          <el-form-item label="任务上传时间">
            <el-time-picker
              v-model="xmlform.xmltaskUploadTime"
              value-format="HH:mm"
              format="HH:mm"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59',
              }"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="任务备注">
            <el-input v-model="xmlform.introduction"></el-input>
          </el-form-item>
          <el-form-item label="xml文件">
            <el-upload
              accept=".xml"
              class="upload-demo"
              action="xml"
              ref="uploadfile"
              :auto-upload="false"
              :limit="1"
              :before-upload="beforeAvatarUpload"
              :on-change="getFile"
              :on-remove="removeFile"
            >
              <el-button size="small" type="primary" plain>选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" size="small" @click="UploadXml()"
        >确认</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import { store } from "@/components/vuex/store.js";
import { ajax as request } from "@/request.js";
import axios from "axios";
export default {
  data: function () {
    return {
      form: {
        name: "",
        key: "",
        taskUploadTime: "23:00",
        introduction: "",
      },
      DialogVisible: false,
      xmlDialogVisible: false,
      xmlform: {
        xmlname: "",
        xmlkey: "",
        xmltaskUploadTime: "23:00",
        introduction: "",
      },
      xmlData: [],
      fileList: [],
      searchKeyword: "", // 搜索关键词
      filteredData: [], // 过滤后的数据
    };
  },
  methods: {
    // 搜索处理方法
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.filteredData = [...this.xmlData];
      } else {
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredData = this.xmlData.filter(item => {
          return (
            (item.taskName && item.taskName.toLowerCase().includes(keyword)) ||
            (item.databaseName && item.databaseName.toLowerCase().includes(keyword)) ||
            (item.introduction && item.introduction.toLowerCase().includes(keyword))
          );
        });
      }
    },

    //读取数据库 初始化xml
    init() {
      let that = this;
      request({
        url: "/task/selectAll",
        method: "get",
      }).then(function (response) {
        if (response.data.success == true) {
          var jsondata = JSON.parse(response.data.data);
          that.xmlData = jsondata.data;
          that.filteredData = [...that.xmlData]; // 初始化过滤数据
          for (var i = 0; i < that.xmlData.length; i++) {
            if (that.xmlData[i].hasCreateTables == 1) {
              that.xmlData[i].hasCreateTables = true;
            } else {
              that.xmlData[i].hasCreateTables = false;
            }
            if (
              that.xmlData[i].isReviewerRestricted == 1 ||
              that.xmlData[i].isReviewerRestricted == true
            ) {
              that.xmlData[i].isReviewerRestricted = true;
            } else {
              that.xmlData[i].isReviewerRestricted = false;
            }
          }
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
    },
    // 修改方法参数，从index改为id
    changeRestricted(id, val) {
      let str = val == true ? "确认任务及时审核吗？" : "确认任务不需及时审核吗？";
      let result = val == true ? 1 : 0;
      let that = this;

      this.$confirm(str, "提示", {})
        .then(() => {
          request({
            url: "/task/setReviewerMode",
            method: "get",
            params: {
              taskId: id,
              isReviewerRestricted: result,
            },
          }).then(function (response) {
            if (response.data.success == true) {
              that.$message.success("设置成功");
              // 更新本地数据状态
              let row = that.xmlData.find(item => item.id === id);
              if (row) {
                row.isReviewerRestricted = val;
              }
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              that.$message.error("设置失败");
            }
          });
        })
        .catch(() => {});
    },
    addRow() {
      this.DialogVisible = true;
    },
    deleteRow(id) {
      this.$confirm("确认删除？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          let that = this;
          request({
            url: "/task/deleteTask",
            method: "post",
            params: { id: id },
          }).then(function (response) {
            var deleteresult = response.data.success;
            if (deleteresult == true) {
              that.$notify.success({
                title: "提示",
                message: "删除成功",
              });
              that.init();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              that.$notify.error({
                title: "提示",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {});
    },
    Upload() {
      if (this.form.name == "") {
        this.$alert("任务名不可为空", "提示", { confirmButtonText: "确定" });
        return;
      }
      if (this.form.key == "") {
        this.$alert("数据库名称不可为空", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.xmlData.length > 0) {
        for (var i = 0; i < this.xmlData.length; i++) {
          if (this.form.key == this.xmlData[i].databaseName) {
            this.$alert("数据库名称重复!", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }
        }
      }
      //存入time和num

      this.DialogVisible = false;
      // this.$store.dispatch('updateData',{config:''})
      sessionStorage.setItem("taskUploadTime", this.form.taskUploadTime);
      sessionStorage.setItem("introduction", this.form.introduction);

      sessionStorage.removeItem("Data");
      var config1 = {
        meta: {
          drawtool: {},
          position: [],
          basemap: [],
        },
        tables: [],
      };
      this.$store.dispatch("updateData", { config: config1 });
      sessionStorage.setItem("getInfo", "1");
      this.$router.push({
        path:
          "/home/" + this.form.name + "/" + this.form.key + "/-1" + "/drawtool",
      });
    },
    editRow(id) {
      let row = this.xmlData.find(item => item.id === id);
      if (!row) return;
      
      sessionStorage.removeItem("Data");
      sessionStorage.setItem("getInfo", "1");
      var config1 = {
        meta: {
          drawtool: {},
          position: [],
          basemap: [],
        },
        tables: [],
      };
      this.$store.dispatch("updateData", { config: config1 });
      this.$router.push({
        path: "/home/" + row.taskName + "/taskKey/" + id + "/drawtool",
      });
    },
    getRow(id) {
      let row = this.xmlData.find(item => item.id === id);
      if (!row) return;
      
      sessionStorage.removeItem("Data");
      sessionStorage.setItem("getInfo", "0");
      var config1 = {
        meta: {
          drawtool: {},
          position: [],
          basemap: [],
        },
        tables: [],
      };
      this.$store.dispatch("updateData", { config: config1 });
      this.$router.push({
        path: "/home/" + row.taskName + "/taskKey/" + id + "/drawtool",
      });
    },
    taskCreat(id) {
      this.$confirm("确认生成？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          let that = this;
          request({
            url: "/table/createTable",
            method: "post",
            params: { id: id },
          }).then(function (response) {
            if (response.data.success) {
              that.$notify.success({
                title: "提示",
                message: "创建成功",
              });
              that.init();
            } else if (response.data.message == "hasCreated") {
              that.$confirm("该任务已经创库，是否重新创库？", "提示", {
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                type: "warning",
              })
                .then(() => {
                  let that1 = that;
                  request({
                    url: "table/deleteAndCreateTable",
                    method: "post",
                    params: { id: id },
                  }).then(function (response) {
                    if (response.data.success) {
                      that1.$notify.success({
                        title: "提示",
                        message: "创建成功",
                      });
                      that1.init();
                    } else {
                      that1.$notify.error({
                        title: "提示",
                        message: "创建失败",
                      });
                    }
                  });
                })
                .catch(() => {});
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              that.$notify.error({
                title: "提示",
                message: "创建失败",
              });
            }
          });
        })
        .catch(() => {});
    },
    downloadXml(id) {
      let that = this;
      request({
        url: "/xml/downloading",
        method: "post",
        params: { id: id },
      }).then(function (response) {
        if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else if (response.status == 200) {
          let row = that.xmlData.find(item => item.id === id);
          if (row) {
            that.download(response.data, row.taskName);
          }
          that.$notify.success({
            title: "提示",
            message: "正在下载",
          });
        } else {
          that.$notify.error({
            title: "提示",
            message: response.data.message,
          });
        }
      });
    },
    download(data, name) {
      let fileName = name + ".xml";
      if ("download" in document.createElement("a")) {
        // 不是IE浏览器
        let blob = new Blob([data]);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
      } else {
        // IE 10+
        window.navigator.msSaveBlob(blob, fileName);
      }
    },
    addXml() {
      this.xmlDialogVisible = true;
      this.xmlform.xmlname = "";
      this.xmlform.xmlkey = "";
      this.xmlform.xmltaskUploadTime = "23:00";
      this.xmlform.introduction = "";
      this.fileList = [];
      if (this.$refs.uploadfile) {
        this.$refs.uploadfile.clearFiles();
      }
    },
    UploadXml() {
      let fd = new FormData();
      if (!this.xmlform.xmlname) {
        this.$alert("请输入任务名称！", "提示", { confirmButtonText: "确定" });
        return;
      }
      if (!this.xmlform.xmlkey) {
        that.$alert("请输入数据库名称！", "提示", {
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.xmlData.length > 0) {
        for (var i = 0; i < this.xmlData.length; i++) {
          if (this.xmlform.xmlkey == this.xmlData[i].databaseName) {
            this.$alert("数据库名称重复!", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }
        }
      }
      if (!this.fileList[0]) {
        this.$alert("请选择xml文件！", "提示", { confirmButtonText: "确定" });
        return;
      } else {
        fd.append("file", this.fileList[0]);
      }
      var userid = sessionStorage.getItem("access-id");
      var configString = {
        name: this.xmlform.xmlname,
        key: this.xmlform.xmlkey,
        id: userid,
        introduction: this.xmlform.introduction,
        taskUploadTime: this.xmlform.xmltaskUploadTime,
      };
      fd.append("configString", JSON.stringify(configString));
      let that = this;
      axios({
        url: "/task/createTaskByXmlFile",
        method: "post",
        data: fd,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(function (response) {
        if (response.data.success == true) {
          that.xmlDialogVisible = false;
          that.$notify.success({
            title: "提示",
            message: "任务上传成功！",
          });
          that.init();
        } else {
          if (response.data.status == 400) {
            that.$notify.error({
              title: "提示",
              message: response.data.message,
            });
          } else {
            that.$notify.error({
              title: "提示",
              message: "上传出错",
            });
          }
        }
      });
    },
    beforeAvatarUpload(file) {
      if (file.type != "xml") {
        this.$message.error("只能上传xml格式数据!");
        return false;
      }
      return true;
    },
    getFile(file) {
      this.fileList = [];
      this.fileList.push(file.raw);
    },
    removeFile() {
      this.fileList = [];
    },
  },
  mounted() {
    this.init();
  },
  store,
  watch: {
    "form.key": {
      handler() {
        let reg = /[^\w_]+$/;
        if (reg.test(this.form.key)) {
          this.$alert("数据库名称只可为字母、数字、下划线组合！", "提示", {
            confirmButtonText: "确定",
          });
        }
        this.form.key = this.form.key.replace(/[^\w_]/g, "");
      },
      deep: true,
    },
    "xmlform.xmlkey": {
      handler() {
        let reg = /[^\w_]+$/;
        if (reg.test(this.xmlform.xmlkey)) {
          this.$alert("数据库名称只可为字母、数字、下划线组合！", "提示", {
            confirmButtonText: "确定",
          });
        }
        this.xmlform.xmlkey = this.xmlform.xmlkey.replace(/[^\w_]/g, "");
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
#buttomContain {
  right: 25px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: space-between; /* 让搜索容器和按钮分别靠左和靠右 */
  width: calc(100% - 50px); /* 设置容器宽度，减去左右边距 */
}

.search-container {
  /* 移除右边距，让搜索容器靠左 */
}

#tableStyle {
  top: 40px;
  margin-bottom: 30px;
}
</style>
