<template>
  <div class="bg-in-stock">
    <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" :rules="goodsExchangeAddFormRule"
      label-width="160px" inline class="change-form">
      <el-form-item prop="warehouse_id" label="出库仓库" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.warehouse_id" :disabled="type === 'detail' || type === 'audit'">
          <!-- @change="handleChangeWareHouse" -->
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.type" filterable allow-create clearable default-first-option
          :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"
            :disabled="item.value == 'SALE_OUT' || item.value == 'HAIL_OUT' || item.value == 'DAMAGE_OUT' || item.value == 'TRANSFER_OUT'" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="订单" prop="order_sn" class="change-form-item">
        <el-input
          v-model="goodsExchangeAddForm.order_list[0].order_sn"
          :disabled="type === 'detail' || type === 'audit'"
          ref="order"
        >
        </el-input>
      </el-form-item> -->
      <el-form-item label="备注" prop="notes" class="change-form-item" style="width: 61%">
        <el-input style="flex: 1" v-model="goodsExchangeAddForm.notes" type="textarea"
          :disabled="type === 'detail' || type === 'audit'" maxlength="250" :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入"></el-input>
      </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.return_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="入库单号">
              <template slot-scope="scope">
                {{ scope.row.stock_sn }}
              </template>
</el-table-column>
<el-table-column label="商品编号">
  <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
</el-table-column>
<el-table-column label="商品名称">
  <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
</el-table-column>
<el-table-column label="规格型号">
  <template slot-scope="scope">
                {{ scope.row.specification }}
              </template>
</el-table-column>
<el-table-column label="单位">
  <template slot-scope="scope">
                {{ scope.row.unit }}
              </template>
</el-table-column>
<el-table-column label="单价">
  <template slot-scope="scope">
                ¥{{ scope.row.amount }}
              </template>
</el-table-column>
<el-table-column label="数量">
  <template slot-scope="scope">
                <el-input v-model="scope.row.num" type="number" :min="0" :maxlength="20"
                  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
</el-table-column>
<el-table-column label="金额">
  <template slot-scope="scope">
                {{ scope.row.num * scope.row.amount || 0 }}
              </template>
</el-table-column>
<el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
  <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="goodsExchangeAddForm.return_list.splice(scope.$index, 1)">删除</el-button>
              </template>
