<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <div style="background: #fff; padding: 15px; margin-top: -15px">
        <el-row :gutter="24" style="display: flex">
          <el-select
            v-model="queryParams.railwayType"
            placeholder="请选择线路类型"
            style="width: 220px; padding-left: 10px"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in lineType"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
              clerable
            />
          </el-select>
          <el-input
            v-model="queryParams.railwayCode"
            placeholder="请输入线路编码"
            style="width: 220px; padding-left: 10px"
            @keyup.enter="handleQuery"
            clearable
          />
          <div
            class="search_btn"
            style="cursor: pointer; margin-left: 15px"
            @click="handleQuery"
          >
            查询
          </div>
          <div class="reset_btn" style="cursor: pointer" @click="reset">
            重置
          </div>
        </el-row>
      </div>

      <div style="margin-top: 15px; background: #fff; padding: 20px">
        <div class="cardHeadr">
          <!-- <div style="font-size: 18px" /> -->
          <div style="font-size: 18px; float: right; display: flex">
            <div @click="addEquipment" class="addBtn">
              <span class="icon font_family">&#xe604;</span>
              新增
            </div>
            <div @click="delLineArray" class="addBtn">
              <span class="icon font_family">&#xe607;</span>
              批量删除
            </div>
            <!-- <el-upload class="addBtn" action="#" :http-request="httpRequest" :show-file-list="false" :on-change="handleChange"
          :before-upload="beforeAvatarUpload" multiple
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
          <div class="addBtn" style="position: relative;top:-23px;left: -6px;" size="small">导入</div>
        </el-upload> -->
            <div @click="importLoadIn" class="addBtn">
              <span class="icon font_family">&#xe606;</span>
              导入
            </div>
            <div @click="uploadOut" class="addBtn">
              <span class="icon font_family">&#xe605;</span>
              导出
            </div>
            <div @click="downloadOut" class="addBtn" style="margin-right: 0">
              <span class="icon font_family">&#xe603;</span>
              下载模板
            </div>
          </div>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="railwayName" label="线路名称" align="center" />
          <el-table-column prop="railwayCode" label="线路编码" align="center" />
          <el-table-column
            prop="railwayTypeName"
            label="线路类型"
            align="center"
          />
          <el-table-column
            prop="milesRange"
            label="线路起止里程（km）"
            align="center"
          />
          
          <!-- <el-table-column prop="railwayName" label="线路名称" align="center" /> -->
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="text13" label="操作" align="center">
            <template slot-scope="scope">
              <div class="operateBtn">
                <div type="text" @click="editEquip(scope.row)">修改</div>
                <div type="text" @click="delLine(scope.row)">
                  <span>删除</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            :page-sizes="[10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
      <el-dialog
        v-if="dialogFormVisible"
        :title="title"
        :visible.sync="dialogFormVisible"
        @close="CloseIn"
        width="636px"
      >
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="线路编码" label-width="80px" prop="railwayCode">
            <el-input
              v-model="form.railwayCode"
              autocomplete="off"
              placeholder="请输入线路编码"
            />
          </el-form-item>
          <el-form-item label="线路名称" label-width="80px" prop="railwayName">
            <el-input
              v-model="form.railwayName"
              autocomplete="off"
              placeholder="请输入线路名称"
            />
          </el-form-item>
          <el-form-item
            label="线路类型"
            label-width="80px"
            prop="railwayTypeName"
          >
            <el-select
              v-model="form.railwayTypeName"
              style="width: 100%"
              placeholder="请选择线路类型"
            >
              <el-option
                v-for="item in lineType"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="起始里程" label-width="80px" prop="initialMileageBD">
            <el-input
              v-model="form.initialMileageBD"
              style="width: 99%"
              oninput="value=value.replace(/[^\d^\.]+/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"
              placeholder="请输入起始里程"
            >
              <template slot="append">km</template>
            </el-input>
          </el-form-item>
          <el-form-item label="结束里程" label-width="80px" prop="endMileageBD">
            <el-input
              v-model="form.endMileageBD"
              style="width: 99%"
              oninput="value=value.replace(/[^\d^\.]+/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"
              placeholder="请输入结束里程"
            >
              <template slot="append">km</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" label-width="80px" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              autocomplete="off"
              placeholder="请输入备注"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- <el-button class="search_btna" @click="submitForm">保存</el-button>
          <el-button class="reset_btna" @click="closeDia">取 消</el-button> -->
          <div class="search" @click="submitForm">保 存</div>
          <div class="reset" @click="closeDia">取 消</div>
        </div>
      </el-dialog>
      <!-- 上传 -->
      <el-dialog
        :visible.sync="uploadDialog"
        title="线路导入"
        width="620px"
        @close="showFalseUpload"
      >
        <el-upload
          ref="upload"
          class="upload-demo"
          style="text-align: center"
          drag
          action="#"
          :http-request="uploadHttpRequest"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="uploadFileList"
        >
          <!-- :headers="headers"  -->
          <!-- :on-success="handleFileSuccess" -->
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <!-- <div class="el-upload__tip">只能上传xls/xlsx文件,且不超过500kb</div> -->
        </el-upload>
        <div class="hxj">支持扩展名：.xlsx</div>
        <div class="hxj" style="margin: 0 -90px">
          请先下载模板，根据模板内容填写，再上传文件
          <span class="xzmba" @click="downloadOut">下载模板</span>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="search_btna" @click="uploadSubmitDialog"
            >确定</el-button
          >
          <el-button class="reset_btna" @click="showFalseUpload"
            >取 消</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
