<template>
  <div class="testdiv">
    <!-- 查询条件 -->
    <div class="divborder newSearchDiv" style="margin: 0px">
      <!-- 产品名称 -->
      <div class="filter">
        <label>产品名称：</label>
        <Input class="searchInput" type="text" v-model="productName" />
      </div>
      <!-- 订单号 -->
      <div class="filter">
        <label>工令号：</label>
        <Input class="searchInput" type="text" v-model="orderNo" />
      </div>
      <!-- 工单批次号 -->
      <div class="filter">
        <label>工单批次号：</label>
        <Input class="searchInput" type="text" v-model="produceNo" />
      </div>
      <!-- 工单状态 -->
      <div class="filter">
        <label>工单状态：</label>
        <Select v-model="status" clearable class="searchSelect">
          <Option :value="2">{{ $t(900938) }}</Option>
          <Option :value="3">{{ $t(444432) }}</Option>
          <Option :value="4">{{ $t(500096) }}</Option>
          <Option :value="5">{{ $t(900936) }}</Option>
          <Option :value="6">{{ $t(900935) }}</Option>
        </Select>
      </div>
      <!-- 次级搜索条件 -->
      <div v-show="!morecondition">
        <!-- 添加时间 -->
        <div class="filter">
          <label>添加时间：</label>
          <DatePicker
            type="daterange"
            :value="dateRange"
            class="searchInput middleWidth"
            @on-change="dateRangeChange"
          ></DatePicker>
        </div>
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <!-- 查询按钮 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search-outline"
          @click="search()"
          >{{ $t(1001) }}</Button
        >
        <!-- 打印工单按钮 -->
        <Button
          type="primary"
          class="fourWord"
          icon="ios-print-outline"
          @click="print()"
          >打印工单</Button
        >
      </div>
      <!-- 次级搜索条件是否显示 -->
      <MoreConbtn
        @getCon="morecondition = !morecondition"
        :morecondition="morecondition"
      ></MoreConbtn>
    </div>
    <!-- 数据展示 -->
    <div class="divborder newTableDiv">
      <!-- 表格主体 -->
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData"
        :columns="tableColumns"
      >
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" size="small" @click="progress(row, index)"
            >查看</Button
          >
        </template>
      </Table>
      <!-- 分页器 -->
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          ></Page>
        </div>
      </div>
    </div>
    <!-- 查看进度弹框 -->
    <Modal
      class="newModalClass progressModal"
      v-model="progressModal"
      :styles="{ width: '1200px' }"
    >
      <p slot="header">
        <span>进度</span>
      </p>
      <div class="modal_body progress">
        <div>
          <div class="filter">
            <label>工令号：</label>
            <Input class="searchInput" :value="row.orderNumber" disabled />
          </div>
          <div class="filter">
            <label>产品名称：</label>
            <Input class="searchInput" :value="row.product_name" disabled />
          </div>
          <div class="filter">
            <label>交付时间：</label>
            <Input class="searchInput" :value="row.delivery_time" disabled />
          </div>
          <div class="filter">
            <label>派工数量：</label>
            <Input class="searchInput" :value="row.quantity" disabled />
          </div>
        </div>
        <div style="margin-top: 16px">
          <Table
            :data="progressTableData"
            :columns="progressTableColumns"
            :max-height="450"
          ></Table>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
    <!-- 打印工单弹框 -->
    <Modal
      class="newModalClass printModal"
      v-model="printModal"
      :styles="{ width: '1000px' }"
    >
      <div class="modal_body">
        <div id="printContent">
          <h1 style="text-align: center">生产制造电子工单</h1>
          <div
            style="
              margin-top: 24px;
              display: flex;
              justify-content: space-between;
              font-size: 16px;
            "
          >
            <div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">订单号：</span>
                <span>{{ printTop.orderNo }}</span>
              </div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">工单号：</span>
                <span>{{ printTop.code }}</span>
              </div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">产品名称：</span>
                <span>{{ printTop.productName }}</span>
              </div>
            </div>
            <div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">交货期：</span>
                <span>{{ printTop.deliverTime }}</span>
              </div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">派单日期：</span>
                <span>{{ printTop.addTime }}</span>
              </div>
              <div style="margin-bottom: 20px">
                <span style="font-weight: bold">派单人员：</span>
                <span>{{ printTop.user }}</span>
              </div>
            </div>
            <div>
              <div style="text-align: center">
                <span style="font-weight: bold">工令号：</span>
                <!-- <span>{{ printTop.orderNumber }}</span> -->
              </div>
              <div style="text-align: center">
                <span
                  id="taskNoQR"
                  style="display: inline-block; width: 88px; height: 88px"
                ></span>
              </div>
            </div>
          </div>
          <table
            style="width: 100%; margin-top: 12px"
            border="1"
            cellspacing="0"
          >
            <tr
              style="
                height: 44px;
                text-align: center;
                background-color: #169bd5;
                font-size: 16px;
                font-weight: bold;
              "
            >
              <th style="width: 80px">工序号</th>
              <th>工序名称</th>
              <th>工序描述</th>
              <th>计划使用设备</th>
              <th>计划数量</th>
              <th>合格数</th>
              <th>不合格数</th>
              <th style="width: 80px">工序码</th>
            </tr>
            <tr
              v-for="(v, i) in printList"
              :key="i"
              style="height: 80px; text-align: center; font-size: 16px"
            >
              <td>{{ v.serialNumber }}</td>
              <td>{{ v.name }}</td>
              <td>{{ v.description }}</td>
              <td></td>
              <td>{{ v.quantity }}</td>
              <td></td>
              <td></td>
              <td style="padding: 5px" :id="`qrcode${i}`"></td>
            </tr>
            <!-- <tr style="height: 80px; text-align: center; font-size: 16px">
              <td>备注</td>
              <td colspan="7"></td>
            </tr> -->
          </table>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="printModal = false">取消</Button>
        <Button type="primary" size="large" @click="output()">打印</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import moment from "moment";