</el-table-column>
</el-table>
</el-form-item>
</div> -->
      <div class="mx">
        <h3>商品明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail' && type !== 'audit'"
          @click="scanCode">扫码出库</el-button>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail' && type !== 'audit'"
          @click="handleSelectWarehouseEntryBatch">选择</el-button>
      </div>
      <div style="width: 100%; display: block">
        <el-form-item style="width: 100%">
          <el-table :data="goodsExchangeAddForm.product_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" 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">
                <span v-if="id">{{ scope.row.goods_vo.sn }}</span>
                <span v-else>{{ scope.row.goods_vo.sn }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                <span v-if="id">{{ scope.row.goods_vo.name }}</span>
                <span v-else>{{ scope.row.goods_vo.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="sku">
              <template slot-scope="scope">
                <span v-if="id">{{ scope.row.product_vo.sku }}</span>
                <span v-else>{{ scope.row.product_vo.sku }}</span>
              </template>
            </el-table-column>
            <el-table-column label="序列号" v-if="sn_code_list">
              <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="product_vo.spec_name" label="规格型号" v-else>
              <!--  <template slot-scope="scope">
                {{ scope.row.product_vo.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.product_vo.unit }}</span>
              </template>
            </el-table-column>
            <el-table-column label="出库数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.out_num" type="number" :min="0" :maxlength="20"
                  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="订单数量">
              <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.usable_stock - scope.row.out_num || 0 }}
              </template>
            </el-table-column> -->
            <el-table-column width="200" label="操作" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <!-- <el-button
                  size="mini"
                  @click="addSnCode(scope.row,scope.$index)"
                  >添加序列号</el-button
                > -->
                <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 class="footer">
      <!-- <el-button v-if="type === 'audit'" type="primary" @click="handlePassGoodsExchange()">审核通过
      </el-button>
      <el-button v-if="type === 'audit'" type="danger" @click="dialogVisible = true">审核驳回
      </el-button> -->
      <el-button v-if="type !== 'audit' && type !== 'detail' && checkPermission(['warehouseOut2:add'])" type="primary"
        @click="saveGoodsExchangeAddForm">保存
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail' && checkPermission(['warehouseOut:update'])" type="primary"
        @click="submitGoodsExchangeAddForm">出库
      </el-button>
      <el-button @click="printIng" v-if="type == 'audit'">打印</el-button>
      <el-button @click="toBack()">返回</el-button>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" label-width="120px" inline style="width: 900px">
        <el-form-item label="驳回原因" prop="reject_reason">
          <el-input v-model="goodsExchangeAddForm.reject_reason" type="textarea" :minlength="0"
            :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsExchange()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="扫码出库" :visible.sync="scanDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form ref="scanGoodsForm" :model="scanGoodsForm" label-width="120px" inline>
        <el-form-item label="sku" prop="bar_code">
          <el-input v-model="scanGoodsForm.bar_code" ref="input" @keyup.enter.native="toSearch()" :minlength="0"
            :maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="序列号" prop="sn_code">
          <el-input v-model="sn_code" ref="sn_input" @keyup.enter.native="toSnCode()" :minlength="0"
            :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsExchange()">确 定</el-button> -->
      </span>
    </el-dialog>
    <!--   <el-dialog
      title="序列号"
      :visible.sync="snCodeVisible"
      width="30%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="scanGoodsForm"
        :model="scanGoodsForm"
        label-width="120px"
        inline
      >
        <el-form-item label="序列号" prop="sn_code">
          <el-input
            v-model="sn_code"
            @keyup.enter.native="toSnCode()"
            :minlength="0"
            :maxlength="100"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-dialog> -->
    <!-- <el-dialog
      title="出库商品"
      :visible.sync="goodsVisible"
      width="1000px"
      @close="closeGoosData"
    >
      <el-table
        :data="goodsData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="商品编号"> </el-table-column>
        <el-table-column prop="bar_code" label="商品条码"> </el-table-column>
        <el-table-column prop="sn_code" label="序列号"> </el-table-column>
        <el-table-column prop="name" label="商品名称"> </el-table-column>
        <el-table-column prop="goods_style" label="规格型号"> </el-table-column>
        <el-table-column prop="goods_unit" label="单位"> </el-table-column>
        <el-table-column prop="product_list.stock_num" label="库存数量">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeGoosData">取 消</el-button>
        <el-button type="primary" @click="submitGoosData()">确 定</el-button>
      </span>
    </el-dialog> -->
  </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";
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: "借用出库",
        },
        {
          real_name: "其他出库",
          id: "其他出库",
        }, */
      ],
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      orderList: [],
      id: "",
      type: "",
      /** 出库单表单*/
      goodsExchangeAddForm: {
        order_list: [
          {
            order_id: "1752156400898293761",
            order_item_list: [
              {
                batch_list: [
                  {
                    batch_id: 0,
                    batch_sn: "",
                    out_num: 0,
                    remain_num: 0,
                    warehouse_entry_sn: "",
                  },
                ],
                num: 0,
                order_item_id: 0,
                product_id: 0,
                product_name: "string",
                product_sn: "string",
                product_specification: "string",
                product_unit: "string",
              },
            ],
            order_sn: "",
          },
        ],
        product_list: [],
        type: "",
      },
      /** 校验规则 */
      goodsExchangeAddFormRule: {
        warehouse_id: [
          { required: true, message: "请选择出库仓库", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择出库类型", trigger: "change" },
        ],
        // change_amount: [
        //   { required: true, message: '请输入换货金额', trigger: 'blur' },
        //   { validator: checkPrice, trigger: 'blur' }
        // ]
      },
      warehouseProduct: null,
      scanDialogVisible: false,
      scanGoodsForm: {},
      routeName: "",
      //出入库
      sttorageType: "",
      // 出库商品明细
      goodsVisible: false,
      goodsData: [],
      // 暂存已勾选商品
      goodsList: [],
      product_list: [],
      snCodeVisible: false,
      sn_code: "",
      sku: "",
      sn_code_list: [],
      index: "",
    };
  },
  mounted() {
    this.routeName = this.$route.name;
    this.sttorageType = this.$route.params.type;
    this.GET_WarehouseList();
    this.GET_DeptList();
    this.outType();
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === "goodsExchangeEdit") {
          this.type = "edit";
        } else if (this.$route.name === "goodsExchangeAudit") {
          this.type = "audit";
        } else if (this.$route.name === "goodsExchangeReturn") {
          this.type = "return";
        } else if (this.$route.name === "goodsExchangeAdd") {
          this.type = "add";
          /* this.goodsExchangeAddForm = {
            change_amount: 0,
            change_list: [],
            return_list: [],
            product_list: [],
            handled_by_id: this.user.uid,
            dept_id: this.user.dept_id,
          }; */
          // this.goodsExchangeAddForm.handled_by_id = this.user.uid
          // this.goodsExchangeAddForm.dept_id = this.user.dept_id
          this.GET_WarehouseList({ dept_id: this.user.dept_id });
          this.$set(
            this.goodsExchangeAddForm,
            "change_time",
            new Date().getTime()
          );
        } else if (this.$route.name === "goodsExchangeDetail") {
          this.type = "detail";
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id;
          this.GET_goodsExchangeAddDetail();
        }
        this.GET_AdministratorList();
      },
    },
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    /* 返回出入明细 */
    toBack() {
      this.$router.push({
        name: "goodsExchange",
        params: { type: "first" },
      });
    },
    //扫序列号goodsExchangeAddForm.product_list[this.index].sn_code_list
    async toSnCode() {
      if (this.sku == '') return this.$message.error('请录入正确的sku')
      await API_GoodsExchange.getSnCode("out", this.sku, this.sn_code.replace(/\s+/g, '')).then(async (res) => {
        this.sn_code = "";
        // 假设res是一个对象，我们根据res的某个属性（如sn）来检查重复
        let exists = this.goodsExchangeAddForm.product_list[
          this.index
        ].sn_code_list.find(
          (item) => item.sn_code === res.sn_code && item.sku === res.sku
        );
        if (!exists) {
          if (this.id) {
            await API_GoodsExchange.skuRedis({
              send_order_id: this.id, item_id: this.goodsExchangeAddForm.product_list[
                this.index
              ].id, sku: res
            }).then(response => {
              this.goodsExchangeAddForm.product_list[this.index].sn_code_list.push(
                res
              );
            })
          } else {
            this.goodsExchangeAddForm.product_list[this.index].sn_code_list.push(
              res
            );
          }

          /* this.goodsExchangeAddForm.product_list[this.index].sn_code_list.push(
            res
          ); */
        }
        this.goodsExchangeAddForm.product_list[this.index].out_num = this.goodsExchangeAddForm.product_list[this.index].sn_code_list.length
        console.log(this.goodsExchangeAddForm.product_list);
        this.scanGoodsForm.bar_code = "";
        this.$nextTick(() => {
          this.$refs.input.focus();
        });
      });
    },
    addSnCode(row, index) {
      this.sku = row.product_vo.sku;
      this.index = index;
      this.snCodeVisible = true;
    },
    //获取出库类型字典
    outType() {
      API_Setting.getPage({ dictType: "out_warehouse_type" }).then((res) => {
        this.typeList = res.data
        /* .filter((el) => {
          if (el.value !== "SALE_OUT" && el.value !== "HAIL_OUT") {
            return el;
          }
        }); */
      });
    },
    /*//商品对应字段
     handleSelectionChange(val) {
      this.goodsList = val.map((el) => {
        el.product_id = el.id;
        el.goods_id = el.id;
        el.product_name = el.name;
        el.product_sn = el.sn;
        el.product_specification = el.goods_style;
        el.batch_list =
          this.goodsExchangeAddForm.order_list[0].order_item_list[0].batch_list;
        return el;
      });
    },
    // 保存已选商品
    submitGoosData() {
        if (this.goodsList.length >= 1) {
          this.goodsExchangeAddForm.order_list[0].order_item_list =
            this.goodsList;
          this.product_list = this.goodsList;
          this.goodsVisible = false;
        } else {
          this.$message.error("请选择商品信息");
        }
      },
      // 关闭商品明细
      closeGoosData() {
        this.goodsVisible = false;
      },*/
    // 打印功能
    printIng() { },
    /* 出库扫码 */
    toSearch() {
      API_GoodsExchange.getProduct(
        this.goodsExchangeAddForm.warehouse_id,
        this.scanGoodsForm.bar_code.replace(/\s+/g, '')
      ).then((res) => {
        res.sn_code_list = []
        this.sku = res.product_vo.sku;
        // 查找当前商品是否已存在于列表中
        const indexs = this.goodsExchangeAddForm.product_list.findIndex((el) => {
          console.log("Comparing with:", el);
          return (
            el.goods_id === res.goods_id &&
            el.product_id === res.product_id &&
            el.product_vo.sku === res.product_vo.sku
          );
        });
        // 如果商品不存在，则添加到列表
        if (indexs === -1) {
          this.index = this.goodsExchangeAddForm.product_list.length
          this.goodsExchangeAddForm.product_list.push(res);
        } else {
          this.index = indexs
        }
        if (res.product_vo.have_sn) {
          this.$nextTick(() => {
            this.$refs.sn_input.focus();
          });
        } else {
          this.goodsExchangeAddForm.product_list[this.index].num += 1
          // this.scanDialogVisible = false;
        }
      });
    },
    // 扫码出库
    scanCode() {
      if (!this.goodsExchangeAddForm.warehouse_id) {
        this.$message.error("请先选择仓库！");
        return;
      }
      this.scanDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    /** 清除已选商品明细
    cleanGoodsList() {
      // 切换部门或仓库需要清除已选对应仓库下的商品数据 change_list
      this.goodsExchangeAddForm.order_list[0].order_item_list = [];
      this.product_list = [];
    },
    changewarehouseList(e) {
      this.$set(this.goodsExchangeAddForm, "warehouse_id", "");
      this.GET_WarehouseList({ dept_id: e });
      this.cleanGoodsList();
    },
    //审核-通过
    handlePassGoodsExchange() {
      if (this.goodsExchangeAddForm.check_amount_same === false) {
        this.$confirm(this.goodsExchangeAddForm.diff_amount_message, "提示", {
          type: "warning",
        })
          .then(() => {
            this.$confirm("确定通过吗？", "提示", { type: "warning" })
              .then(() => {
                API_GoodsExchange.auditGoodsExchange(this.id, {
                  status: "PASS",
                }).then(() => {
                  this.$message.success("已通过！");
                  const { callback } = this.$route.params;
                  if (typeof callback === "function") callback();
                  this.$store.dispatch("delCurrentViews", {
                    view: this.$route,
                    $router: this.$router,
                  });
                  this.$router.push({ name: "goodsExchange" });
                });
              })
              .catch(() => {});
          })
          .catch(() => {});
      } else {
        this.$confirm("确定通过吗？", "提示", { type: "warning" })
          .then(() => {
            API_GoodsExchange.auditGoodsExchange(this.id, {
              status: "PASS",
            }).then(() => {
              this.$message.success("已通过！");
              const { callback } = this.$route.params;
              if (typeof callback === "function") callback();
              this.$store.dispatch("delCurrentViews", {
                view: this.$route,
                $router: this.$router,
              });
              this.$router.push({ name: "goodsExchange" });
            });
          })
          .catch(() => {});
      }
    },
    // 审核-拒绝
    handleRejectGoodsExchange() {
      this.$confirm("确定拒绝吗？", "提示", { type: "warning" })
        .then(() => {
          API_GoodsExchange.auditGoodsExchange(this.id, {
            status: "REJECT",
            reject_reason: this.goodsExchangeAddForm.reject_reason,
          }).then(() => {
            this.$message.success("已拒绝！");
            this.dialogVisible = false;
            const { callback } = this.$route.params;
            if (typeof callback === "function") callback();
            this.$store.dispatch("delCurrentViews", {
              view: this.$route,
              $router: this.$router,
            });
            this.$router.push({ name: "goodsExchange" });
          });
        })
        .catch(() => {});
    },*/
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
    //保存
    saveGoodsExchangeAddForm() {
      this.$refs["goodsExchangeAddForm"].validate((valid) => {
        if (valid) {
          const { id } = this.goodsExchangeAddForm;
          const params = this.MixinClone(this.goodsExchangeAddForm);
          //保存类型
          params.save_or_submit = "save";
          params.warehouse_consignee_id = this.deptListAll.id;
          params.out_time = Date.parse(new Date());
          params.staff_name = this.goodsExchangeAddForm.distribution_name;
          if (params.warehouse_id) {
            params.warehouse_name = this.warehouseList.find(
              (ware) => ware.id === params.warehouse_id
            ).name;
          }
          if (params.handled_by_id) {
            params.handled_by = this.adminList.find(
              (admin) => admin.id === params.handled_by_id
            ).real_name;
          }
          params.change_time = Math.floor(params.change_time / 1000);

          if (!this.goodsExchangeAddForm.product_list.length) {
            return;
          }
          if (params.type == 'OTHER_OUT' || params.type == 'BORROW_OUT') {
            const isStockSufficient = params.product_list.map((el) => {
              if (el.out_num > el.usable_stock) {
                this.$message.error("该商品库存不足！");
                return false
              }
              return true
            });
            if (!isStockSufficient) {
              return;
            }
          }
          if (this.$route.name === "goodsExchangeEdit") {
            API_GoodsExchange.editWarehouseOut(id, params).then((response) => {
              this.$message.success("修改成功！");
              const { callback } = this.$route.params;
              if (typeof callback === "function") callback();
              this.$store.dispatch("delCurrentViews", {
                view: this.$route,
                $router: this.$router,
              });
              this.$router.push({ name: "goodsExchange" });
            });
          } else if (this.$route.name === "goodsExchangeAdd") {
            // 新增入库
            params.product_list.map(el => {
              el.product_stock_id = el.id
              el.id = ''
            })
            API_GoodsExchange.warehouseOut(params).then(() => {
              this.$message.success("添加成功！");
              const { callback } = this.$route.params;
              if (typeof callback === "function") callback();
              this.$store.dispatch("delCurrentViews", {
                view: this.$route,
                $router: this.$router,
              });
              this.$router.push({ name: "goodsExchange" });
            });
          }
        }
      });
    },
    //出库
    submitGoodsExchangeAddForm() {
      this.$refs["goodsExchangeAddForm"].validate((valid) => {
        if (valid) {
          const { id } = this.goodsExchangeAddForm;
          const params = this.MixinClone(this.goodsExchangeAddForm);
          //保存类型
          params.save_or_submit = "submit";
          params.warehouse_consignee_id = this.deptListAll.id;
          params.out_time = Date.parse(new Date());
          params.staff_name = this.goodsExchangeAddForm.distribution_name;
          if (params.warehouse_id) {
            params.warehouse_name = this.warehouseList.find(
              (ware) => ware.id === params.warehouse_id
            ).name;
          }
          if (params.handled_by_id) {
            params.handled_by = this.adminList.find(
              (admin) => admin.id === params.handled_by_id
            ).real_name;
          }
          params.change_time = Math.floor(params.change_time / 1000);
          if (!this.goodsExchangeAddForm.product_list.length) {
            this.$message.error("请选择商品！");
            return;
          }
          if (params.type == 'OTHER_OUT' || params.type == 'BORROW_OUT') {
            const isStockSufficient = params.product_list.map((el) => {
              if (el.out_num > el.usable_stock) {
                this.$message.error("该商品库存不足！");
                return false
              }
              return true
            });
            if (!isStockSufficient) {
              return;
            }
          }
          if (this.$route.name === "goodsExchangeEdit") {
            API_GoodsExchange.editWarehouseOut(id, params).then((response) => {
              this.$message.success("修改成功！");
              const { callback } = this.$route.params;
              if (typeof callback === "function") callback();
              this.$store.dispatch("delCurrentViews", {
                view: this.$route,
                $router: this.$router,
              });
              this.$router.push({ name: "goodsExchange" });
            });
          } else if (this.$route.name === "goodsExchangeAdd") {
            params.product_list.map(el => {
              el.product_stock_id = el.id
              el.id = ''
            })
            // 新增入库
            API_GoodsExchange.warehouseOut(params).then(() => {
              this.$message.success("添加成功！");
              const { callback } = this.$route.params;
              if (typeof callback === "function") callback();
              this.$store.dispatch("delCurrentViews", {
                view: this.$route,
                $router: this.$router,
              });
              this.$router.push({ name: "goodsExchange" });
            });
          }
        }
      });
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      /*   API_GoodsExchange.getProductStock().then((res) => {
        this.goodsData = res.data;
        this.goodsVisible = true;
      });*/
      if (!this.goodsExchangeAddForm.warehouse_id) {
        this.$message.error("请先选择仓库！");
        return;
      }
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: `/admin/erp/warehouseOut/getGoodByWarehouse/${this.goodsExchangeAddForm.warehouse_id}`,
        warehouseList: this.warehouseList,
        //change_list
        selectedIds: this.id
          ? this.goodsExchangeAddForm.product_list &&
          this.goodsExchangeAddForm.product_list.map((item) => item.id)
          : this.goodsExchangeAddForm.product_list.map((item) => item.id),
        purchasePlanApiParams: {
          warehouse_id: this.goodsExchangeAddForm.warehouse_id,
        },
      });
      goodsData.purchasePlans.map(el => { el.sn_code_list = [] })
      this.goodsExchangeAddForm.warehouse_id = goodsData.warehouse_id;
      this.goodsExchangeAddForm.product_list = goodsData.purchasePlans;
      console.log(this.goodsExchangeAddForm.product_list);/*.map(
        (item) => {
          //
           item.amount = item.entry_price;
          item.product_sn = item.product_sn;
          item.product_name = item.product_name;
          item.specification = item.product_specification;
          item.product_id = item.product_id;
          item.unit = item.product_unit;
          item.stock_sn = item.warehouse_entry_sn;
          item.stock_id = item.warehouse_entry_id;
          item.stock_batch_sn = item.sn;
          item.stock_batch_id = item.id;
          item.cost_price = item.product_cost_price;
          item.goods_id=item.id
          return item;
        }
      );*/
      this.goodsExchangeAddForm.change_amount =
        this.goodsExchangeAddForm.product_list.reduce(
          (sum, obj) => sum + obj.entry_price,
          0
        );
    },
    /** 选择订单编号 */
    async handleSelectOrderSn() {
      const orders = await this.$EnPickerOrder({
        orderApi: "admin/erp/order",
        selectedIds: [this.goodsExchangeAddForm.order_sn],
        limit: 1,
      });
      this.$set(
        this.goodsExchangeAddForm,
        "distribution_name",
        orders[0].distribution_name
      );
      const orderIds = orders.map((v) => v.sn);
      this.$set(this.goodsExchangeAddForm, "order_sn", orderIds.join(","));
      this.GET_WarehouseOutProduct();
    },
    /** 获取出库单商品明细 */
    async GET_WarehouseOutProduct() {
      const res = await API_Erp.getWarehouseOutProduct({
        order_sn: this.goodsExchangeAddForm.order_sn,
      });
      this.goodsExchangeAddForm.return_list = res.data.map((item) => {
        item.amount = item.product_price;
        item.product_sn = item.product_sn;
        item.product_name = item.product_name;
        item.specification = item.product_specification;
        item.product_id = item.product_id;
        item.unit = item.product_unit;
        item.out_num = item.return_num;
        item.stock_sn = item.warehouse_entry_sn;
        item.cost_price = item.product_cost_price;
        return item;
      });
    },
    /** 获取仓库 */
    GET_DeptList() {
      API_GoodsExchange.getInfo().then((response) => {
        this.deptListAll = response;
        this.deptListAll.password = "";
      });
    },
    /** 切换仓库 */
    handleChangeWareHouse(val) {
      //this.goodsExchangeAddForm.product_list = []change_list
    },
    /** 获取详情页面数据 */
    GET_goodsExchangeAddDetail() {
      this.$nextTick(() => {
        API_GoodsExchange.getGoodsWarehouseOut(this.id).then((response) => {
          this.goodsExchangeAddForm = response;
          this.GET_WarehouseList({ dept_id: response.warehouse_id });
          this.goodsExchangeAddForm.change_time = Math.floor(
            this.goodsExchangeAddForm.change_time * 1000
          );
          /* 获取缓存数据 */

          response.product_list.map(el => {
            el.order_num = el.out_num
            el.out_num = 0
            if (!el.sn_code_list) {
              el.sn_code_list = []
            } else {
              el.out_num = el.sn_code_list
            }
          })
          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.product_specification = item.specification;
              item.product_unit = item.unit;
              item.warehouse_entry_sn = item.stock_sn;
              item.usable_stock=item.goods_vo.usable_stock
            return item;
          });
         this.goodsExchangeAddForm.return_list = response.return_list.map(
            (item) => {
              item.product_price = item.amount;
              item.product_specification = item.specification;
              item.product_unit = item.unit;
              item.return_num = item.out_num;
              item.warehouse_entry_sn = item.stock_sn;
              return item;
            }
          ); */
          // this.GET_WarehouseOutProduct()
        });
      });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.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: 30%;
    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;
}

.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>
