<template>
  <div class="testdiv">
    <!-- 查询条件 -->
    <div class="divborder newSearchDiv" style="margin: 0px">
      <!-- 订单号 -->
      <div class="filter">
        <label>{{ $t(300038) }}：</label>
        <Input class="searchInput" v-model="productionOrderNo" />
      </div>
      <!-- 产品名称 -->
      <div class="filter">
        <label>{{ $t(100088) }}：</label>
        <Input class="searchInput" v-model="productName" />
      </div>
      <!-- 工单号 -->
      <div class="filter">
        <label>{{ $t(900337) }}：</label>
        <Input class="searchInput" v-model="workOrderNo" />
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <!-- 查询按钮 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="search()"
          >{{ $t(1001) }}</Button
        >
        <!-- 派工按钮 -->
        <Button
          type="success"
          class="twoWord"
          icon="md-add-circle"
          @click="add()"
          >{{ $t(950371) }}</Button
        >
        <!-- 终止按钮 -->
        <Button
          type="warning"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="end()"
          >{{ $t(900948) }}</Button
        >
        <!-- 查看进度按钮 -->
        <Button
          type="primary"
          class="fourWord"
          icon="md-download"
          @click="progress()"
          >{{ $t(5500096) }}</Button
        >
      </div>
    </div>
    <div class="divborder newTableDiv">
      <!-- 主体表格 -->
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData"
        :columns="tableColumns"
      ></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 dispatchModal"
      v-model="dispatchModal"
      :styles="{ width: '1200px' }"
    >
      <p slot="header">
        <span>派工</span>
      </p>
      <div class="modal_body dispatch">
        <div>
          <div class="filter">
            <label>工单数量：</label>
            <Input class="searchInput" :value="row.install_count" disabled />
          </div>
          <div class="filter">
            <label>已排数量：</label>
            <Input
              class="searchInput"
              :value="row.scheduled_quantity"
              disabled
            />
          </div>
          <div class="filter">
            <label> <i>*</i> 本次排程数量： </label>
            <InputNumber
              :min="1"
              class="searchInput"
              v-model="dispatchNum"
              onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
            ></InputNumber>
          </div>
          <div class="filter">
            <label> <i>*</i> 批次数： </label>
            <InputNumber
              :min="1"
              class="searchInput"
              v-model="dispatchBatch"
              onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
            ></InputNumber>
          </div>
          <Button
            class="dispatchBtn"
            type="primary"
            size="small"
            @click="dispatch()"
            v-text="$t(1011)"
            >确定</Button
          >
        </div>
        <div style="margin-top: 16px">
          <div class="filter">
            <label>工单号：</label>
            <Input class="searchInput" :value="row.code" 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.draw_number" disabled />
          </div>
          <div class="filter">
            <label>交付时间：</label>
            <Input class="searchInput" :value="row.delivery_time" disabled />
          </div>
        </div>
        <div style="margin-top: 16px">
          <Table
            :max-height="450"
            class="tableClass"
            :data="dispatchTableData"
            :columns="dispatchTableColumns"
          ></Table>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="dispatchModal = false" v-text="$t(1033)">
          取消
        </Button>
        <Button
          size="large"
          type="primary"
          @click="confirmDispatch()"
          :disabled="isLoading"
        >
          确认
        </Button>
      </div>
    </Modal>
    <!-- 终止弹框 -->
    <Modal
      class="newModalClass endModal"
      v-model="endModal"
      :styles="{ width: '1200px' }"
    >
      <p slot="header">
        <span>终止</span>
      </p>
      <div class="modal_body end">
        <div>
          <div class="filter">
            <label>工单号：</label>
            <Input class="searchInput" :value="row.code" 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.install_count" disabled />
          </div>
          <div class="filter">
            <label>未派工数量：</label>
            <Input
              class="searchInput"
              :value="row.install_count - row.scheduled_quantity"
              disabled
            />
          </div>
        </div>
        <div style="margin-top: 16px">
          <Table
            ref="table"
            :data="endTableData"
            :columns="endTableColumns"
            :max-height="450"
            highlight-row
            @on-selection-change="handleSelect"
          ></Table>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="endModal = false" v-text="$t(1033)"
          >取消</Button
        >
        <Button
          @click="confirmEnd()"
          type="primary"
          size="large"
          v-text="$t(900948)"
          >终止</Button
        >
      </div>
    </Modal>
    <!-- 进度弹出框 -->
    <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.code" 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.install_count" disabled />
          </div>
        </div>
        <div style="margin-top: 16px">
          <Table
            :data="progressTableData"
            :columns="progressTableColumns"
            :max-height="450"
          ></Table>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";