import {
  getLineDataList,
  getLineDataAddNewer,
  getLineDataLoadIn,
  getDownLoadList,
  getLineDataDelete,
  getLineDataUpdate,
  getLineDataLoadOut,
} from "@/api/account/line";
import { dataType} from "@/api/alarmList";

export default {
  name: "Cart",
  computed: {
    ...mapGetters(["name"]),
  },
  data() {
    var xlbm = (rule, value, callback) => {
      if (value === undefined || value === "") {
        callback(new Error("请输入线路编码"));
      } else if (value.length > 20) {
        callback(new Error("最多可输入20位"));
      } else {
        callback();
      }
    };
    var xlmc = (rule, value, callback) => {
      if (value === undefined || value === "") {
        callback(new Error("请输入线路名称"));
      } else if (value.length > 20) {
        callback(new Error("最多可输入20位"));
      } else {
        callback();
      }
    };
    var bbz = (rule, value, callback) => {
      if (value === undefined || value === "") {
        callback(new Error("请输入备注"));
      } else if (value.length > 200) {
        callback(new Error("最多可输入200位"));
      } else {
        callback();
      }
    };
    return {
      // 导入
      dataForm: {
        name: "",
        file: null,
      },
      rules: {
        railwayCode: [{ required: true, validator: xlbm, trigger: "blur" }],
        railwayName: [{ required: true, validator: xlmc, trigger: "blur" }],
        railwayTypeName: [
          { required: true, message: "请选择线路类型", trigger: "change" },
        ],
        initialMileageBD: [{ required: true, message: "请输入起始里程", trigger: "blur" }],
        endMileageBD: [{ required: true, message: "请输入结束里程", trigger: "blur" }],
        // remark: [{ required: true, validator: bbz, trigger: 'blur' }]
      },
      queryParams: {
        pageSize: "10",
        pageNum: "1",
        railwayType: "",
        railwayCode: "",
        railwayName: "",
        ids: [],
      },
      lineType: [
        // {
        //   value: "1",
        //   label: "高铁",
        // },
        // {
        //   value: "2",
        //   label: "普铁",
        // },
      ],
      // dataType: [
      //   {
      //     value: "1",
      //     label: "全部类型",
      //   },
      //   {
      //     value: "2",
      //     label: "类型一",
      //   },
      //   {
      //     value: "3",
      //     label: "类型二",
      //   },
      // ],
      getRespons: "",
      uploadDialog: false,
      tableData: [],
      dialogFormVisible: false,
      dataForm: {
        name: "",
        file: null,
      },
      form: {
        railwayCode: "",
        railwayName: "",
        railwayType: "",
        railwayTypeName: "",
        remark: "",
      },
      fileList: [],
      dialogType: "",
      title: "",
      ids: [],
      headers: { Authorization: getToken() },
      action: "#",
    };
  },
  created() {
    this.getLineaList();
    this.dataType("railway_type");
  },
  methods: {
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getLineaList();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getLineaList();
    },
    uploadFileList(file) {
      if (file.status === "ready") {
        this.fileList.push(file);
        if (this.fileList.length > 1) {
          this.fileList.splice(0, 1);
        }
      }
    },

    dataType(val) {
      dataType(val).then((res) => {
        console.log(res);
        if (val === "railway_type") {
          this.lineType = res.data;
        } 
      });
    },




    showFalseUpload() {
      (this.uploadDialog = false), (this.fileList = []);
    },
    uploadSubmitDialog() {
      const fileData = new FormData();
      fileData.append("file", this.fileList[0].raw);
      let isHttpRequest = this.fileList[0].raw.name.split(".");
      if (
        isHttpRequest[isHttpRequest.length - 1] == "xlsx" ||
        isHttpRequest[isHttpRequest.length - 1] == "xls"
      ) {
        getLineDataLoadIn(fileData).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "导入成功!",
            });
            this.uploadDialog = false;
            this.fileList = [];
            this.getLineaList();
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
            this.getLineaList();
            this.fileList = [];
          }
        });
      } else {
        this.$message({
          type: "error",
          message: "上传的文件只能是xls以及xlsx格式!",
        });
        this.fileList = [];
      }
    },
    // 导入
    httpRequest(param) {
      let formData = new FormData();
      formData.append("file", this.dataForm.file.raw);
      let configHeaders = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      getLineDataLoadIn(formData).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.getLineaList(this.data);
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    //验证文件类型
    beforeAvatarUpload(file) {
      const isXls =
        file.type === "application/vnd.ms-excel"
          ? true
          : file.type ===
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          ? true
          : false;
      if (!isXls) {
        alert("上传的文件只能是xls以及xlsx格式!");
      }
      return isXls;
    },
    // 判断文件个数
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    importLoadIn: function () {
      this.uploadDialog = true;
    },
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id);
      this.queryParams.ids = val.map((item) => item.id);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getLineaList();
    },
    reset() {
      this.queryParams = {};
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getLineaList();
    },
    getLineaList: function () {
      getLineDataList(this.queryParams).then((response) => {
        if (!this.queryParams.pageNum || !this.queryParams.pageSize) {
          this.queryParams.pageNum = 1;
          this.queryParams.pageSize = 10;
          getLineDataList(this.queryParams).then((res) => {
            this.tableData = res.data.records;
            this.total = res.data.total;
          });
        }
        if (
          response.data.records.length == 0 &&
          this.queryParams.pageNum != 1
        ) {
          this.queryParams.pageNum = this.queryParams.pageNum - 1;
          getLineDataList(this.queryParams).then((res) => {
            this.tableData = res.data.records;
            this.total = res.data.total;
          });
        }
        this.tableData = response.data.records;
        this.total = response.data.total;
      });
    },
    submitForm(form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.initialMileageBD>this.form.endMileageBD) {
            return this.$message({
                    message: "结束里程必须大于起始里程",
                    type: "error",
                  });
          }
          if (this.dialogType == 1) {
            this.form.railwayType = this.form.railwayTypeName;
            getLineDataAddNewer(this.form).then((response) => {
              if (response.code == 200) {
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
                this.getLineaList();
                this.dialogFormVisible = false;
                this.$refs["form"].resetFields();
                this.form = {};
              } else {
                this.$message({
                  message: response.msg,
                  type: "error",
                });
              }
            });
          } else if (this.dialogType == 2) {
            if (
              this.form.railwayTypeName == "高铁" ||
              this.form.railwayTypeName == "1"
            ) {
              this.form.railwayType = 1;
            } else if (
              this.form.railwayTypeName == "普铁" ||
              this.form.railwayTypeName == "2"
            ) {
              this.form.railwayType = 2;
            }
            getLineDataUpdate(this.form).then((response) => {
              if (response.code == 200) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.getLineaList();
                this.dialogFormVisible = false;
                this.$refs["form"].resetFields();
                this.form = {};
              } else {
                this.form.railwayType = this.form.railwayTypeName;
                //     if (this.form.railwayType ==1) {
                //   this.form.railwayType = '高铁'
                // } else if (this.form.railwayType == 2) {
                //   this.form.railwayType = '普铁'
                // }
                this.$message({
                  message: response.msg,
                  type: "error",
                });
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    delLineArray() {
      if (this.ids.length == 0) {
        this.$message({
          type: "error",
          message: "请先选择需要删除的数据",
        });
      } else {
        this.$confirm("确定要删除吗?", "信息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            getLineDataDelete(this.ids).then((res) => {
              if (res.code == 200) {
                this.getLineaList();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    delLine: function (row) {
      this.$confirm("确定要删除吗?", "信息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          getLineDataDelete(row.id).then((res) => {
            if (res.code == 200) {
              this.getLineaList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    closeDia() {
      this.dialogFormVisible = false;
      this.$refs["form"].resetFields();
      this.form = {};
    },
    CloseIn() {
      this.dialogFormVisible = false;
      this.$refs["form"].resetFields();
      this.form = {};
    },
    addEquipment: function () {
      this.dialogFormVisible = true;
      this.dialogType = 1;
      this.title = "新增线路";
    },
    editEquip: function (row) {
      this.form.railwayType = row.railwayTypeName;
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(row));
      if (this.form.railwayType == 1) {
        this.form.railwayType = "高铁";
      } else if (this.form.railwayType == 2) {
        this.form.railwayType = "普铁";
      }
      this.dialogType = 2;
      this.title = "修改线路信息";
    },
    uploadOut: function () {
      delete this.queryParams.pageNum;
      delete this.queryParams.pageSize;
      getLineDataLoadOut(this.queryParams).then((res) => {

        // this.exportFile(res, "线路台账信息");

        if (res.type == "application/json") {
          const reader = new FileReader(); 
          reader.readAsText(res, 'utf-8'); 
          reader.onload = function () {
            const msg = JSON.parse(reader.result);
            if(msg.code == 200){
              this.exportFile(res, "线路台账信息");
            } else{
              Message({
                type: 'error',
                message: msg.msg
              });
            }      
          }
        }else{
          this.exportFile(res, "线路台账信息");
        }
      })
    },
    exportFile: function (obj, name = Date.now(), suffix = "xlsx") {
      const url = window.URL.createObjectURL(
        new Blob([obj], { type: "application/vnd.ms-excel" })
      );
      const aDOM = document.createElement("a");
      aDOM.style.display = "none";
      aDOM.href = url;
      const fileName = name + "." + suffix;
      aDOM.setAttribute("download", fileName);
      document.body.appendChild(aDOM);
      aDOM.click();
      document.body.removeChild(aDOM);
    },
    downloadOut() {
      getDownLoadList({}).then((res) => {
        this.exportDownFile(res, "线路台账模板");
      });
    },
    exportDownFile: function (obj, name = Date.now(), suffix = "xlsx") {
      const url = window.URL.createObjectURL(
        new Blob([obj], { type: "application/vnd.ms-excel" })
      );
      const aDOM = document.createElement("a");
      aDOM.style.display = "none";
      aDOM.href = url;
      const fileName = name + "." + suffix;
      aDOM.setAttribute("download", fileName);
      document.body.appendChild(aDOM);
      aDOM.click();
      document.body.removeChild(aDOM);
    },
    deleteEquip: function () {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 45px 30px 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.cardHeadr {
  margin-top: -20px;
  display: flex;
  justify-content: space-between;
}

.search_btn {
  background-color: #2766dd;
  color: #f7f8fb;
  font-size: 14px;
  display: inline-block;
  width: 80px;
  height: 40px;
  border-radius: 2px;
  font-size: 14px;
  line-height: 40px;
  text-align: center;
  margin-top: 2px;
}

.search_btna {
  background-color: #2766dd;
  color: #f7f8fb;
  font-size: 14px;
  display: inline-block;
  width: 80px;
  height: 40px;
  border-radius: 2px;
  font-size: 14px;
  text-align: center;
}

.search_btn:hover {
  background-color: #4d85f4;
}

.reset_btn {
  color: #565656;
  border: 1px solid #d7d7d7;
  font-size: 14px;
  display: inline-block;
  width: 80px;
  height: 40px;
  border-radius: 2px;
  font-size: 14px;
  line-height: 40px;
  text-align: center;
  margin-left: 12px;
  margin-top: 2px;
}

.reset_btna {
  color: #565656;
  font-size: 14px;
  border: 1px solid #d7d7d7;
  width: 80px;
  height: 40px;
  border-radius: 2px;
  font-size: 14px;
  text-align: center;
  margin-left: 12px;
}

.reset_btn:hover {
  color: #1f9fff;
  border: 1px solid #1f9fff;
  background: none;
}

.addBtn {
  margin: 15px 20px 15px 0;
  cursor: pointer;
  text-align: center;
  width: 98px;
  height: 34px;
  border-radius: 2px;
  border: 1px solid #abc7fd;
  line-height: 34px;
  font-weight: 400;
  font-size: 14px;
  color: #2250c8;
  background-color: #e7eeff;
}

.addBtn:hover {
  color: #ffffff;
  background-color: #2250c8;
  border: 1px solid #2250c8;
}

.addBtn:active {
  color: #ffffff;
  background-color: #194da4;
  border: 1px solid #194da4;
}

.operateBtn {
  display: flex;
  justify-content: center;
  color: #2866dd;

  div {
    font-size: 14px;
    margin: 0 5px;
    cursor: pointer;
  }
}

::v-deep .el-dialog__body {
  padding: 20px 95px !important;
}

.xzmba {
  color: #2766dd;
  text-decoration: underline;
  cursor: pointer;
}

.hxj {
  text-align: center;
}

::v-deep .el-dialog__header {
  padding: 0 20px 10px !important;
}

::v-deep .el-upload__tip {
  margin-top: -17px;
}

::v-deep .el-upload-dragger .el-upload__text {
  margin-top: -10px;
}

.dialog-footer {
  text-align: center;
}

::v-deep .el-textarea .el-input__count {
  bottom: -40px;
}

::v-deep .el-input__icon {
  line-height: 47px;
}
::v-deep .el-select .el-input .el-select__caret {
  line-height: 20px !important;
}
</style>
