<template>
  <div class="bg-in-stock" id="deliverySheet">
    <div ref="printId">
      <div class="title">
        <h2 v-if="checkType == 'first'">出库单</h2>
        <h2 v-else>入库单</h2>
      </div>
      <div class="numOrder">
        <barcode :value="barcodeValue"></barcode>
      </div>
      <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" :rules="goodsExchangeAddFormRule"
        label-width="120px" inline class="change-form">
        <el-form-item label="订单编号:" prop="sn" class="change-form-item" v-if="checkType == 'second' && (goodsExchangeAddForm.type == 'SALE_AFTER' || goodsExchangeAddForm.type == 'HAIL_ENTRY')">
          {{ goodsExchangeAddForm.sn }}
        </el-form-item>
        <el-form-item label="入库单编号:" prop="sn" class="change-form-item" v-if="checkType == 'second' && (goodsExchangeAddForm.type == 'OTHER_ENTRY' || goodsExchangeAddForm.type == 'SALE_ENTRY')">
          {{ goodsExchangeAddForm.sn }}
        </el-form-item>
        <el-form-item label="调拨单编号:" prop="sn" class="change-form-item" v-if="checkType == 'second' && goodsExchangeAddForm.type == 'TRANSFER_ENTRY'">
          {{ goodsExchangeAddForm.sn }}
        </el-form-item>
        <el-form-item v-if="checkType == 'first'" label="出库仓库:" class="change-form-item">
          {{ warehouseName(goodsExchangeAddForm.warehouse_id) }}
        </el-form-item>
        <el-form-item v-else label="入库仓库:" class="change-form-item">
          {{ warehouseName(goodsExchangeAddForm.warehouse_id) }}
        </el-form-item>
        <el-form-item label="类型:" prop="type" class="change-form-item">
          {{ warehouseType(goodsExchangeAddForm.type) }}
        </el-form-item>
        <el-form-item label="备注:" prop="memo" class="change-form-item" style="width: 61%">
          <span v-if="checkType == 'first'">{{ goodsExchangeAddForm.notes }}</span>
          <span v-else>{{ goodsExchangeAddForm.memo }}</span>
        </el-form-item>
        <div class="mx">
          <h3>商品明细</h3>
        </div>
        <div style="width: 100%; display: block">
          <el-form-item style="width: 100%">
            <el-table :data="goodsExchangeAddForm.product_list" border :cell-style="{ textAlign: 'center' }"
              row-key="id" :header-cell-style="{ textAlign: 'center' }" class="draggable-table"
              style="width: 100%; margin-top: 20px">
              <el-table-column label="库位号">
                <template slot-scope="scope">
                  <el-popover placement="right" trigger="click" v-if="scope.row.area_stock_list">
                    <div>
                      <p v-for="item in scope.row.area_stock_list" :key="item.id">{{ item.warehouse_area_name }}</p>
                    </div>
                    <span slot="reference" v-if="scope.row.area_stock_list.length !== 0">{{
                      scope.row.area_stock_list[0].warehouse_area_name }}</span>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="商品编号">
                <template slot-scope="scope">
                  {{ scope.row.goods_vo.sn }}
                </template>
              </el-table-column>
              <el-table-column label="商品名称">
                <template slot-scope="scope">
                  {{ scope.row.goods_vo.name }}
                </template>
              </el-table-column>
              <el-table-column label="sku">
                <template slot-scope="scope">
                  <!-- {{ scope.row.bar_code }} -->
                  <span v-if="id">{{ scope.row.product_vo.sku }}</span>
                  <span v-else>{{ scope.row.sku }}</span>
                </template>
              </el-table-column>
              <el-table-column label="序列号">
                <template slot-scope="scope">
                  <div class="sn-code-container">
                    <span v-for="item in scope.row.sn_code_list" :key="item.id">
                      <p>{{ item.sn_code }}</p>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="product_vo.spec_name" label="规格型号" v-if="id">
                <!-- <template slot-scope="scope">
                  {{ scope.row.product_vo.spec_name.join("/") }}
                </template> -->
              </el-table-column>
              <el-table-column prop="spec_name" label="规格型号" v-else>
                <!--  <template slot-scope="scope">
                  {{ scope.row.spec_name.join("/") }}
                </template> -->
              </el-table-column>
              <el-table-column label="单位">
                <template slot-scope="scope">
                  <span v-if="id">{{ scope.row.product_vo.unit }}</span>
                  <span v-else>{{ scope.row.unit }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column label="订单数量"> </el-table-column> -->
              <el-table-column v-if="checkType == 'first'" label="出库数量">
                <template slot-scope="scope">
                  {{ scope.row.out_num }}
                </template>
              </el-table-column>
              <!--  <el-table-column v-else label="入库数量">
                <template slot-scope="scope">
                  {{ scope.row.num }}
                </template>
              </el-table-column> -->
              <el-table-column prop="entry_num" label="已入库数量"
                v-if="(goodsExchangeAddForm.type == 'TRANSFER_ENTRY' || goodsExchangeAddForm.type == 'HAIL_ENTRY' || goodsExchangeAddForm.type == 'SALE_AFTER') && checkType !== 'first'"></el-table-column>
              <el-table-column prop="not_entry_num" label="未入库数量"
                v-if="(goodsExchangeAddForm.type == 'TRANSFER_ENTRY' || goodsExchangeAddForm.type == 'HAIL_ENTRY' || goodsExchangeAddForm.type == 'SALE_AFTER') && checkType !== 'first'">
              </el-table-column>
              <el-table-column label="订单数量"
                v-if="(goodsExchangeAddForm.type == 'HAIL_ENTRY' || goodsExchangeAddForm.type == 'SALE_AFTER' || goodsExchangeAddForm.type == 'TRANSFER_ENTRY') && checkType !== 'first'">
                <template slot-scope="scope">
                  {{ scope.row.order_num }}
                </template>
              </el-table-column>
              <el-table-column label="可用库存">
                <template slot-scope="scope">
                  {{ scope.row.usable_stock }}
                </template>
              </el-table-column>
              <el-table-column label="实际库存">
                <template slot-scope="scope">
                  {{ scope.row.actual_stock }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="差异">
                <template slot-scope="scope">
                  入库减去库存
                  {{ scope.row.num - scope.row.already_num || 0 }}
                </template>
              </el-table-column>-->
              <el-table-column label="操作" v-if="false">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="
                    goodsExchangeAddForm.product_list.splice(scope.$index, 1)
                    ">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <el-button @click="handlePrintGoodsLend">打印</el-button>
      <el-button @click="$router.back()">返回</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Foundation, RegExp } from "~/ui-utils";
import * as API_GoodsExchange from "@/api/goodsExchange";
import * as API_Setting from "@/api/setting";
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_Erp from "@/api/erp";
import * as API_Auth from "@/api/auth";
import Print from "print-js";
import html2canvas from "html2canvas";
import Sortable from "sortablejs";
export default {
  name: "goodsExchangeAdd",
  data() {
    const checkPrice = (rule, value, callback) => {
      if (!value && value !== 0) {
        return callback(new Error("换货金额不能为空"));
      } else if (!RegExp.money.test(value)) {
        callback(new Error("请输入正整数或者两位小数"));
      } else if (parseFloat(value) > 99999999) {
        callback(new Error("换货金额设置超过上限值"));
      } else {
        callback();
      }
    };
    return {
      typeList: [
        /* {
          real_name: "采购入库",
          id: "采购入库",
        },
        {
          real_name: "租赁返回",
          id: "租赁返回",
        },
        {
          real_name: "其他入库",
          id: "其他入库",
        }, */
      ],
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      orderList: [],
      id: "",
      type: "",
      /** 出库单表单*/
      goodsExchangeAddForm: {
        change_amount: 0,
        change_list: [],
        return_list: [],
        product_list: [],
      },
      /** 校验规则 */
      goodsExchangeAddFormRule: {
        // change_amount: [
        //   { required: true, message: '请输入换货金额', trigger: 'blur' },
        //   { validator: checkPrice, trigger: 'blur' }
        // ]
      },
      warehouseProduct: null,
      scanDialogVisible: false,
      scanGoodsForm: {},
      routeName: "",
      // 出库商品明细
      goodsVisible: false,
      goodsData: [],
      // 暂存已勾选商品
      goodsList: [],
      // 条形码
      barcodeValue: "",
      // 类型
      checkType: "",
      warehouseList: [],
    };
  },
  mounted() {
    // this.routeName = this.$route.name;
    this.id = this.$route.params.id;
    this.checkType = this.$route.params.type;
    this.GET_WarehouseList();
    this.GET_DeptList();
    this.GET_goodsExchangeAddDetail();
    this.rowDrop();
  },
  watch: {
    // $route: {
    //   immediate: true,
    // },
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    /* 获取类型 */
    warehouseType(val) {
      let name = "";
      this.typeList.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    //获取仓库名称
    warehouseName(val) {
      let name = "";
      this.warehouseList.map((el) => {
        if (el.id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    /* 仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        ".draggable-table .el-table__body-wrapper tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        animation: 300,
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.goodsExchangeAddForm.product_list.splice(
            oldIndex,
            1
          )[0];
          _this.goodsExchangeAddForm.product_list.splice(newIndex, 0, currRow);
        },
      });
    },
    // 打印功能
    printIng() { },
    /** 出入库单 */
    handlePrintGoodsLend() {
      // Print({
      //   printable: 'deliverySheet',
      //   type: 'html',
      //   targetStyles: ['*'],
      //   ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      // })
      const printContent = this.$refs.printId;
      // 获取dom 宽度 高度
      const width = printContent.clientWidth;
      const height = printContent.clientHeight;
      // 创建一个canvas节点
      const canvas = document.createElement("canvas");

      const scale = 1; // 定义任意放大倍数，支持小数；越大，图片清晰度越高，生成图片越慢。
      canvas.width = width * scale; // 定义canvas 宽度 * 缩放
      canvas.height = height * scale; // 定义canvas高度 *缩放
      canvas.style.width = width * scale + "px";
      canvas.style.height = height * scale + "px";
      canvas.getContext("2d").scale(scale, scale); // 获取context,设置scale

      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动轴滚动的长度
      const scrollLeft =
        document.documentElement.scrollLeft || document.body.scrollLeft; // 获取水平滚动轴的长度

      html2canvas(printContent, {
        canvas,
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
        scrollX: -scrollLeft, // 解决水平偏移问题，防止打印的内容不全
        scrollY: -scrollTop,
      })
        .then((canvas) => {
          const url = canvas.toDataURL("image/png");
          printJS({
            printable: url,
            type: "image",
            documentTitle: "", // 标题
            style: "@page{size:auto;margin: 0cm 1cm 0cm 1cm;}", // 去除页眉页脚
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    toSearch() {
      API_GoodsExchange.getGoodsInfo({
        barcode: this.scanGoodsForm.bar_code,
      }).then((res) => {
        console.log(res);
      });
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
        this.deptListAll = response;
      });
    },
    /** 获取详情页面数据  getGoodsWarehouseOut*/
    GET_goodsExchangeAddDetail() {
      this.$nextTick(() => {
        if (this.checkType == "first") {
          API_GoodsExchange.getGoodsWarehouseOut(this.id).then((response) => {
            API_Setting.getPage({ dictType: "out_warehouse_type" }).then(
              (res) => {
                this.typeList = res.data;
              }
            );
            this.goodsExchangeAddForm = response;
            this.barcodeValue = response.sn;
            this.goodsExchangeAddForm.distribution_name = response.staff_name;
            this.goodsExchangeAddForm.product_list =
              response.product_list; /* .map(
              (item) => {
                item.name = item.goods_vo.name;
                item.sn = item.goods_vo.sn;
                item.sn_code = item.goods_vo.sn_code;
                item.bar_code = item.goods_vo.bar_code;
                item.entry_price = item.amount;
                item.goods_specification = item.specification;
                item.goods_unit = item.goods_vo.goods_unit;
                item.warehouse_entry_sn = item.stock_sn;
                item.usable_stock = item.goods_vo.usable_stock;
                return item;
              }
            ); */
          });
        } else {
          API_GoodsExchange.getGoodsExchangeInfo(this.id).then((response) => {
            API_Setting.getPage({ dictType: "warehouse_entry_type" }).then(
              (res) => {
                this.typeList = res.data;
              }
            );
            this.goodsExchangeAddForm = response;
            this.barcodeValue = response.sn;
            this.goodsExchangeAddForm.distribution_name = response.staff_name;
            this.goodsExchangeAddForm.product_list = response.product_list/* .map(
              (item) => {
                item.name = item.goods_do.name;
                item.sn = item.goods_do.sn;
                item.sn_code = item.goods_do.sn_code;
                item.bar_code = item.goods_do.bar_code;
                item.entry_price = item.amount;
                item.goods_specification = item.specification;
                item.goods_unit = item.goods_do.goods_unit;
                item.warehouse_entry_sn = item.stock_sn;
                item.usable_stock = item.goods_do.usable_stock;
                return item;
              }
            ); */
          });
        }
      });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
@media print {
  .barcode-container {
    border: none;
  }
}

/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
  width: 100%;

  .button {
    margin-left: 10px;
  }
}

.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;

  .change-form-item {
    width: 49%;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }

  /deep/ {
    .el-form-item__content {
      flex: 1;
      width: 100%;
    }

    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;

  .title {
    text-align: center;
  }

  .numOrder {
    display: flex;
    justify-content: center;
  }
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

.sn-code-container {
  max-height: 100px;
  /* 设置最大高度，超过这个高度将显示滚动条 */
  overflow-y: auto;
  /* 垂直方向上溢出时显示滚动条 */
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