export default {
  inject: ["reload"],
  data() {
    return {
      // 防抖
      isLoading: false,
      // 排程数量
      dispatchNum: null,
      // 批次数
      dispatchBatch: null,
      // 工单号
      workOrderNo: "",
      // 产品名称
      productName: "",
      // 订单号
      productionOrderNo: "",
      // 主体表格数据
      tableData: [],
      // 主体表格列字段
      tableColumns: [
        {
          type: "sort",
          title: this.$t(1008),
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 75,
        },
        {
          title: this.$t(100088),
          key: "product_name",
        },
        {
          title: this.$t(100089),
          key: "product_code",
        },
        {
          title: this.$t(900337),
          key: "code",
        },
        {
          title: this.$t(100090),
          key: "draw_number",
        },
        {
          title: this.$t(5500136),
          key: "install_count",
        },
        {
          title: this.$t(950190),
          key: "scheduled_quantity",
        },
        {
          title: this.$t(500100),
          key: "delivery_time",
        },
        {
          title: this.$t(900925),
          key: "days_remaining",
        },
        {
          title: this.$t(200002),
          key: "workorder_status",
          align: "center",
          render: (h, params) => {
            let status, bg;
            if (params.row.workorder_status == 2) {
              status = "未排产";
              bg = "#FF9900";
            } else if (params.row.workorder_status == 3) {
              status = "已派工";
              bg = "#FF5E31";
            } else if (params.row.workorder_status == 4) {
              status = "生产中";
              bg = "#2D8CF0";
            } else if (params.row.workorder_status == 5) {
              status = "已完工";
              bg = "#2CC377";
            } else if (params.row.workorder_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(900950),
          key: "plan_starttime",
          width: 108,
        },
        {
          title: this.$t(900951),
          key: "plan_endtime",
          width: 108,
        },
        {
          title: this.$t(900952),
          key: "actual_completiontime",
          width: 108,
        },
        {
          title: this.$t(600588),
          key: "ok_number",
        },
        {
          title: this.$t(600589),
          key: "nok_number",
        },
        {
          title: this.$t(1950514),
          key: "batches_number",
        },
        {
          title: this.$t(500103),
          render: (h, params) => {
            let rate = params.row.completion_rate;
            return h("div", {
              domProps: {
                innerHTML: `${rate}%`,
              },
            });
          },
        },
      ],
      total: 0,
      page: 1,
      pagesize: 10,
      // 当前选中的行数据
      row: {},
      // 派工弹框是否显示
      dispatchModal: false,
      // 派工弹框中表格数据
      dispatchTableData: [],
      // 派工弹框中表格列字段
      dispatchTableColumns: [
        {
          title: this.$t(900958),
          key: "orderNumber",
          align: "center",
        },
        {
          title: this.$t(811197),
          key: "count",
          align: "center",
        },
      ],
      // 终止弹出框是否显示
      endModal: false,
      // 终止弹出框中表格数据
      endTableData: [],
      // 终止弹出框中表格列字段
      endTableColumns: [
        // {
        //   type: "selection",
        //   width: 50,
        //   align: "center",
        // },
        {
          title: "工令单号",
          key: "jobNo",
        },
        {
          title: "派工人员",
          key: "dispatchBy",
        },
        {
          title: "派工时间",
          key: "dispatchTime",
        },
        {
          title: "状态",
          key: "status",
        },
        {
          title: "已报工数量",
          key: "reportNum",
        },
        {
          title: "剩余数量",
          key: "leftNum",
        },
      ],
      // 终止弹出框已选项目
      selection: [],
      // 进度弹出框是否显示
      progressModal: false,
      // 进度弹出框中表格数据
      progressTableData: [],
      // 进度弹出框中表格列字段
      progressTableColumns: [
        {
          title: this.$t(500006),
          key: "serialNumber",
          width: 66,
        },
        {
          title: this.$t(900967),
          key: "name",
        },
        {
          title: this.$t(6000030),
          key: "description",
        },
        {
          title: this.$t(5500136),
          key: "producted_number",
        },
        {
          title: this.$t(444430),
          key: "job_count",
        },
        {
          title: this.$t(800152),
          key: "ok_number",
        },
        {
          title: this.$t(500102),
          key: "nok_number",
        },
        {
          title: this.$t(444431),
          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: this.$t(200054),
          key: "state",
          align: "center",
        },
      ],
    };
  },
  mounted() {
    // 首次进入组件，查询
    this.search();
    // 格式化表格列字段
    this.tableColumns = this.$time.initTableTitle(this.tableColumns);
    this.endTableColumns = this.$time.initTableTitle(this.endTableColumns);
    this.endTableColumns[0].width = 100;
    this.endTableColumns[0].tooltip = true;
    this.progressTableColumns = this.$time.initTableTitle(
      this.progressTableColumns
    );
  },
  methods: {
    // 获取主体表格数据
    search() {
      // 拿到当前组件实例
      const _this = this;
      // 解构取值
      let {
        workOrderNo,
        productName,
        productionOrderNo,
        page,
        pagesize,
      } = this;
      // 组装请求入参
      let params = {
        ordernumber: productionOrderNo,
        product_name: productName,
        code: workOrderNo,
        page,
        pagesize,
      };
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/GetDataList",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          // 判断下请求是否成功
          if (result.ret == 1) {
            _this.total = result.total;
            _this.page = result.page;
            _this.pagesize = result.pagesize;
            let arr;
            // 如果返回的值为 null undefined 之类的，转为空数组
            arr = result.data ? result.data : [];
            // arr.forEach((item) => {
            //   if (item) {
            //   }
            // });
            _this.tableData = arr;
          } 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;
    },
    // 点击派工按钮，弹出派工弹出框
    add() {
      const _this = this;
      // 解构取到当前选择的行数据
      let { row } = this;
      // 如果当前未选择行
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(9000396));
        return false;
      }
      // 清空派工弹框中输入排程数量及批次数
      this.dispatchNum = null;
      this.dispatchBatch = null;
      // 清空派工表格数据
      this.dispatchTableData = [];
      _this.isLoading = false;
      // 弹出框弹出
      this.dispatchModal = true;
    },
    // 点击弹框内派工按钮，进行一键派工
    dispatch() {
      // 拿到当前组件实例
      const _this = this;
      // 表单必填项验证
      if (!_this.dispatchNum) {
        _this.$Message.error(_this.$t(444422));
        return false;
      }
      if (!_this.dispatchBatch) {
        _this.$Message.error(_this.$t(444423));
        return false;
      }
      if (_this.dispatchBatch > _this.dispatchNum) {
        _this.$Message.error(_this.$t(444453));
        return false;
      }
      // 组装请求参数
      let params = {
        id: _this.row.id,
        num: _this.dispatchBatch,
        total: _this.dispatchNum,
      };
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/GetDispatchDetails",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            if (Array.isArray(data) && data.length) {
              _this.dispatchTableData = data;
            } else {
              _this.dispatchTableData = [];
            }
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 确认派工
    confirmDispatch() {
      const _this = this;
      let data = {
        id: _this.row.id,
        planId: _this.row.planid,
        orders: _this.dispatchTableData,
      };
      _this.isLoading = true;
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/AddSchedule",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success(_this.$t(result.msg));
            _this.dispatchModal = false;
            _this.search();
          } else {
            _this.$Message.error(_this.$t(444447));
          }
        });
    },
    // 点击终止按钮，弹出终止弹出框
    end() {
      const _this = this;
      // 解构取到当前选择的行数据
      let { row } = this;
      // 如果当前未选择行
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(9000396));
        return false;
      }
      let params = {
        code: row.code,
      };
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/GetStopScheduleData",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            // 弹出框弹出
            this.endModal = true;
            let data = result.data;
            let tableData = [];
            if (data && Array.isArray(data) && data.length) {
              data.forEach((v) => {
                tableData.push({
                  // ID
                  id: v.id,
                  // 剩余数量
                  leftNum: v.last_number,
                  // 派工人员
                  dispatchBy: v.name,
                  // 工令单号
                  jobNo: v.orderNumber,
                  // 已报工数量
                  reportNum: v.producted_num,
                  // 状态
                  status: v.state,
                  // 派工时间
                  // dispatchTime: moment(v.time * 1000).format(
                  //   "YYYY-MM-DD HH:mm:ss"
                  // ),
                  dispatchTime: v.time,
                });
              });
            }
            _this.endTableData = tableData;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听终止弹出框中项目多选
    handleSelect(v) {
      let arr = [];
      for (let i = 0; i < v.length; i++) {
        arr.push(v[i].id);
      }
      this.selection = arr;
    },
    // 确定终止
    confirmEnd() {
      const _this = this;
      // let { selection } = this;
      // if (!selection || !selection.length) {
      //   _this.$Message.error(_this.$t(444435));
      //   return false;
      // }
      // let { endTableData } = this;
      // let idArr = endTableData.map((v) => {
      //   return v.id;
      // });
      let { row } = this;

      let params = {
        planId: row.id,
      };
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/StopSchedule",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success(_this.$t(result.msg));
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
          _this.endModal = false;
          _this.reload();
        });
    },
    // 点击查看进度按钮，弹出进度弹出框
    progress() {
      const _this = this;
      // 解构取到当前选择的行数据
      let { row } = this;
      // 如果当前未选择行
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(9000396));
        return false;
      }
      let params = {
        id: _this.row.id,
      };
      _this.axios
        .request({
          url: "cnc/ProductPlanDispatch/GetOrderProgress",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.progressTableData = [];
            if (Array.isArray(data) && data.length) {
              _this.progressTableData = data;
            }
            // 弹出框弹出
            this.progressModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
  },
};
</script>

<style>
.dispatchBtn {
  margin-left: 24px;
}

.dispatchModal .ivu-modal .ivu-modal-body {
  padding: 30px 40px;
}

.endModal .ivu-modal .ivu-modal-body {
  padding: 30px 40px;
}

.progressModal .ivu-modal .ivu-modal-body {
  padding: 30px 40px;
}
</style>
