<template>
  <el-dialog id="dialog-container" :title="title" :visible.sync="open" width="1000px" height="480px" append-to-body>
    <div class="dialog-body" style="height: 430px; padding: 0px !important">
      <div class="search-container" ref="searchPanel" style="padding-left: 5px; padding-right: 5px">
        <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="开始日期">
            <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择开始日期" @keyup.enter.native="handleQuery" style="width:192px !important">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择结束日期" @keyup.enter.native="handleQuery" style="width:192px !important">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="物料编号" prop="goodsId">
            <el-input v-model="queryParams.goodsId" placeholder="请输入物料编号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="物料名称" prop="goodsName">
            <el-input v-model="queryParams.goodsName" placeholder="请输入物料名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="来源单号" prop="deliveryId">
            <el-input v-model="form.deliveryId" placeholder="请输入来源单号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="托盘号" prop="ctl">
            <el-input v-model="queryParams.ctl" placeholder="请输入托盘号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="申请人" prop="applicant">
            <el-input v-model="queryParams.applicant" placeholder="请输入申请人" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="仓库" prop="storageId">
            <el-select
              v-model="queryParams.storageId"
              filterable
              placeholder="选择仓库"
            >
              <el-option
                v-for="storage in filterStorage"
                :key="storage.storageId"
                :label="storage.storageShortName"
                :value="storage.storageId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-container">
        <div ref="mainTablePanel">
          <el-table ref="goodsTable" v-loading="loading" border size="mini" height="300" :data="goodsList"
            @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="出库日期" align="center" prop="createTime" width="140"/>
            <el-table-column label="物料编号" align="center" prop="goodsId" width="130"/>
            <el-table-column label="物料名称" align="center" prop="goodsName" width="150"/>
            <el-table-column label="出库数量" align="center" prop="trNum" />
            <el-table-column label="退库数量" prop="recNumNow" width="180" height="20px">
            <template slot-scope="scope">
              <el-input-number
                :min="0"
                v-model="scope.row.recNumNow"
                placeholder="请输入退库数量"
              />
            </template>
            </el-table-column>
            <el-table-column label="来源单号" align="center" prop="deliveryId" />
            <el-table-column label="仓库" align="center" prop="storageId" />
            <el-table-column label="库位" align="center" prop="locationId" width="100"/>
            <el-table-column label="申请人" align="center" prop="applicant" />
            <el-table-column label="出库类型" align="center" prop="ckType" width="140">
              <template slot-scope="scope">
                <el-select v-model="scope.row.ckType">
                  <el-option
                    v-for="dict in dict.type.outbound_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="条形码" align="center" prop="barcode" />
            <el-table-column label="分类" align="center" prop="goodsTypeId" />
            <el-table-column label="规格" align="center" prop="specification" width="150"/>
            <el-table-column label="物料描述" align="center" prop="recoil" />
            <el-table-column label="物料单位" align="center" prop="unit" />
            <el-table-column label="备注" align="center" prop="remark" />
          </el-table>
          <div class="pagePanel">
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">生成入库单</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listStorageAreaLocation } from "@/api/system/storage";
import { listSelectTckOrdersbak } from "@/api/system/tckOrdersbak";
import { workshopReturn } from "@/api/system/trkNotice";

export default {
  name: "ExistOrdersSelect",
  dicts: [
    "sys_yes_no",
    "common_status",
    "goods_unit",
    "goods_type",
    "outbound_type"
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      storageIds: [],
      // 非单个禁用
      single: false,
      // 非多个禁用
      multiple: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料表格数据
      goodsList: [],
      // 选择的物料
      selectItem: null,
      // 弹出层标题
      title: "出库单选择",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      // 是否显示弹出层
      open: false,
      // 选择回调函数
      callBack: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        goodsId: null,
        goodsName: null,
        startDate: null,
        endDate: null,
        deliveryId: null,
        ctl: null,
        applicant: null,
        storageId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    this.getStorageAreaLocation();
  },
  computed: {
    filterStorage() {
      return this.storageIds;
    }
  },
  mounted() { },
  methods: {

    generateUniqueId() {
      const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      const date = new Date();
      const uniqueId = date.getTime().toString(36).toUpperCase();
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      const timeString = hours + minutes + seconds;
      const randomLetter = letters.charAt(Math.floor(Math.random() * letters.length));
      return uniqueId + timeString + randomLetter;
    },

    /** 查询物料列表 */
    getList() {

      if (this.queryParams.goodsId != null && this.queryParams.goodsId != "") {
        this.queryParams.goodsId = this.queryParams.goodsId.replace(/\s+/g,"").toUpperCase();
      }

      this.loading = true;
      listSelectTckOrdersbak(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsName: null,
        startDate: null,
        endDate: null,
        deliveryId: null,
        ctl: null,
        applicant: null,
        storageId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectItem = selection;
    },
    /** 查询仓库列表 */
    getStorageAreaLocation() {
      listStorageAreaLocation({}).then((response) => {
        if (response.code == 200) {
          var storageArray = new Array();

          for (var index = 0; index < response.data.length; index++) {
            var storageInfo = response.data[index];
            if (storageArray.indexOf(storageInfo.storageId) == -1) {
              storageArray.push(storageInfo.storageId);
              this.storageIds.push({
                storageId: storageInfo.storageId,
                storageName: storageInfo.storageName,
              });
            }
          }
          storageArray = [];
        } else {
          this.$modal.msgError("查询仓库信息失败");
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.selectItem == null) {
        this.$modal.msgError("请选择待提交的物料");
        return;
      }
      console.log(this.selectItem);
      var updateList = [];
      for(var n in this.selectItem) {
          var obj = this.selectItem[n];

          if (obj.recNumNow == 0 || obj.recNumNow == "") {
            this.$modal.msgError("请输入退货数量，物料【" + obj.goodsId + '  ' + obj.goodsName +"】");
            return;
          }

          if (obj.recNumNow > obj.trNum) {
            this.$modal.msgError("退库数量不能大于出库数量，物料【" + obj.goodsId + '  ' + obj.goodsName +"】");
            return;
          }

          updateList.push(obj);
      }

      var form={
        tckOrderdetailBakList: updateList
      }

      var that = this;
      workshopReturn(form).then((response) => {
          if (response.code != 200) {
            that.$modal.msgError("发生系统错误，生成入库单失败");
            return;
          }
          if (response.data.error != "") {
            that.$modal.msgError(response.data.error);
            return;
          } else {
            that.$modal.msgSuccess(response.data.success);

            var result = {
              id: response.data.id,
              noticeId: response.data.noticeId,
              deliveryId: response.data.deliveryId
            }
            that.callBack(result);
          }
      })

      this.open = false;
    },
    showModal(newCallBack) {
      this.open = true;
      this.callBack = newCallBack;
      this.getList();
    }
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}

#dialog-container {
  .el-dialog__body {
    padding: 5px !important;
  }

  .pagination-container {
    background: none !important;
    margin-top: 5px !important;

    .el-pagination {
      left: 0 !important;
    }
  }
}

</style>