import QRCode from "qrcodejs2";
import { getLodop } from "@/assets/js/LodopFuncs.js";

export default {
  data() {
    return {
      // 搜索条件--产品名称
      productName: "",
      // 搜索条件--订单号
      orderNo: "",
      // 搜索条件--工单批次号
      produceNo: "",
      // 搜索条件--工单状态
      status: "",
      // 搜索条件--时间范围
      dateRange: [],
      // 次级搜索条件是否显示
      morecondition: false,
      // 选中行
      row: {},
      // 数据总量
      total: 0,
      // 页码
      page: 1,
      // 页距
      pagesize: 10,
      // 表格数据
      tableData: [],
      // 表格字段
      tableColumns: [
        {
          type: "sort",
          title: this.$t(1008),
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 88,
        },
        {
          title: this.$t(900958),
          key: "orderNumber",
        },
        {
          title: this.$t(900924),
          key: "delivery_time",
        },
        {
          title: this.$t(100088),
          key: "product_name",
        },
        {
          title: this.$t(100089),
          key: "product_code",
        },
        {
          title: this.$t(900337),
          key: "code",
        },
        {
          title: this.$t(200054),
          key: "status",
          align: "center",
          render: (h, params) => {
            let status, bg;
            if (params.row.status == 2) {
              status = "未排产";
              bg = "#FF9900";
            } else if (params.row.status == 3) {
              status = "已派工";
              bg = "#FF5E31";
            } else if (params.row.status == 4) {
              status = "生产中";
              bg = "#2D8CF0";
            } else if (params.row.status == 5) {
              status = "已完工";
              bg = "#2CC377";
            } else if (params.row.status == 6) {
              status = "已终止";
              bg = "#ED4014";
            } else {
              status = "逾期";
              bg = "#0000FF";
            }
            return h(
              "div",
              {
                style: {
                  backgroundColor: bg,
                  color: "#fff",
                  width: "100%",
                  height: "36px",
                  lineHeight: "36px",
                  textAlign: "center",
                },
              },
              status
            );
          },
        },
        {
          title: this.$t(811197),
          key: "quantity",
        },
        {
          title: this.$t(901009),
          key: "producted_number",
        },
        {
          title: this.$t(901010),
          key: "difference",
        },
        {
          title: this.$t(5500096),
          slot: "action",
          align: "center",
        },
      ],
      // 查看进度弹框是否弹出
      progressModal: false,
      // 进度弹出框中表格数据
      progressTableData: [],
      // 进度弹出框中表格列字段
      progressTableColumns: [
        {
          title: "工序",
          key: "serialNumber",
        },
        {
          title: "工序名称",
          key: "name",
        },
        {
          title: "工序说明",
          key: "description",
        },
        {
          title: "工单数量",
          key: "producted_number",
        },
        {
          title: "已派工数量",
          key: "job_count",
        },
        {
          title: "OK数量",
          key: "ok_number",
        },
        {
          title: "NOK数量",
          key: "nok_number",
        },
        {
          title: "生产进度",
          width: 250,
          align: "center",
          render: (h, params) => {
            let per = params.row.productionschedule;
            return h("div", [
              h("Progress", {
                props: {
                  percent: per > 100 ? 100 : per,
                  "stroke-width": 20,
                  "hide-info": true,
                },
                style: {
                  marginRight: "4px",
                  width: "75%",
                },
              }),
              h("span", {
                domProps: {
                  innerHTML: per.toFixed(1) + "%",
                },
                style: {
                  fontWeight: "bold",
                },
              }),
            ]);
          },
        },
        {
          title: "状态",
          key: "state",
        },
      ],
      // 打印工单弹框是否弹出
      printModal: false,
      // 打印工单弹框中上方的数据
      printTop: {},
      // 打印工单弹框中下方的列表数据
      printList: [],
    };
  },
  mounted() {
    // 初始化表格字段
    this.tableColumns = this.$time.initTableTitle(this.tableColumns);
    this.progressTableColumns = this.$time.initTableTitle(
      this.progressTableColumns
    );
    // 初始化查询
    this.search();
  },
  methods: {
    // 查询
    search() {
      // 拿到当前组件实例
      const _this = this;
      // 解构取值
      let {
        page,
        pagesize,
        productName,
        orderNo,
        produceNo,
        status,
        dateRange,
      } = this;
      let params = {
        productName: productName,
        code: produceNo,
        orderNumber: orderNo,
        status: status,
        startTime: dateRange[0] ? dateRange[0] : "",
        endTime: dateRange[1] ? dateRange[1] : "",
        page,
        pagesize,
      };
      _this.axios
        .request({
          url: "cnc/WorkOrderList/GetWorkOrderList",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.total = result.total;
            _this.page = result.page;
            _this.pagesize = result.pagesize;
            _this.tableData = [];
            if (data && Array.isArray(data) && data.length) {
              _this.initTableData(data);
            }
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 改变页码
    changePage(value) {
      this.page = value;
      this.search();
    },
    // 改变页距
    handlePageSize(value) {
      this.pagesize = value;
      this.search();
    },
    // 选中行
    handleRowChange(currentRow) {
      this.row = currentRow;
    },
    // 监听时间范围变化
    dateRangeChange(v) {
      this.dateRange = v;
    },
    // 初始化表格数据
    initTableData(tablelist) {
      let data = [];
      tablelist.forEach((item) => {
        if (item) {
          data.push({
            id: item.id,
            orderNumber: item.orderNumber,
            delivery_time: item.delivery_time
              ? moment(item.delivery_time * 1000).format("YYYY-MM-DD")
              : "",
            product_name: item.product_name,
            product_code: item.product_code,
            code: item.code,
            status: item.status,
            quantity: item.quantity,
            producted_number: item.producted_number,
            difference: item.difference,
          });
        }
      });
      this.tableData = data;
    },
    // 查看进度
    progress(row, index) {
      const _this = this;
      let params = {
        id: row.id,
      };
      _this.axios
        .request({
          url: "cnc/WorkOrderList/GetOrderProgress",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.progressTableData = [];
            let data = result.data;
            if (Array.isArray(data) && data.length) {
              _this.progressTableData = data;
            }
            // 弹框弹出
            _this.progressModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 打印工单
    print() {
      const _this = this;
      let { row } = this;
      // 若未选择行数据，捕获错误并退出
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(9000396));
        return false;
      }
      let params = {
        id: row.id,
      };
      _this.axios
        .request({
          url: "cnc/WorkOrderList/GetWorkOrderRouteDetals",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            let top = {};
            let list = [];
            if (data && Array.isArray(data) && data.length) {
              top.orderNo = data[0].ordernumber;
              top.deliverTime = data[0].delivery_time;
              top.orderNumber = data[0].orderNumber;
              top.code = data[0].code;
              top.addTime = data[0].addTime;
              top.productName = data[0].product_name;
              top.user = data[0].user;
              _this.generateORCode("taskNoQR", top.orderNumber, 88, 88);
              list = data;
            } else {
              _this.$Message.error(_this.$t(444452));
              return false;
            }
            _this.printTop = top;
            _this.printList = list;
            _this.$nextTick(() => {
              for (let i = 0; i < list.length; i++) {
                _this.generateORCode(
                  `qrcode${i}`,
                  `${list[i].orderNumber}|${list[i].route_id}`,
                  70,
                  70
                );
              }
            });
            // 弹框弹出
            _this.printModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 生成二维码
    generateORCode(id, text, w, h) {
      // 清空区域内容
      document.getElementById(id).innerHTML = "";
      // 生成二维码
      let qrcode = new QRCode(id, {
        width: w,
        height: h,
        // 二维码内容
        text: text,
        // 前景色
        colorDark: "#000",
        // 背景色
        colorLight: "#fff",
        // 容错等级
        correctLevel: QRCode.CorrectLevel.L,
      });
    },
    // 输出到打印机打印
    output() {
      const _this = this;
      let { $t } = this;
      if (!getLodop()) {
        _this.$Modal.confirm({
          title: $t(600013),
          content: $t(444454),
          width: 360,
          closable: true,
          okText: $t(444455),
          onOk: () => {
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = "/static/lodop/clodop_setup.exe";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            _this.printModal = false;
            return false;
          },
        });
        return false;
      }
      LODOP = getLodop();
      LODOP.PRINT_INIT("打印工单");
      LODOP.ADD_PRINT_HTM(
        "24px",
        "2%",
        "96%",
        "100%",
        document.getElementById("printContent").innerHTML
      );
      LODOP.PREVIEW();
    },
  },
};
</script>
