<template>
  <div class="echo_flex">
    <!-- 左 -->
    <div class="divborder leftDiv">
      <!-- 产线层级树 -->
      <Tree
        ref="tree"
        class="treeDiv"
        :data="treeList"
        @on-select-change="getList"
      >
      </Tree>
    </div>
    <!-- 右 -->
    <div class="rightDiv">
      <!-- 查询条件 -->
      <div class="divborder newSearchDiv">
        <div class="filter">
          <label>时间范围：</label>
          <DatePicker
            class="searchInput middleWidth"
            type="daterange"
            format="yyyy-MM-dd"
            v-model="searchDate"
          >
          </DatePicker>
        </div>
        <div class="filter">
          <label>更新类型：</label>
          <Select class="searchSelect" v-model="searchObj.type">
            <Option :value="1">新增</Option>
            <Option :value="2">修改</Option>
            <Option :value="3">删除</Option>
          </Select>
        </div>
        <div class="filter">
          <label>程序号：</label>
          <Input v-model="searchObj.programcode" class="searchInput" />
        </div>
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="tosearch()"
        >
          查询
        </Button>
      </div>
      <!-- 数据展示 -->
      <div class="divborder newTableDiv">
        <!-- 表格 -->
        <Table
          highlight-row
          class="tableClass"
          :data="tableData"
          :columns="columns"
          @on-current-change="handleRowChange"
        >
        </Table>
        <!-- 分页器 -->
        <div class="pageDiv">
          <div class="pageDirection">
            <Page
              show-elevator
              show-sizer
              show-total
              :total="total"
              :current.sync="page"
              :page-size="pagesize"
              :page-size-opts="[10, 20, 30, 40, 100]"
              @on-change="changePage"
              @on-page-size-change="handlePageSize"
            >
            </Page>
          </div>
        </div>
      </div>
      <div class="expand_box" v-show="show == true">
        <!-- 未更新 -->
        <div class="echo_border" v-show="update == false">
          <div class="echo_btn0">
            <Button type="primary" @click="download(0)">下载</Button>
          </div>
          <div class="echo_ih">
            <div v-html="infohtml"></div>
          </div>
        </div>
        <!-- 更新 -->
        <div v-show="update == true">
          <div class="buttonbox">
            <Button type="primary" @click="download(1)">下载</Button>
            <Button type="primary" @click="diff()">对比</Button>
            <Button type="primary" @click="download(2)">下载</Button>
          </div>
          <div class="echo_flex" v-show="diffshow == false">
            <div class="box echo_bn" v-html="infoHtml1"></div>
            <div class="box" v-html="infoHtml2"></div>
          </div>
          <div class="diffbox" v-show="diffshow == true">
            <code-diff
              :old-string="oldStr"
              :new-string="newStr"
              :context="1000"
              outputFormat="side-by-side"
              :isShowNoChange="true"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import CodeDiff from "vue-code-diff";

