<template>
  <div class="t_pgcl">
    <Row :gutter="12" class="h100" v-if="productId && routeId">
      <Col span="12" class="h100 p24">
        <div class="card bg_white">
          <h1 v-if="returnProgram.length">设备内程序回传至服务器：</h1>
          <div class="pg_list" v-if="returnProgram.length">
            <div
              class="pg"
              :id="`returnPg${i}`"
              v-for="(v, i) in returnProgram"
              :key="i"
              @click="selectReturnPg(i)"
            >
              <div class="pg_title">{{ v.program_code }}</div>
              <div
                class="pg_preview"
                @click="returnProgramPreview(v.machine_id, v.program_code)"
              >
                <Icon type="md-eye" />
                预览
              </div>
            </div>
          </div>
          <div class="btn" v-if="returnProgram.length">
            <Button size="large" type="primary" @click="beforeReturn()">
              程序回传
            </Button>
          </div>
          <div class="empty h100" v-if="!returnProgram.length"></div>
        </div>
      </Col>
      <Col span="12" class="h100 p24">
        <div class="card bg_white">
          <h1 v-if="callProgram.length">服务器端程序调用至设备：</h1>
          <div v-if="callProgram.length" class="pg_list">
            <div
              class="pg"
              :id="`callPg${i}`"
              v-for="(v, i) in callProgram"
              :key="i"
              @click="selectCallPg(i)"
            >
              <div class="pg_title">
                <span>{{ v.program_code }}</span>
                <span class="pg_version">{{ v.program_version }}</span>
              </div>
              <div class="pg_preview" @click="callProgramPreview(v.id)">
                <Icon type="md-eye" />
                预览
              </div>
            </div>
          </div>
          <div class="btn" v-if="callProgram.length">
            <Button size="large" type="primary" @click="beforeCall()">
              程序调用
            </Button>
            <div class="tips">
              <span>提示：上传前请在设备上点击【接收】程序</span>
            </div>
          </div>
          <div class="empty h100" v-if="!callProgram.length"></div>
        </div>
      </Col>
    </Row>
    <div class="empty h100" v-else></div>
    <!-- 程序调用预览弹框 -->
    <Modal v-model="callPreview" footer-hide fullscreen>
      <p slot="header">
        <span> 程序预览 </span>
      </p>
      <div class="modal_body">
        <Tabs value="0" type="card">
          <TabPane
            v-for="(v, i) in callPreviewList"
            :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>
    <!-- 程序回传预览弹框 -->
    <Modal v-model="returnPreview" footer-hide fullscreen>
      <p slot="header">
        <span> 程序预览 </span>
      </p>
      <div class="modal_body">
        <Tabs value="0" type="card">
          <TabPane
            v-for="(v, i) in returnPreviewList"
            :label="`程序（${v.code}）`"
            :name="`${i}`"
            :key="i"
          >
            <textarea class="echo_textarea" :value="v.content"></textarea>
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: "t_pgcl",
  inject: ["reload"],
  props: {
    curLevel: {
      type: Array,
    },
    levelNums: {
      type: Number,
    },
    signDetail: {
      type: Object,
    },
  },
  data() {
    return {
      // 程序调用列表
      callProgram: [],
      // 程序调用预览弹框是否显示
      callPreview: false,
      // 程序调用预览列表
      callPreviewList: [],
      // 当前选中的调用程序
      curCallPg: {},
      // 程序回传列表
      returnProgram: [],
      // 程序回传预览弹框是否显示
      returnPreview: false,
      // 程序回传预览列表
      returnPreviewList: [],
      // 当前选中的回传程序
      curReturnPg: {},
      productId: 0,
      routeId: 0,
      // 全屏好看的 Loading
      loading: null,
    };
  },
  mounted() {
    const _this = this;
    // 若当前页面不是从签到签出页面跳转过来的，就返回签到签出页面
    if (!_this.curLevel.length) {
      _this.$router.replace({
        name: "t_sign",
      });
      return false;
    }
    _this.getReturnProgram();
    _this.getWkodBySection();
  },
  methods: {
    // 根据工位 ID 查询该工位下是否有已绑定的工单
    getWkodBySection() {
      const _this = this;
      let params = {
        sectionId: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebScanMachine",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.productId = data.product_id;
            _this.routeId = data.route_id;
            _this.getCallProgram();
          }
        });
    },
    // 获取程序调用列表
    getCallProgram() {
      const _this = this;
      let params = {
        page: 1,
        pagesize: 999999999,
        product_id: _this.productId,
        route_id: _this.routeId,
      };
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetProgramsCheckedList",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          _this.callProgram = [];
          if (result.ret == 1) {
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.callProgram = data;
            }
          }
        });
    },
    // 调用程序预览
    callProgramPreview(id) {
      const _this = this;
      let params = {
        programId: id,
      };
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetAllContent",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          _this.callPreviewList = [];
          if (result.ret == 1) {
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.callPreviewList = data;
            }
            _this.callPreview = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 选中调用程序
    selectCallPg(i) {
      this.curCallPg = {};
      this.curReturnPg = {};
      $(".pg").removeClass("pg_active");
      $(`#callPg${i}`).addClass("pg_active");
      this.curCallPg = this.callProgram[i];
      console.log(this.curCallPg);
    },
    // 程序调用之前
    beforeCall() {
      const _this = this;
      if (JSON.stringify(_this.curCallPg) == "{}") {
        _this.$Message.error("请选择程序！");
        return false;
      }
      let params = {
        programcode: _this.curCallPg.program_code,
        programId: _this.curCallPg.id,
      };
      _this.axios
        .request({
          url: "/dnc/DncUpDown/CheckprogramsNew",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let isUpload = alert(_this.$t(700134));
            if (isUpload) {
              _this.call();
            }
          } else {
            _this.call();
          }
        });
    },
    // 调用程序
    call() {
      const _this = this;
      let data = {
        sectionid: _this.curLevel[_this.curLevel.length - 1],
        programid: _this.curCallPg.id,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/dnc/DncUpDown/UploadMainSonProgram",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("程序调用成功！");
            _this.getReturnProgram();
            _this.getCallProgram();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 获取程序回传列表
    getReturnProgram() {
      const _this = this;
      let params = {
        sectionid: _this.curLevel[_this.curLevel.length - 1],
        page: 1,
        pageSize: 999999999,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/dnc/DncContrast/getProgramBymID",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          _this.returnProgram = [];
          if (result.ret == 1) {
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.returnProgram = data;
            }
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 回传程序预览
    returnProgramPreview(machineid, programcode) {
      const _this = this;
      let params = {
        machineid,
        programcode,
      };
      _this.axios
        .request({
          url: "/dnc/dnc/Getncvalue",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          _this.returnPreviewList = [];
          if (result.ret == 1) {
            let data = result.data;
            if (data) {
              let arr = [];
              arr.push({
                code: programcode,
                content: data,
              });
              _this.returnPreviewList = arr;
            }
            _this.returnPreview = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 选中回传程序
    selectReturnPg(i) {
      this.curCallPg = {};
      this.curReturnPg = {};
      $(".pg").removeClass("pg_active");
      $(`#returnPg${i}`).addClass("pg_active");
      this.curReturnPg = this.returnProgram[i];
      console.log(this.curReturnPg);
    },
    // 程序回传之前 之前个锤子，直接回传
    beforeReturn() {
      const _this = this;
      if (JSON.stringify(_this.curReturnPg) == "{}") {
        _this.$Message.error("请选择程序！");
        return false;
      }
      let data = {
        sectionid: _this.curLevel[_this.curLevel.length - 1],
        program: _this.curReturnPg.program_code,
        productName: _this.curReturnPg.product_name,
        machine_id: _this.curReturnPg.machine_id,
        product_id: _this.productId ? _this.productId : 0,
        route_id: _this.routeId ? _this.routeId : 0,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/ReturnPrograms",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("程序回传成功！");
            _this.getReturnProgram();
            _this.getCallProgram();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
  },
};
</script>
<style lang="less" scoped>
.t_pgcl {
  height: 100%;
  .h100 {
    height: 100%;
  }
  .p24 {
    padding: 0 0 8px;
    .bg_white {
      background-color: #fff;
    }
    .card {
      height: 100%;
      width: 99%;
      margin: 0 auto;
      padding: 12px 16px;
      position: relative;
      .pg_list {
        overflow-y: auto;
        margin-top: 12px;
        height: ~"calc(80vh - 120px)";
        .pg {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 8px 12px;
          border-bottom: 1px solid #f7f8fa;
          .pg_title {
            font-size: 20px;
            color: #8e94a1;
            .pg_version {
              color: #9a9a9a;
              margin-left: 16px;
            }
          }
          .pg_preview {
            cursor: pointer;
            font-size: 18px;
            color: #2f8df0;
          }
        }
      }
      .btn {
        position: absolute;
        bottom: 16px;
        width: 95%;
        display: flex;
        flex-direction: row-reverse;
        justify-content: space-between;
        .tips {
          color: #ababab;
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
  }
}
.modal_body {
  height: 100%;
  .echo_textarea {
    height: 85vh;
    font-size: 20px;
    white-space: nowrap;
    overflow: auto;
    resize: none;
    width: 100%;
  }
}
.echo_textarea::-webkit-scrollbar {
  width: 0;
  height: 0;
}
.pg_active {
  background-color: #f5f7f9;
}
.pg:hover {
  background-color: #f5f7f9;
}
.empty {
  background: url("../../static/images/empty.png");
  background-repeat: no-repeat;
  background-position: 50% 50%;
}
</style>
