<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <div class="filter">
        <label>创建人：</label>
        <Input class="searchInput" v-model="createBy" />
      </div>
      <div class="filter">
        <label>审核人：</label>
        <Input class="searchInput" v-model="checkBy" />
      </div>
      <div class="filter">
        <label>产品名称：</label>
        <Select v-model="productId" clearable filterable class="searchSelect">
          <Option v-for="v in productList" :value="v.id" :key="v.id">{{
            v.name
          }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>时间范围：</label>
        <DatePicker
          type="daterange"
          clearable
          :value="searchDate"
          class="searchInput middleWidth"
          @on-change="handleDateChange"
        ></DatePicker>
      </div>
      <div class="searchBtn">
        <!-- 查询 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="search(true)"
        >
          查询
        </Button>
        <!-- 下载 -->
        <Button
          type="primary"
          class="twoWord intervalRight"
          icon="md-download"
          @click="download()"
        >
          下载
        </Button>
        <!-- 上传至 NC -->
        <Button
          type="primary"
          class="fourWord"
          icon="md-add-circle"
          @click="upload()"
        >
          上传至NC
        </Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        highlight-row
        class="tableClass"
        :data="tableData"
        :columns="tableColumns"
        @on-current-change="handleRowChange"
      >
      </Table>
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current.sync="page"
            :page-size.sync="pagesize"
            :page-size-opts="[10, 20, 30, 40, 100]"
            show-elevator
            show-sizer
            show-total
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
          >
          </Page>
        </div>
      </div>
    </div>
    <!-- 上传至NC弹框 -->
    <Modal class="newModalClass" v-model="showModal" :width="666">
      <p slot="header">
        <span>上传</span>
      </p>
      <div class="modal_body">
        <div class="echo_left">
          <div class="pgInfo">
            <p>程序号：{{ row.program_code }}</p>
            <p>产品名称：{{ row.productname }}</p>
            <p>图纸号：{{ row.code }}</p>
            <p>创建人：{{ row.createname }}</p>
            <p>创建备注：{{ row.create_remark }}</p>
            <p>审核人：{{ row.checkname }}</p>
            <p>审核备注：{{ row.check_remark }}</p>
            <p>文件大小：{{ row.file_size }} B</p>
          </div>
          <div style="margin: 20px">已选择：{{ machineName }}</div>
          <div style="margin: 20px">{{ msg }}</div>
        </div>
        <div class="divborder echo_right">
          <Tree :data="treeList" ref="tree" @on-select-change="getList()">
          </Tree>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="showModal = false">取消</Button>
        <Button
          id="uploadProgram"
          size="large"
          type="primary"
          @click="uploadProgram"
        >
          上传
        </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" v-if="refresh">
        <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 {
      // 页码 页距 总计
      page: 1,
      pagesize: 10,
      total: 0,
      // 搜索条件 创建人 审核人 产品名称 搜索时间范围
      createBy: "",
      checkBy: "",
      productId: "",
      searchDate: [],
      // 产品名称下拉列表
      productList: [],
      previewList: [],
      previewModal: false,
      refresh: true,
      // 表格数据 表格字段列
      tableData: [],
      tableColumns: [
        {
          type: "sort",
          title: "序号",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 75,
          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;
                          _this.refresh = false;
                          _this.$nextTick(() => {
                            _this.refresh = true;
                          });
                        } else {
                          _this.$Message.error(_this.$t(result.msg));
                        }
                      });
                  },
                },
              },
              "预览"
            );
          },
        },
        {
          title: "主程序号",
          key: "program_code",
        },
        {
          title: "产品名称",
          key: "productname",
        },
        {
          title: "产品图纸号",
          key: "code",
        },
        {
          title: "工序名称",
          key: "process_name",
        },
        {
          title: "主程序文件名",
          key: "file_name",
          width: 120,
          align: "center",
        },
        {
          title: "创建人",
          key: "createname",
          width: 85,
          align: "center",
        },
        {
          title: "创建时间",
          key: "createtime",
          width: 150,
          align: "center",
        },
        {
          title: "创建备注",
          key: "create_remark",
          width: 90,
          align: "center",
        },
        {
          title: "审核人",
          key: "checkname",
          width: 85,
          align: "center",
        },
        {
          title: "审核时间",
          key: "checktime",
          width: 150,
          align: "center",
        },
        {
          title: "审核结果",
          width: 90,
          align: "center",
          render: (h, params) => {
            let status = params.row.checkinfo;
            let text;
            switch (status) {
              case 0:
                text = "未审核";
                break;
              case 1:
                text = "通过";
                break;
              case 2:
                text = "不通过";
                break;
            }
            return h(
              "div",
              {
                style: {
                  textAlign: "center",
                },
              },
              text
            );
          },
        },
        {
          title: "审核备注",
          key: "check_remark",
          width: 90,
          align: "center",
        },
        {
          title: "子程序个数",
          key: "program_number",
          align: "center",
        },
        {
          title: "版本号",
          key: "program_version",
        },
        {
          title: "状态",
          align: "center",
          width: 90,
          render: (h, params) => {
            let bg, text;
            let status = params.row.checkstatus;
            switch (status) {
              case 1:
                text = "待审核";
                bg = "#FFFF00";
                break;
              case 2:
                text = "已审核";
                bg = "#00FF00";
                break;
              case 3:
                text = "被拒绝";
                bg = "#FF0000";
                break;
            }
            return h("div", {
              domProps: {
                innerHTML: text,
              },
              style: {
                backgroundColor: bg,
                width: "100%",
                height: "36px",
                lineHeight: "36px",
                textAlign: "center",
              },
            });
          },
        },
      ],
      // 弹框是否弹出
      showModal: false,
      row: {},

      machineName: "",
      machineId: "",
      msg: "",
    };
  },
  computed: {
    // 树结构数据
    treeList() {
      return this.$store.state.app.tree;
    },
  },
  mounted() {
    // 获取产品名称下拉列表
    this.getProductList();
    // 获取树结构数据
    this.$store.dispatch("getTree");

    // 格式化表格样式
    this.tableColumns = this.$time.initTableTitle(this.tableColumns);

    this.search();
  },
  methods: {
    handlePageSize(v) {
      this.page = 1;
      this.pagesize = v;
      this.search();
    },
    handlePage(v) {
      this.page = v;
      this.search();
    },
    handleRowChange(v) {
      this.row = v;
    },
    // 获取产品名称下拉列表
    getProductList() {
      const _this = this;
      _this.axios
        .request({
          url: "/config/ProjectProduct/GetProductsByCode?code=&name=&count=50",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.productList = result.data;
          }
        });
    },
    // 获取具体工位的相关信息
    getList() {
      let node = this.$refs.tree.getSelectedNodes();
      if (node.length) {
        if (node[0].children.length) {
          this.$Message.error(this.$t(100128));
        } else {
          this.getMachineInfo(node[0].value);
        }
      }
    },
    // 根据产线层级 ID 获取详情
    getMachineInfo(id) {
      let params = {
        id,
      };
      this.axios
        .request({
          url: "/config/Machine/GetmachineidBySection",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.machineName = res.data.data.title;
            let v = res.data.data;
            this.msg = "";
            if (v.attribute == 1) {
              this.machineName = v.title;
              this.machineId = v.machine_id;
            } else if (v.attribute == 2) {
              this.machineName = v.title;
              this.machineId = v.machine_id;
              this.msg = this.$t(700170); // 串口设备，上传前要在设备上点击接收程序
            } else if (v.attribute == 3) {
              this.machineName = v.title;
              this.machineId = v.machine_id;
              this.msg = this.$t(700169); // ftp设备
            } else if (v.attribute == 4) {
              $("#uploadProgram").hide();
              this.msg = this.$t(700171); // 无系统设备没法上传
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 监听查询日期范围变化
    handleDateChange(v) {
      this.searchDate = v;
    },
    // 查询
    search(isInit) {
      const _this = this;
      _this.row = {};
      if (isInit) {
        _this.page = 1;
        _this.pagesize = 10;
      }
      let { createBy, checkBy, productId, searchDate, page, pagesize } = this;
      let params = {
        createBy,
        checkBy,
        keywords: productId,
        page,
        pagesize,
      };
      if (searchDate[0]) {
        params.startDate =
          parseInt(new Date(`${searchDate[0]} 00:00:00`).getTime()) / 1000;
      }
      if (searchDate[1]) {
        params.endDate =
          parseInt(new Date(`${searchDate[1]} 23:59:59`).getTime()) / 1000;
      }

      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetProgramsCheckedLists",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.total = result.total;
            _this.tableData = [];
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.tableData = data;
            }
          }
        });
    },
    // 点击上传按钮
    upload() {
      const _this = this;
      let { row } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(1043));
        return false;
      }
      _this.$store.dispatch("getTree");
      _this.machineName = "";
      _this.showModal = true;
    },
    // 点击下载按钮
    download() {
      const _this = this;
      let { row, $t } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error($t(1043));
        return false;
      }
      if (!row.file_url) {
        _this.$Message.error($t(9000147));
        return false;
      }
      _this.axios
        .request({
          url: `/dnc/DncPgCreate/DownloadZipById?programId=${row.id}`,
          data: {
            programId: row.id,
          },
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            window.location.href = _this.axios.publicPath + result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 上传程序
    uploadProgram() {
      let data = {
        programid: this.row.id, // 程序id
        machineid: this.machineId, // 设备id
      };
      this.axios
        .request({
          url: "/dnc/DncUpDown/UploadMainSonProgram",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.$Message.success("上传成功");
            this.showModal = false;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
  },
};
</script>
<style scoped>
.echo_textarea::-webkit-scrollbar {
  width: auto;
}
.echo_textarea {
  font-size: 14px;
  white-space: nowrap;
  overflow: auto;
  resize: none;
  width: 100%;
  height: 444px;
}
.echo_right {
  width: 280px;
  height: 400px;
  overflow: auto;
}
.echo_left {
  width: 45%;
  float: left;
  height: 100%;
  padding-left: 5px;
}
.expand-row {
  margin-bottom: 16px;
}
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
.pgInfo {
  font-size: 12px;
  background-color: #ddd;
  border-radius: 10px;
  padding: 20px;
  line-height: 30px;
  margin-right: 10px;
}
</style>
