<template>
  <div>
    <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="searchBtn">
            <Button
              type="primary"
              class="twoWord"
              icon="ios-search"
              @click="download()"
            >
              下载
            </Button>
            <Button
              type="primary"
              class="fourWord"
              icon="md-cloud-upload"
              @click="upload()"
            >
              上传程序
            </Button>
          </div>
          <p v-show="state == 4">{{ tipsmsg }}</p>
          <div class="flex echo_flex">
            <div class="tips">程序上传历史记录：</div>
            <div class="filter">
              <label>时间范围：</label>
              <DatePicker
                type="daterange"
                format="yyyy-MM-dd"
                clearable
                v-model="searchDate"
                class="searchInput middleWidth"
                placement="top-end"
              >
              </DatePicker>
              <div class="searchBtn echo_btn">
                <Button
                  type="primary"
                  class="twoWord"
                  icon="ios-search"
                  @click="tosearch()"
                >
                  查询
                </Button>
              </div>
            </div>
          </div>
        </div>
        <div class="divborder newTableDiv">
          <Table
            highlight-row
            class="tableClass"
            :data="data1"
            :columns="columns"
            @on-current-change="handleRowChange1"
            @on-row-click="onExpand1"
          >
          </Table>
          <div class="pageDiv">
            <div class="pageDirection">
              <Page
                :total="total"
                :current.sync="page"
                :page-size="pagesize"
                :page-size-opts="[10, 20, 30, 40, 100]"
                show-elevator
                show-sizer
                show-total
                @on-change="changePage"
                @on-page-size-change="handlePageSize"
              >
              </Page>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 上传程序 -->
    <Modal class="newModalClass echo_wrap" v-model="show" :width="1200">
      <p slot="header">
        <span>上传程序</span>
      </p>
      <div class="modal_body">
        <div class="filter">
          <label style="width: 120px">产品名称/程序号：</label>
          <Input class="searchInput" v-model="name1" @on-change="getProgram" />
        </div>
        <div>
          <Table
            highlight-row
            :max-height="600"
            :data="tableData"
            :columns="columns1"
            @on-current-change="handleRowChange"
          >
          </Table>
        </div>
        <p style="margin-top: 10px">{{ tipsmsg }}</p>
      </div>
      <div slot="footer">
        <Button size="large" @click="show = false">取消</Button>
        <Button size="large" type="primary" @click="submit()">确认</Button>
      </div>
    </Modal>
    <!-- 程序预览弹框 -->
    <Modal
      class="newModalClass echo_wrap"
      v-model="previewModal"
      :width="900"
      footer-hide
    >
      <p slot="header">
        <span>程序预览</span>
      </p>
      <div class="modal_body">
        <Tabs value="0" type="card">
          <TabPane
            v-for="(v, i) in previewList"
            :label="
              v.program_type == 1
                ? `主程序（${v.program_code}）`
                : `子程序（${v.program_code}）`
            "
            :name="`${i}`"
            :key="i"
          >
            <textarea class="echo_textarea" :value="v.file_content"></textarea>
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  </div>
</template>
<script>
import moment from "moment";

