<template>
  <div class="activityBox">
    <div class="uploadForm">
      <div class="noteBox">
        <h3 class="lableBox">活动名称：</h3>
        <el-input
          class="noteClass"
          v-model="activityForm.title"
          placeholder="输入活动名称"
          @focus="inputfocus"
        ></el-input>
        <p class="redErr" v-if="titleFlag">*请输入活动名称</p>
      </div>
      <div class="upgradeBox">
        <h3 class="lableBox">装置列表：</h3>
        <el-input
          type="textarea"
          :rows="22"
          placeholder="请输入装置列表"
          v-model="activityForm.cmdidArr"
          @focus="textfocus"
        >
        </el-input>
        <p class="redErr" v-if="cmdidFlag">*请输入活动名称</p>
      </div>
      <el-button
        class="uploadBtn"
        size="small"
        type="primary"
        @click="submitUpload"
        >上传活动列表</el-button
      >
    </div>
    <div class="activityList">
      <el-table
        :data="activityData"
        style="width: 100%"
        border
        stripe
        height="calc(100% - 0px)"
        v-loading="activityloading"
      >
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column prop="title" label="活动名称"> </el-table-column>
        <el-table-column prop="termCount" label="装置数量">
          <template slot-scope="scope">
            {{ scope.row.termCount }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="path" label="文件路径"> </el-table-column> -->
        <el-table-column label="操作" width="300" class-name="editClass">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="handleEditClick(scope.row)"
              size="small"
              icon="el-icon-document"
              >修改</el-link
            >
            <el-link
              type="primary"
              @click="handleLookClick(scope.row)"
              size="small"
              icon="el-icon-document"
              >详情</el-link
            >
            <el-link
              type="danger"
              @click="handleDeleteClick(scope.row)"
              size="small"
              icon="el-icon-delete"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      class="termsDialog"
      :title="activityName"
      :visible.sync="termsShow"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-button class="exportBtn" type="primary" @click="handleExport"
        >导出活动列表</el-button
      >
      <el-table
        ref="activityTable"
        id="activityTable"
        :data="termsData"
        style="width: 100%"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        height="600px"
        v-loading="activityloading"
        @header-click="handleHeaderClick"
      >
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column prop="lineName" label="线路名称"> </el-table-column>
        <el-table-column prop="towerName" label="杆塔名称"> </el-table-column>
        <el-table-column prop="cmdid" label="装置编号">
          <template slot="header" slot-scope="scope">
            装置编号<el-tag
              type="success"
              style="cursor: pointer; margin-left: 8px"
              >复制列</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="protocol" label="规约">
          <template slot-scope="scope">
            {{ protocolMap[scope.row.protocol] }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="termsShow = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getActivityApi,addActiveApi,updActiveApi,delActiveApi } from "@/utils/api/index";
import htmlToExcel from "@/utils/htmlToExcel";
import { saveAs } from "file-saver";
import XLSX from "xlsx";
export default {
  name: "activity",
  components: {},
  data() {
    return {
      activityloading: true,
      activityData: [], //活动列表
      activityForm: {
        title: "",
        cmdidArr: "",
      },
      cmdObjects: [], // 用于存储转换后的对象数组  
      titleFlag: false, //title为空
      cmdidFlag: false, //cmdid为空
      termsShow: false,
      termsData: [],
      termsLoading: true,
      activityName: "",
      activityNameTitle: "",
      protocolMap: {
        65280: "国网I1",
        65296: "陕西",
        65281: "安徽",
        65282: "江苏",
        65283: "湖南",
        65284: "浙江",
        65285: "河南全景",
        65286: "河南郑州",
        65290: "河南统一视频v2020",
        65298:"宁夏",
        2:"南网"
      },
      ActibityId: "", //判断是否是修改
    };
  },
  computed: {},
  watch: {  
    'activityForm.cmdidArr': {  
      handler(newVal) {  
        // 每当 activityForm.cmdidArr 发生变化时，调用 convertToCmdObjects 方法  
        this.cmdObjects = this.convertToCmdObjects(newVal);  
      },  
      deep: false, // 不需要深度监听，因为我们直接监听的是字符串  
      immediate: false, // 不需要立即触发一次 handler 函数  
    },  
  }, 
  mounted() {
    this.getactivityList();
  },
  methods: {
    convertToCmdObjects(text) {  
      // 去除文本首尾的空白字符，并按换行符分割成数组  
      const cmdids = text.trim().split(/\r?\n/);  
      // 映射每个 cmdid 到一个对象，并返回对象数组  
      return cmdids.map(cmdid => ({ cmdid }));  
    }, 
    async handleHeaderClick(column) {
      console.log(column);
      // 获取当前列的数据字段名
      const dataField = column.property;
      // 获取当前列的所有数据值
      const columnData = this.termsData.map((row) => row[dataField]);
      console.log(`当前列数据字段：${dataField}`);
      console.log(`当前列数据值：${columnData}`);
      this.copyToClipboard(columnData.join("\n"));
      console.log(columnData);
      // this.activityForm.cmdidArr = columnData.join("\n");
      // this.activityForm.title = this.activityNameTitle;
      //this.termsShow = false;
    },
    copyToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        const successful = document.execCommand("copy");
        const msg = successful ? "成功复制到剪贴板" : "复制失败";
        console.log(msg);
        this.$message({
          duration: 1500,
          showClose: true,
          message: msg,
          type: "success",
        });
      } catch (err) {
        console.error("复制失败:", err);
      } finally {
        document.body.removeChild(textArea);
      }
    },
    //导出活动列表表格
    handleExport() {
      htmlToExcel.getExcel("#activityTable", "设备活动列表");
    },
    //获取活动列表
    getactivityList() {
      this.activityloading = true;
      this.activityData = [];
      getActivityApi()
        .then((res) => {
          console.log(res);
          this.activityData = res.data;
          this.activityloading = false;
        })
        .catch((err) => {});
    },
    
    //活动详情
    handleLookClick(row) {
      console.log(row)
      this.termsShow = true;
      this.termsLoading = true;
      this.termsData =  row.terms;
      this.activityNameTitle = row.title;
      this.activityName =
      row.title + "(" + row.terms.length + ")";
          this.termsData = row.terms;
     },
    //删除该活动
    handleDeleteClick(row) {
      console.log(row);
      delActiveApi({
        id: row.id,
      })
        .then((res) => {
          console.log(res);
          this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                duration: 1500,
                showClose: true,
                message: "文件删除成功",
                type: "success",
              });
              this.getactivityList();
            })
            .catch(() => {});
        })
        .catch((err) => {});
    },
    //title获取焦点时触发
    inputfocus() {
      this.titleFlag = false;
    },
    //text获取焦点时触发
    textfocus() {
      this.cmdidFlag = false;
    },
    //修改活动详情
    handleEditClick(row) {
      console.log(row);
      this.ActibityId = row.id;
      this.activityForm.title = row.title;
      const columnData = row.terms.map((item) => item.cmdid);
      this.activityForm.cmdidArr = columnData.join("\n");
    },
    //上传活动列表
    submitUpload() {
      if (this.activityForm.title == "") {
        this.titleFlag = true;
        return;
      }
      if (this.activityForm.cmdidArr == "") {
        this.cmdidFlag = true;
        return;
      }
      let actParams = {};
      if (this.ActibityId !== "") {
        //修改
        console.log(this.ActibityId);
        actParams = {
          id: this.ActibityId,
          title: this.activityForm.title,
          terms: this.cmdObjects,
        };
        updActiveApi(actParams)
        .then((res) => {
          console.log(res);
          this.getactivityList();
          this.activityForm.title = "";
          this.activityForm.cmdidArr = "";
          this.ActibityId = "";
        })
        .catch((err) => {});
      } else {
        //新增
        console.log(this.cmdObjects);  
        actParams = {
          title: this.activityForm.title,
          terms: this.cmdObjects, 
        };
        addActiveApi(actParams)
        .then((res) => {
          console.log(res);
          this.getactivityList();
          this.activityForm.title = "";
          this.activityForm.cmdidArr = "";
          this.ActibityId = "";
        })
        .catch((err) => {});
      }
    },
  },
};
</script>
<style lang="less">
.activityBox {
  height: calc(100% - 24px);
  width: calc(100% - 24px);
  padding: 12px;
  display: flex;
  .uploadForm {
    min-width: 300px;
    margin-right: 20px;

    .noteBox {
      margin-bottom: 16px;
      position: relative;
      .noteClass {
        width: 100%;
      }
      .lableBox {
        font-size: 14px;
        font-weight: normal;
        width: 78px;
        line-height: 32px;
      }
      .redErr {
        position: absolute;
        font-size: 12px;
        color: red;
      }
    }
    .upgradeBox {
      position: relative;
      .lableBox {
        font-size: 14px;
        font-weight: normal;
        width: 78px;
        line-height: 32px;
      }
      .redErr {
        position: absolute;
        font-size: 12px;
        color: red;
      }
    }
    .uploadBtn {
      margin-top: 16px;
      margin-left: auto;
      display: flex;
    }
  }

  .activityList {
    height: calc(100% - 0px);
    flex: 1;
    min-width: 0;
    .el-table {
      .el-table__cell {
        text-align: center;
      }
    }
  }
  .editClass {
    .el-link.el-link--primary {
      margin-right: 14px;
    }
  }
  .termsDialog {
    .el-dialog {
      margin-top: 0 !important;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .exportBtn {
      position: absolute;
      z-index: 1;
      top: 16px;
      right: 66px;
    }

    .el-dialog__body {
      padding: 12px;
    }
  }
}
.el-dialog__headerbtn {
  top: 18px;
  .el-dialog__close {
    font-size: 26px;
    &:hover {
      background: #e2e2e2;
    }
  }
}
</style>
