<template>
  <div class="flex">
    <div class="divborder leftDiv">
      <Tree
        class="treeDiv"
        :data="treeList"
        ref="tree"
        @on-select-change="getList()"
      >
      </Tree>
    </div>
    <div class="rightDiv">
      <div class="divborder newSearchDiv">
        <div class="filter">
          <label>程序号：</label>
          <Input v-model="programcode" class="searchInput" />
        </div>
        <div class="searchBtn">
          <Button
            type="primary"
            class="twoWord"
            icon="ios-search"
            @click="tosearch()"
            >查询</Button
          >
          <Button
            type="primary"
            class="twoWord intervalRight"
            icon="md-download"
            @click="download"
            v-show="downloadpg"
            >下载</Button
          >
          <Button
            type="primary"
            class="fourWord"
            icon="ios-search"
            v-show="getpg"
            @click="receiveProgram"
            >接收程序</Button
          >
          <!-- <Button
            type="primary"
            class="twoWord intervalRight"
            icon="md-download"
            @click="returnProgram"
            >回传</Button
          > -->
          <span>{{ msg }}</span>
        </div>
      </div>
      <div class="divborder newTableDiv">
        <Table
          highlight-row
          class="tableClass"
          :data="data1"
          :columns="columns"
          :loading="loading"
          @on-selection-change="handleSelect"
          @on-row-click="onExpand"
        >
        </Table>
        <div class="pageDiv">
          <div class="pageDirection">
            <Page
              show-elevator
              show-sizer
              show-total
              :total="total"
              :current.sync="page"
              :page-size.sync="pagesize"
              :page-size-opts="[10, 20, 30, 40, 100]"
              @on-change="handlePage"
              @on-page-size-change="handlePageSize"
            >
            </Page>
          </div>
        </div>
      </div>
    </div>
    <Modal
      class="newModalClass"
      title="接收程序"
      v-model="modal"
      :styles="{ width: '600px' }"
    >
      <div
        class="modal_body"
        style="
          width: 500px !important;
          padding: 0;
          height: 400px !important;
          overflow: auto;
        "
      >
        <div v-html="infoHtml"></div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="cancle">取消</Button>
        <Button type="primary" size="large" @click="download2()">下载</Button>
      </div>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </Modal>
    <Modal
      class="newModalClass"
      title="回传程序"
      v-model="returnmodal"
      :styles="{ width: '600px' }"
    >
      <div class="filter">
        <label>路卡号：</label>
        <Select
          v-model="gateno"
          label-in-value
          filterable
          clearable
          remote
          :remote-method="remoteMethod"
          :loading="loading1"
          class="searchSelect"
        >
          <Option
            v-for="item in gatelist"
            :value="item.toll_gate_code"
            :key="item.toll_gate_code"
          >
            {{ item.toll_gate_code }}&nbsp;产品：{{
              item.productid
            }}&nbsp;工序：{{ item.process_code }}</Option
          >
        </Select>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="cancle">取消</Button>
        <Button type="primary" size="large" @click="returnCommit()"
          >确认回传</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import axios from "@/libs/api.request";