export default {
  data() {
    return {
      tipsmsg: "",
      name: "",
      total: 0,
      page: 1,
      pagesize: 10,
      data1: [],
      obj: {},
      columns: [
        {
          type: "expand",
          width: 40,
          render: (h, params) => {
            if (params.row.id === this.obj.id) {
              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
                  ),
                ]
              );
            }
          },
        },
        {
          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",
        },
        {
          title: "程序号",
          key: "program_code",
          align: "center",
        },
        {
          title: "产品图纸号",
          key: "draw_number",
          align: "center",
        },
        {
          title: "创建人",
          key: "pgcreatename",
          align: "center",
        },
        {
          title: "创建时间",
          key: "pgcreatetime",
          align: "center",
        },
        {
          title: "审核人",
          key: "pgcheckname",
          align: "center",
        },
        {
          title: "审核时间",
          key: "pgchecktime",
          align: "center",
        },
        {
          title: "上传人",
          key: "work_name",
          align: "center",
        },
        {
          title: "上传时间",
          key: "time",
          align: "center",
        },
      ],
      cid: "",
      show: false,
      name1: "",
      detailobj: {},
      type: 0,
      total1: 0,
      page1: 1,
      pagesize1: 10,
      content: "",
      previewList: [],
      previewModal: false,
      columns1: [
        {
          title: "序号",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page1 - 1) * this.pagesize1 + 1
            );
          },
          width: 70,
          align: "center",
        },
        {
          title: "操作",
          width: 80,
          align: "center",
          render: (h, params) => {
            const _this = this;
            return h(
              "div",
              {
                style: {
                  textAlign: "center",
                  color: "#2D8CF0",
                  cursor: "pointer",
                },
                on: {
                  click: () => {
                    console.log(params);
                    let row = params.row;
                    if (!row.program_version) {
                      _this.$Message.error("程序版本号不能为空！");
                      return false;
                    }
                    _this.axios
                      .request({
                        url: "/dnc/DncPgCreate/GetAllContent",
                        params: {
                          programId: row.id,
                        },
                        method: "get",
                      })
                      .then((res) => {
                        let result = res.data;
                        if (result.ret == 1) {
                          _this.previewList = [];
                          let data = result.data;
                          if (data && Array.isArray(data) && data.length) {
                            _this.previewList = data;
                          }
                          _this.previewModal = true;
                        } else {
                          _this.$Message.error(_this.$t(result.msg));
                        }
                      });
                  },
                },
              },
              "预览"
            );
          },
        },
        {
          title: "程序号",
          key: "program_code",
          align: "center",
        },
        {
          title: "产品名称",
          key: "productname",
          align: "center",
        },
        {
          title: "图纸号",
          key: "code",
          align: "center",
        },
        {
          title: "大小",
          key: "file_size",
          align: "center",
        },
        {
          title: "工序名称",
          key: "process_name",
          align: "center",
        },
        {
          title: "创建人",
          key: "createname",
          align: "center",
        },
        {
          title: "审核人",
          key: "checkname",
          align: "center",
        },
        {
          title: "创建备注",
          key: "create_remark",
          align: "center",
        },
      ],
      tableData: [],
      disabled1: false,
      disabled2: false,
      delType: 0,
      searchDate: "",
      state: 0,
    };
  },
  computed: {
    treeList() {
      return this.$store.state.app.tree;
    },
  },
  mounted() {
    // 获取树形图数据
    this.$store.dispatch("getTree");
    // 格式化表格样式
    this.columns1 = this.$time.initTableTitle(this.columns1);
    this.columns = this.$time.initTableTitle(this.columns);

    this.searchDate = [
      moment(new Date().getTime() - 3600 * 1000 * 24 * 7).format("YYYY-MM-DD"),
      moment(new Date().getTime()).format("YYYY-MM-DD"),
    ];
  },
  methods: {
    // 监听选中树节点
    getList() {
      let node = this.$refs.tree.getSelectedNodes();
      if (node.length > 0) {
        this.cid = node[0].value;
        this.tosearch();
        // 获取设备信息
        this.getMachineInfo();
      }
    },
    // 获取工位详情
    getMachineInfo() {
      let { request } = this;
      let data = {
        id: this.cid,
      };
      let url = "/config/Machine/GetmachineidBySection";
      request(url, data, "get").then((res) => {
        if (res.data.ret == 1) {
          let info = res.data.data;
          this.tipsmsg = "";
          if (info.attribute == 1) {
            this.state = 1;
          } else if (info.attribute == 2) {
            this.state = 2;
            this.tipsmsg = this.$t(700170);
          } else if (info.attribute == 3) {
            this.state = 3;
            this.tipsmsg = this.$t(700169);
          } else if (info.attribute == 4) {
            this.state = 4;
            this.tipsmsg = this.$t(700171);
          }
        } else {
          this.$Message.error(this.$t(res.data.msg));
        }
      });
    },
    // 查询之前
    tosearch() {
      this.page = 1;
      this.pagesize = 10;
      this.search();
    },
    // 查询
    search() {
      let starttime = "",
        endtime = "";
      starttime = this.searchDate[0];
      endtime = this.searchDate[1];

      var data = {
        sectionId: this.cid,
        starttime: starttime,
        endtime: endtime,
        page: this.page,
        pagesize: this.pagesize,
      };

      let url = "/dnc/DncUpDown/GetPguploadlists";
      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);
        }
      });
    },
    // 渲染右边表格
    renderTable(array) {
      let a = [];
      array.forEach((item, index) => {
        a.push({
          id: item.id,
          machine_name: item.machine_name,
          productname: item.productname,
          productid: item.productid,
          pgcreatename: item.pgcreatename,
          pgcreatetime: item.pgcreatetime,
          createmid: item.createmid,
          file_name: item.file_name,
          file_url: item.file_url,
          pgcheckname: item.pgcheckname,
          pgchecktime: item.pgchecktime,
          checkmid: item.checkmid,
          projectid: item.projectid,
          program_code: item.program_code,
          draw_number: item.draw_number,
          work_name: item.work_name,
          time: item.time,
          _expanded: false,
          _highlight: false,
          index: index,
        });
      });
      this.data1 = a;
    },
    // 点击上传程序
    upload() {
      if (this.cid) {
        this.name1 = "";
        this.getProgram();
        this.show = true;
      } else {
        this.$Message.error("请选择设备");
      }
    },
    // 获取弹框内表格数据
    getProgram() {
      let data = {
        keywords: this.name1,
        pagesize: 666666,
      };
      this.request(
        "/dnc/DncPgCreate/GetProgramsCheckedLists",
        data,
        "get"
      ).then((res) => {
        if (res.data.ret == 1) {
          this.tableData = res.data.data;
        }
      });
    },
    // 弹框中点击确认验证是否要上传程序
    submit() {
      if (JSON.stringify(this.detailobj) == "{}") {
        this.$Message.error("请选择程序");
        return false;
      }
      let data = {
        programcode: this.detailobj.program_code,
        programId: this.detailobj.id,
      };
      let url = "/dnc/DncUpDown/CheckprogramsNew";
      this.request(url, data, "get").then((res) => {
        if (res.data.ret == 1) {
          let msg = alert(this.$t(700134));
          if (msg) {
            this.uploadProgramPost();
          }
        } else {
          this.uploadProgramPost();
        }
      });
    },
    // 上传程序
    uploadProgramPost() {
      let data = {
        sectionid: this.cid,
        programid: this.detailobj.id,
      };
      let url = "/dnc/DncUpDown/UploadMainSonProgram";
      this.request(url, data, "post").then((res) => {
        if (res.data.ret == 1) {
          this.show = false;
          this.$Message.success("上传成功");
          this.tosearch();
        } else {
          this.$Message.error(this.$t(res.data.msg));
        }
      });
    },
    // 根据表格每一行的文件地址获取文件内容
    getText(url) {
      let data = {
        file_url: url,
      };
      this.request("/dnc/DncPgCreate/getContent", data, "get").then((res) => {
        if (res.data.ret == 1) {
          this.content = res.data.data.content;
        }
      });
    },
    // 监听弹框内表格当前选中行
    handleRowChange(v) {
      this.detailobj = v;
      this.getText(v.file_url);
    },
    // 监听右边表格页距变化
    handlePageSize(v) {
      this.pagesize = v;
      this.search();
    },
    // 监听右边表格页码变化
    changePage(v) {
      this.page = v;
      this.search();
    },
    // 监听右边表格当前选中行
    handleRowChange1(v) {
      this.obj = v;
      this.getText(v.file_url);
    },
    // 右边表格点击某一行展开，其它行收缩
    onExpand1(row, 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) {
        this.$Message.error("请选择设备");
        return;
      }
      if (!this.obj.id) {
        this.$Message.error("请选择数据");
        return;
      }
      if (!this.obj.file_url) {
        this.$Message.error(this.$t("9000147"));
        return;
      }
      this.request(
        "/dnc/DncPgCreate/getContent?file_url=" + this.obj.file_url,
        "",
        "get"
      ).then((res) => {
        if (res.data.ret === 1) {
          var info = res.data.data;
          var content = info.content.replace(/\n/g, "\r\n");
          this.funDownload(content, this.obj.file_name);
        } else {
          this.$Message.error(this.$t(res.data.msg));
        }
      });
    },
    // Blob 文件下载方法
    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);
    },
    // 进一步封装 axios 请求方法
    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);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.echo_textarea::-webkit-scrollbar {
  width: auto;
}
.echo_textarea {
  font-size: 14px;
  white-space: nowrap;
  overflow: scroll;
  resize: none;
  width: 100%;
  height: 444px;
}
.echo_btn {
  display: inline-flex;
}
.tips {
  height: 40px;
  line-height: 40px;
}
.echo_flex {
  margin: 0 10px;
  justify-content: space-between;
}
.tipsmsg {
  margin-left: 10px;
}
.flex {
  display: flex;
}
.label {
  width: 100px;
}
</style>
