<template>
  <div class="bg-in-stock">
    <el-form ref="GoodsTransferForm" :model="GoodsTransferForm" label-width="120px" :rules="GoodsTransferFormRule"
      inline>
      <h3>调拨单</h3>
      <el-form-item label="调拨时间" prop="transfer_time" class="change-form-item">
        <span v-if="type === 'detail'">{{ GoodsTransferForm.transfer_time }}</span>
        <el-date-picker v-else v-model="GoodsTransferForm.transfer_time" value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime" :disabled="type === 'detail' || type === 'audit' || type === 'check'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="out_warehouse_id" label="调出仓库">
        <span v-if="type === 'detail'">{{getWarehouse(GoodsTransferForm.out_warehouse_id)  }}</span>
        <el-select v-else @change="cleanGoodsList" v-model="GoodsTransferForm.out_warehouse_id"
          :disabled="type === 'detail'">
          <el-option v-for="item in WarehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="in_warehouse_id" label="调入仓库">
        <span v-if="type === 'detail'">{{getWarehouse(GoodsTransferForm.in_warehouse_id)  }}</span>
        <el-select v-else v-model="GoodsTransferForm.in_warehouse_id" :disabled="type === 'detail'">
          <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="send_type">
        <span v-if="type === 'detail'">{{ getdeliveryType(GoodsTransferForm.send_type) }}</span>
        <el-select v-else v-model="GoodsTransferForm.send_type" clearable :disabled="type === 'detail'">
          <el-option v-for="item in deliveryTypeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <span v-if="type === 'detail'">{{ GoodsTransferForm.remark }}</span>
        <el-input v-else :disabled="type === 'detail'" type="textarea" :rows="2" placeholder="请输入内容"
          v-model="GoodsTransferForm.remark">
        </el-input>
      </el-form-item>
      <div class="mx">
        <h3>商品明细</h3>
        <!-- <el-button
          class="button"
          size="mini"
          type="primary"
          v-if="type !== 'detail'"
          >扫码出库</el-button
        > -->
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail'"
          @click="handleSelectWarehouseEntryBatch">选择</el-button>
      </div>
      <div style="display: block">
        <el-table :data="GoodsTransferForm.product_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }" style="width: 85%; margin-top: 20px">
          <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="序列号">
            <template slot-scope="scope">
              <span v-if="!id"> {{ scope.row.product_vo.sn_code }}</span>
              <span v-else> {{ scope.row.product_vo.sn_code }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="product_vo.spec_name" label="规格型号">
            <!-- <template slot-scope="scope">
              <span v-if="!id">{{
                scope.row.product_vo.spec_name.join("/")
              }}</span>
              <span v-else>{{ scope.row.product_vo.spec_name.join("/") }}</span>
            </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">
              <span v-if="!id">{{ scope.row.usable_stock }}</span>
              <span v-else>{{ scope.row.use_able_num }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调拨数量">
            <template slot-scope="scope">
              <span v-if="type === 'detail'">{{ scope.row.num }}</span>
              <el-input v-else v-model="scope.row.num" type="number" :min="0" :maxlength="20" :disabled="type === 'detail' || type === 'audit' || type === 'check'
                "></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="type !== 'detail'">
            <template slot-scope="scope">
              <el-button size="mini" type="danger"
                @click="GoodsTransferForm.product_list.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type !== 'detail'" type="primary" @click="submitGoodsTransferForm">保存
      </el-button>
      <el-button @click="printIng">打印</el-button>
      <el-button @click="roBack()">返回 </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import * as API_GoodsTransfer from "@/api/goodsTransfer";
import * as API_BasicSetting from "@/api/basicSetting";
import { Foundation } from "~/ui-utils";
import * as API_Setting from "@/api/setting";
import * as API_Auth from "@/api/auth";
import * as API_Express from "@/api/express";
export default {
  name: "goodsTransferAdd",
  data() {
    return {
      adminList: [],
      // 所选部门对应调出仓库
      WarehouseList: [],
      // 所选部门对应调入仓库
      inWarehouseList: [],
      deptList: [],
      deptListAll: [],
      goodstransferType: [],
      fileList: [],
      id: "",
      /** 调拨单表单*/
      GoodsTransferForm: {
        out_dept_id: "",
        out_handled_by_id: "",
        product_list: [],
      },
      type: "",
      deliveryTypeList: [],
      GoodsTransferFormRule: {
        transfer_time: {
          required: true,
          message: "请选择调整时间",
          trigger: "change",
        },
        out_warehouse_id: {
          required: true,
          message: "请选择调出仓库",
          trigger: "change",
        },
        in_warehouse_id: {
          required: true,
          message: "请选择调入仓库",
          trigger: "change",
        },
        send_type: {
          required: true,
          message: "请选择配送方式",
          trigger: "change",
        },
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  mounted() {
    if (this.$route.name === "goodsTransferAdd") {
      this.GoodsTransferForm.out_handled_by_id = this.user.uid;
      this.GoodsTransferForm.dept_id = this.user.dept_id;
      /* this.$set(this.GoodsTransferForm, "transfer_time", new Date().getTime()); */
    } else if (this.$route.name === "goodsUnderstockDetail") {
      this.id = this.$route.params.id;
      this.type = "detail";
    }
    if (this.$route.params.id) {
      this.id = this.$route.params.id;
      this.GET_GoodsTransferDetail();
    }
    this.GET_DeptList();
    this.GET_DictDataInfo();
    this.GET_AdministratorList();
    this.GET_WarehouseList({ dept_id: this.user.dept_id });
    this.GET_ExpressList();
  },
  methods: {
    getdeliveryType(value) {
      // Access orderTypeList directly from the component's data
      const type = this.deliveryTypeList.find(type => type.id === value);
      return type ? type.name : '未知类型';
    },
    getWarehouse(value) {
      // Access orderTypeList directly from the component's data
      const type = this.WarehouseList.find(type => type.id === value);
      return type ? type.name : '未知类型';
    },
    // 打印功能
    printIng() { },
    /** 切换调出部门 */
    changeDept() {
      this.GET_WarehouseList("outWarehouseList");
      this.cleanGoodsList();
    },
    /** 清除已选商品明细 */
    cleanGoodsList() {
      // 切换部门或仓库需要清除已选对应仓库下的商品数据
      this.$set(this.GoodsTransferForm, "product_list", []);
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    roBack() {
      const { callback } = this.$route.params;
      if (typeof callback === "function") callback();
      this.$store.dispatch("delCurrentViews", {
        view: this.$route,
        $router: this.$router,
      });
      this.$router.push({ name: "goodsUnderstock" });
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      if (!this.GoodsTransferForm.out_warehouse_id) {
        this.$message.error("请先选择调出仓库！");
        return;
      }
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: `/admin/erp/warehouseOut/getGoodByWarehouse/${this.GoodsTransferForm.out_warehouse_id}`,
        warehouseList: this.outWarehouseList,
        selectedIds: this.id
          ? this.GoodsTransferForm.product_list &&
          this.GoodsTransferForm.product_list.map((item) => item.id)
          : this.GoodsTransferForm.product_list.map((item) => item.id),
        purchasePlanApiParams: {
          warehouse_id: this.GoodsTransferForm.out_warehouse_id,
        },
      });
      this.GoodsTransferForm.out_warehouse_id = goodsData.warehouse_id;
      if (goodsData.purchasePlans || goodsData.purchasePlans.length) {
        this.GoodsTransferForm.product_list = goodsData.purchasePlans.map(
          (item) => {
            item.warehouse_entry_batch_id = item.id;
            return item;
          }
        );
      }
    },
    submitGoodsTransferForm() {
      this.$refs["GoodsTransferForm"].validate((valid) => {
        if (valid) {
          const { id } = this.GoodsTransferForm;
          const params = this.MixinClone(this.GoodsTransferForm);
          /*       params.transfer_time = Math.floor(params.transfer_time / 1000); */
          if (params.product_list.length == 0) {
            this.$message.error("请选择商品！");
          }
          if (params.in_warehouse_id == params.out_warehouse_id) {
            this.$message.error("调出和调入仓库不能一致！");
            return;
          }
          params.product_list = params.product_list.map((item) => {
            const query = {
              num: item.num,
              goods_id:item.goods_id,
              use_able_num: Number(item.usable_stock),
              product_id: item.product_id,
              product_stock_id: item.id
            };
            return query;
          });
          if (id) {
            API_GoodsTransfer.editGoodsTransfer(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: "goodsUnderstock" });
            });
          } else {
            API_GoodsTransfer.addGoodsTransfer(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: "goodsUnderstock" });
            });
          }
        }
      });
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
        this.deptListAll = response;
      });
    },
    /** 获取仓库
    GET_WarehouseList(key) {
      let type = key === 'outWarehouseList' ? 'out_dept_id' : 'in_dept_id'
      const params = {
        dept_id: this.GoodsTransferForm[type]
      }
      API_BasicSetting.getWarehouseListAll(params).then(response => {
        this[key] = response
      })
    },*/
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then((response) => {
        this.WarehouseList = response;
      });
    },
    GET_DictDataInfo() {
      API_Setting.getDictDataInfo("erp_goodstransfer_type").then((res) => {
        this.goodstransferType = res;
      });
    },
    /** 获取采购计划详情页面数据 */
    GET_GoodsTransferDetail() {
      API_GoodsTransfer.getGoodsTransferInfo(this.id).then((response) => {
        this.GoodsTransferForm = response;
        /* this.fileList = response.attachment
          ? [{ name: "附件", url: response.attachment }]
          : []; */
        /* this.GoodsTransferForm.transfer_time = Math.floor(
          this.GoodsTransferForm.transfer_time * 1000
        ); */
      });
    },
    /** 获取物流公司列表 */
    GET_ExpressList() {
      API_Express.getExpressList(this.params).then((response) => {
        this.deliveryTypeList = response.data;
      });
    },
  },
};
</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;

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

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

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

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}

/deep/ .el-form-item {
  width: 350px;
}
</style>