export default {
  components: { CodeDiff },
  data() {
    return {
      oldStr: "",
      newStr: "",
      // 查询条件--时间范围
      searchDate: [
        moment(new Date().getTime() - 3600 * 1000 * 24 * 6).format(
          "YYYY-MM-DD "
        ),
        moment(new Date().getTime()).format("YYYY-MM-DD "),
      ],
      searchObj: {
        type: 0,
        programcode: "",
      },

      total: 0,
      page: 1,
      pagesize: 10,

      treenode: [],

      tableData: [],
      columns: [
        {
          title: "序号",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 75,
          align: "center",
        },
        {
          title: "设备名称",
          key: "machine_name",
          align: "center",
        },
        {
          title: "程序号",
          key: "program_number",
          align: "center",
        },
        {
          title: "产品图纸号",
          key: "productcode",
          align: "center",
        },
        {
          title: "产品名称",
          key: "productname",
          align: "center",
          minWidth: 100,
        },
        {
          title: "更新时间",
          key: "time",
          align: "center",
        },
        {
          title: "更新类型",
          key: "type_str",
          align: "center",
        },
      ],

      row: {},

      content: "",
      infohtml: "",
      content1: "",
      content2: "",
      infoHtml1: "",
      infoHtml2: "",

      diffshow: false,
      diffhtml: "",

      update: false,
      show: false,
    };
  },
  computed: {
    treeList() {
      return this.$store.state.app.tree;
    },
  },
  mounted() {
    // 获取树形图数据
    this.$store.dispatch("getTree");

    // 格式化表格样式
    this.columns = this.$time.initTableTitle(this.columns);
  },
  methods: {
    // 监听树结构当前选中节点
    getList() {
      let node = this.$refs.tree.getSelectedNodes();
      if (node.length) {
        this.treenode = node[0];
        this.tosearch();
      }
    },
    // 查询之前
    tosearch() {
      this.page = 1;
      this.pagesize = 10;
      this.search();
    },
    // 查询
    search() {
      if (!this.treenode || !this.treenode.value) {
        this.$Message.error(this.$t(700071));
        return false;
      }
      if (this.treenode.children.length > 0) {
        this.$Message.error(this.$t(100128));
        return false;
      }
      this.searchObj.starttime = moment(this.searchDate[0]).format(
        "YYYY-MM-DD"
      );
      this.searchObj.endtime = moment(this.searchDate[1]).format("YYYY-MM-DD");
      let params = {
        sectionid: this.treenode.value,
        type: this.searchObj.type,
        programcode: this.searchObj.programcode,
        starttime: this.searchObj.starttime,
        endtime: this.searchObj.endtime,
        page: this.page,
        pagesize: this.pagesize,
      };
      this.axios
        .request({
          url: "/dnc/DncContrast/GetPgMonitorlists",
          params,
          method: "get",
        })
        .then((res) => {
          this.show = false;
          if (res.data.ret === 1) {
            if (res.data.data && res.data.data.length > 0) {
              this.total = res.data.total;

              let arr = [];
              let type_str = "";

              res.data.data.forEach((item) => {
                if (item) {
                  if (item.type === "add") {
                    type_str = this.$t(700147);
                  } else if (item.type === "update") {
                    type_str = this.$t(1003);
                  } else if (item.type === "delete") {
                    type_str = this.$t(1004);
                  }
                  arr.push({
                    id: item.id,
                    program_number: item.program_number,
                    oldcode: item.program_number,
                    machine_name: item.machine_name,
                    productcode: item.productcode,
                    productname: item.productname,
                    time: item.time,
                    machine_id: item.machine_id,
                    type: item.type,
                    type_str: type_str,
                    document: item.document,
                    lastContext: item.lastContext,
                  });
                }
              });
              this.tableData = arr;
            } else {
              this.tableData = [];
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 监听表格当前选中行
    handleRowChange(currentRow) {
      this.row = currentRow;
      this.getContent();
      this.show = true;
      this.diffshow = false;
    },
    // 获取程序内容
    getContent() {
      this.update = false;
      if (this.row.type == "add" || this.row.type == "delete") {
        this.content = this.row.document;
        this.renderContent(this.content, 0);
      } else if (this.row.type == "update") {
        this.content1 = this.row.document;
        this.content2 = this.row.lastContext;
        this.renderContent(this.content1, 1);
        this.renderContent(this.content2, 2);
        this.update = true;
      }
    },
    // 渲染文本
    renderContent(content, i) {
      var infoArray = content.split("\n");
      var html = "";

      if (infoArray.length > 0) {
        infoArray.forEach((ele, i) => {
          html +=
            '<p><span style="background:#ddd;display:inline-block;text-align:center;padding:0px 5px;min-width:30px;">' +
            (i + 1) +
            "</span><span>" +
            ele +
            "</span></p>";
        });
      }
      if (i == 0) {
        this.infohtml = html;
      }
      if (i == 1) {
        this.infoHtml1 = html;
      }
      if (i == 2) {
        this.infoHtml2 = html;
      }
    },
    // 点击对比
    diff() {
      if (!this.content1 || !this.content2) {
        this.$Message.error(this.$t(700149));
        return false;
      }

      let left = this.content1;
      let right = this.content2;

      left = left.replace(/\r/g, "\n");
      right = right.replace(/\r/g, "\n");
      left = left.replace(/\n+/g, "\n");
      right = right.replace(/\n+/g, "\n");

      this.oldStr = left;
      this.newStr = right;

      this.diffshow = true;
    },
    // 点击下载
    download(a) {
      let filename, content;
      if (a == 0) {
        filename = this.row.oldcode + ".txt";
        content = this.content.replace(/\n/g, "\r\n");
      }
      if (a == 1) {
        filename = this.row.oldcode + ".txt";
        content = this.content1.replace(/\n/g, "\r\n");
      }
      if (a == 2) {
        filename = this.row.oldcode + ".txt";
        content = this.content2.replace(/\n/g, "\r\n");
      }
      var eleLink = document.createElement("a");
      eleLink.download = filename;
      eleLink.style.display = "none";
      // 字符内容转变成blob地址
      var blob = new Blob([content]);
      eleLink.href = URL.createObjectURL(blob);
      // 触发点击
      document.body.appendChild(eleLink);
      eleLink.click();
      // 然后移除
      document.body.removeChild(eleLink);
    },
    // 监听页码变化
    changePage(v) {
      this.page = v;
      this.search();
    },
    // 监听页距变化
    handlePageSize(v) {
      this.pagesize = v;
      this.search();
    },
  },
};
</script>

<style scoped>
.echo_bn {
  border-right: none;
}
.echo_ih {
  border-top: 1px solid black;
  overflow: auto;
  width: 100%;
  height: 200px;
  margin-top: 5px;
}
.echo_btn0 {
  text-align: center;
  padding: 5px;
  height: 36px;
}
.echo_border {
  border: 1px solid black;
}
.expand_box {
  width: 100%;
  height: 200px;
}
.echo_flex {
  display: flex;
}
.box {
  width: 50%;
  height: 200px;
  border: 1px solid #000;
  overflow: auto;
}
.diffbox {
  width: 100%;
  height: 200px;
  border: 1px solid #000;
  overflow: auto;
}
.buttonbox {
  width: 100%;
  height: 53px;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border: 1px solid #000;
  border-bottom: none;
  margin-top: 20px;
}
</style>