export default {
  data() {
    return {
      spinShow: false,
      programcode: "",
      cid: "",
      total: 0,
      page: 1,
      pagesize: 10,
      data1: [],
      obj: {},
      columns: [
        {
          type: "expand",
          width: 40,
          render: (h, params) => {
            var newArr = [];
            if (
              this.content !== null &&
              this.content !== undefined &&
              this.content !== ""
            ) {
              var infoArray = this.content.split("\n");
              infoArray.forEach((ele, i) => {
                newArr.push(
                  h("p", [
                    h(
                      "span",
                      {
                        style: {
                          background: "#ddd",
                          display: "inline-block",
                          "text-align": "center",
                          padding: "0px 5px",
                          "min-width": "30px",
                        },
                      },
                      i + 1
                    ),
                    h("span", ele),
                  ])
                );
              });
            }
            return h(
              "div",
              {
                style: {
                  border: "1px solid black",
                  overflow: "auto",
                  width: "99%",
                  height: "200px",
                },
              },
              [
                h(
                  "div",
                  {
                    style: {
                      "white-space": "nowrap",
                      "max-width": "1000px",
                    },
                  },
                  newArr
                  // this.infoHtml
                ),
              ]
            );
            // }
          },
        },
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: this.$t("1008"),
          key: "order",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 70,
          align: "center",
        },
        {
          title: "设备名称",
          key: "machine_name",
          align: "center",
          minWidth: 100,
        },
        {
          title: "程序号",
          key: "program_code",
          align: "center",
          minWidth: 100,
        },
        {
          title: "产品图纸号",
          key: "product_code",
          align: "center",
          minWidth: 100,
        },
        {
          title: "产品名称",
          key: "product_name",
          align: "center",
          minWidth: 100,
        },
        {
          title: "文件名",
          key: "filename",
          align: "center",
          minWidth: 100,
        },
        {
          title: "是否被修改",
          key: "updatestatus",
          align: "center",
          minWidth: 100,
        },
        {
          title: "修改时间",
          key: "updatetime",
          align: "center",
          minWidth: 100,
        },
        {
          title: "创建人",
          key: "createname",
          align: "center",
          minWidth: 100,
        },
        {
          title: "创建时间",
          key: "createtime",
          align: "center",
          minWidth: 100,
        },
        {
          title: "创建备注",
          key: "create_remark",
          align: "center",
          minWidth: 100,
        },
        {
          title: "审核人",
          key: "checkname",
          align: "center",
          minWidth: 100,
        },
        {
          title: "审核时间",
          key: "checktime",
          align: "center",
          minWidth: 100,
        },
        {
          title: "审核备注",
          key: "check_remark",
          align: "center",
          minWidth: 100,
        },
      ],
      attribute: 0,
      msg: "",
      getpg: true,
      downloadpg: true,
      selection: [],
      modal: false,
      returnmodal: false,
      infoHtml: "",
      filename: "",
      loading: false,
      loading1: false, // 远程搜索loading
      gateno: "",
      gatelist: [],
    };
  },
  computed: {
    treeList() {
      return this.$store.state.app.tree;
    },
  },
  created() {
    // 获取树形图数据
    this.$store.dispatch("getTree");
    // 格式化表格样式
    this.columns = this.$time.initTableTitle(this.columns);
  },
  methods: {
    // 获取id
    getList() {
      let node = this.$refs.tree.getSelectedNodes();
      if (node.length > 0) {
        if (node[0].children.length > 0) {
          this.$Message.error(this.$t(100128));
          return;
        } else {
          this.programcode = "";
          let id = node[0].value;
          this.getMachineInfo(id);
          this.cid = node[0].value;
        }
      }
    },
    getMachineInfo(id) {
      let data = {
        id: id,
      };
      this.request("/config/Machine/GetmachineidBySection", data, "get").then(
        (res) => {
          if (res.data.ret == 1) {
            let info = res.data.data;
            this.machineName = info.title;

            this.machineId = info.machine_id;
            this.downloadpg = true;
            this.getpg = false;

            this.data1 = [];
            this.msg = "";

            if (info.attribute == 1) {
              this.tosearch();
            } else if (info.attribute == 2) {
              this.downloadpg = false;
              this.getpg = true;
              this.msg = this.$t(700172);
            } else if (info.attribute == 3) {
              this.msg = this.$t(700173);
              this.tosearch();
            } else if (info.attribute == 4) {
              this.downloadpg = false;
              this.getpg = false;
              this.msg = this.$t(700174);
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        }
      );
    },
    tosearch() {
      this.page = 1;
      this.pagesize = 10;
      this.search();
    },
    // 查询
    search() {
      if (!this.cid) {
        this.$Message.error(this.$t(700071));
        return false;
      }
      var data = {
        sectionId: this.cid,
        programcode: this.programcode,
        page: this.page,
        pagesize: this.pagesize,
      };
      let url = "/dnc/DncUpDown/GetPgDownloadlists";
      this.request(url, data, "get").then((res) => {
        if (res.data.ret == 1) {
          this.total = res.data.total;
          let list = res.data.data;
          this.renderTable(list);
        } else {
          this.data1 = [];
        }
      });
    },
    renderTable(array) {
      let a = [];
      array.forEach((item, i) => {
        a.push({
          id: item.id,
          machine_id: item.machine_id,
          machine_name: item.machine_name,
          product_name: item.product_name,
          productid: item.productid,
          createname: item.createname,
          createtime: item.createtime,
          createmid: item.createmid,
          filename: item.filename,
          file_url: item.file_url,
          checkname: item.checkname,
          checktime: item.checktime,
          checkmid: item.checkmid,
          check_remark: item.check_remark,
          create_remark: item.create_remark,
          updatestatus: item.updatestatus == 1 ? "是" : "否",
          status: item.updatestatus,
          updatetime: item.updatetime,
          projectid: item.projectid,
          program_code: item.program_code,
          product_code: item.product_code,
          productid: item.productid,
          _expanded: false,
          _highlight: false,
          index: i,
        });
      });
      this.data1 = a;
    },
    cancle() {
      this.modal = false;
    },
    renderModal(arr) {
      let a = [];
      arr.forEach((item) => {
        a.push({
          id: item.id,
          productcode: item.product_code,
          productname: item.product_name,
          productid: item.productid,
          createname: item.createname,
          create_remark: item.create_remark,
          createmid: item.createmid,
          file_size: item.file_size,
          file_name: item.file_name,
          file_url: item.file_url,
          checkname: item.checkname,
          checkmid: item.checkmid,
          projectid: item.projectid,
          program_code: item.program_code,
          _expanded: false,
          _highlight: false,
        });
      });
      this.tableData = a;
    },
    // 接收程序
    receiveProgram() {
      if (this.cid == 0 || this.cid == "" || this.cid == undefined) {
        this.$Message.error(this.$t(700071));
        return false;
      }
      this.request(
        "/config/ProjectLevelSection/getNCMachineInfo",
        { sectionid: this.cid },
        "get"
      ).then((res) => {
        if (res.data.ret == 1) {
          this.modal = true;
          this.filename = res.data.data.title;
          // this.getText();
          this.getPargramText();
        } else {
          this.$Message.error(this.$t(res.data.msg));
        }
      });
      // this.content = "123\n123\n123\n123\n123\n123\n"
      // this.filename = '123';
      // this.renderText();
      // this.modal = true;
    },
    getPargramText() {
      let params = {
        sectionid: this.cid,
      };
      this.spinShow = true;
      this.axios
        .request({
          url: "/dnc/DncUpDown/getContent",
          params,
          method: "get",
        })
        .then((res) => {
          // var res = {
          //   data:{
          //     ret:1,
          //     data:'sfasdfa\nsdfasdfasdf\nasfsafdas\n'
          //   }
          // }
          this.spinShow = false;
          if (res.data.ret == 1 && res.data.data != "") {
            var infoArray = res.data.data.split("\n");
            var infohtml = "";
            if (infoArray.length > 0) {
              infoArray.forEach((ele, i) => {
                infohtml +=
                  '<p><span style="background:#ddd;display:inline-block;text-align:center;padding:0px 5px;min-width:30px;">' +
                  (i + 1) +
                  "</span><span>" +
                  ele +
                  "</span></p>";
              });
            }
            this.infoHtml = infohtml;
            this.content = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 获取程序内容
    getText() {
      let params = {
        machine_id: this.obj.machine_id,
        programcode: this.obj.program_code,
      };

      this.axios
        .request({
          url: "/dnc/DncUpDown/getProgramContent",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.loading = false;
            this.content = res.data.data;
            this.expand(this.obj.index);
          }
        });
    },
    renderText() {
      var infoArray = this.content.split("\n");
      var infohtml = "";
      if (infoArray.length > 0) {
        infoArray.forEach((ele, i) => {
          infohtml +=
            '<p><span style="background:#ddd;display:inline-block;text-align:center;padding:0px 5px;min-width:30px;">' +
            (i + 1) +
            "</span><span>" +
            ele +
            "</span></p>";
        });
      }
      this.infoHtml = infohtml;
      // $("#downloadid").attr("machineid", title);
    },
    handleSelect(data) {
      this.selection = data;
    },
    handlePageSize(value) {
      this.page = 1;
      this.pagesize = value;
      this.search();
    },
    handlePage(value) {
      this.page = value;
      this.search();
    },
    handleRowChange(currentRow, oldCurrentRow) {
      this.obj = currentRow;
      this.getText();
      if (this.content) {
        this.onExpand(this.obj.index);
      }
      // this.loading = true;
    },
    onExpand(row, index) {
      this.obj = row;

      if (this.data1[index]._expanded == true) {
        this.data1[index]._expanded = false;
      } else {
        this.loading = true;
        this.getText();
      }
    },
    expand(index) {
      this.data1.forEach((item, i) => {
        // 这个循环是为了每次只能展开一个，其他自动收起，不需要可以去掉
        i !== index ? (this.data1[i]._expanded = false) : "";
        i !== index ? (this.data1[i]._highlight = false) : "";
      });
      this.data1[index]._expanded = !this.data1[index]._expanded;
      this.data1[index]._highlight = true;
      this.data1.sort();
    },
    // 下载
    download() {
      if (this.cid == 0 || this.cid == "" || this.cid == undefined) {
        this.$Message.error(this.$t(700071));
        return false;
      }
      if (this.selection.length == 0) {
        this.$Message.error("请选择数据");
        return false;
      }

      let data = {},
        arr = [];
      this.selection.forEach((ele) => {
        arr.push(ele.program_code);
      });
      data = {
        data: arr,
        sectionid: this.cid,
      };
      this.request("/dnc/DncUpDown/DownloadProgram", data, "post").then(
        (res) => {
          if (res.data.ret == 1) {
            window.location.href = this.axios.publicPath + res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        }
      );
    },
    download2() {
      let filename = this.filename + ".txt";
      this.funDownload(this.content, filename);
    },
    // 下载方法
    funDownload(content, filename) {
      // 创建隐藏的可下载链接
      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);
    },
    request(url, data, type) {
      if (type == "get") {
        return this.axios
          .request({
            url: url,
            params: data,
            method: type,
          })
          .then((res) => {
            return res;
          })
          .catch((error) => error);
      } else {
        return this.axios
          .request({
            url: url,
            data,
            method: type,
          })
          .then((res) => {
            return res;
          })
          .catch((error) => error);
      }
    },
    // 加载路卡编号
    loadGateNo() {
      var data = {
        gateno: 10,
        gateno: this.programcode,
      };
      let url = "/dnc/DNC/GetTollGate";
      this.request(url, data, "get").then((res) => {
        if (res.data.ret == 1) {
          this.total = res.data.total;
          this.gatelist = res.data.data;
        }
      });
    },
    // 回传程序
    returnProgram() {
      if (this.cid == 0 || this.cid == "" || this.cid == undefined) {
        this.$Message.error(this.$t(700071));
        return false;
      }
      if (this.selection.length == 0) {
        this.$Message.error("请选择数据");
        return false;
      }
      if (this.selection.length > 1) {
        this.$Message.error("回传数据只能单条数据回传");
        return false;
      }
      this.returnmodal = true;
    },
    // 确认回传
    returnCommit() {
      let data = {},
        arr = [];
      this.selection.forEach((ele) => {
        arr.push(ele.program_code);
      });
      var selobj = this.selection[0];
      data = {
        sectionid: this.cid,
        data: arr,
        gateNo: this.gateno, // 路卡
        program: selobj.program_code, // 程序号
        productName: selobj.product_code, // 图纸号
      };
      this.request("/dnc/DncPgCreate/ReturnProgram", data, "post").then(
        (res) => {
          if (res.data.ret == 1) {
            window.location.href = this.axios.publicPath + res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        }
      );
    },
    // 加载路卡编号
    remoteMethod(query) {
      // 远程搜索
      if (query !== "") {
        this.loading1 = true;
        setTimeout(() => {
          this.loading1 = false;
          this.iniproducts(query);
        }, 200);
      } else {
        this.iniproducts("");
      }
    },
    iniproducts(query) {
      var params = {
        gateno: query,
        count: 50,
      };
      let url = "/dnc/DNC/GetTollGate";
      this.request(url, params, "get").then((res) => {
        this.gatelist = res.data.data;
      });
    },
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}
</style>
