<template>
  <div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库">
              <el-select v-model="advancedForm.warehouse_id" clearable>
                <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编号/sku/序列号">
              <el-input v-model="advancedForm.keyword" clearable placeholder="请输入内容" width="200px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button @click="advancedSearchEvent"> 搜索 </el-button>
    </div>
    <en-table-layout :tableData="tableData.data" ref="table" :loading="loading"
      @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <!-- <el-button
            size="mini"
            v-if=""
            type="primary"
            @click="handleAddGoodsTransfer"
            >新增</el-button
          > -->
          <!-- <el-button
            size="mini"
            v-if="checkPermission(['goodsTransfer:del'])"
            @click="handleDeleteGoodsTransfer()"
            type="danger"
            :disabled="multipleSelection.length === 0"
            >删除</el-button
          > -->
          <el-button size="mini" type="primary" v-if="checkPermission(['updateWarnStock:update'])" @click="handleSubmitGoodsTransfer">设置预警库存</el-button>
          <el-button size="mini" type="primary" @click="checkExport">导出</el-button>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse_name" label="仓库名称">
          <!-- <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['goodsTransfer'])"
              style="color: #409eff"
              :to="{
                name: 'goodsTransferDetail',
                params: { id: scope.row.id },
              }"
            >
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{ scope.row.sn }}</span>
          </template> -->
        </el-table-column>
        <el-table-column label="商品编号" prop="sn">
          <!-- <template slot-scope="scope">{{
            scope.row.transfer_time | unixToDate
          }}</template> -->
        </el-table-column>
        <el-table-column prop="type" label="类别">
        <template slot-scope="scope">
          {{ scope.row.product_vo.hire_or_sail=='sail' ? '售卖商品' : '租赁商品'  }}
        </template>
       </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" />
       <el-table-column prop="type" label="sku">
        <template slot-scope="scope">
          {{ scope.row.product_vo ? scope.row.product_vo.sku : ''  }}
        </template>
       </el-table-column>
             <!-- <el-table-column prop="product_vo.sku" label="库位号" />
        <el-table-column prop="goods_bar_code" label="商品条码" />
        <el-table-column prop="goods_sn_code" label="序列号" />
          <template slot-scope="scope">{{ typeFilter(scope.row.type) }}</template>
        </el-table-column> 
        <el-table-column prop="goods_style" label="规格型号" />-->
        <el-table-column prop="goods_unit" label="单位" />
        <!--   <el-table-column prop="warehouse_area.status" label="状态">
          <template slot-scope="scope">{{
            statusFilter(scope.row.status)
          }}</template>
        </el-table-column> -->
        <el-table-column prop="actual_stock" label="实际库存" >
          <template slot-scope="scope">
           <span :style="Number(scope.row.actual_stock)<Number(scope.row.warning_stock)?'color:red':''">{{ scope.row.actual_stock }}</span> 
          </template>
        </el-table-column>
        <el-table-column prop="usable_stock" label="可用库存" />
        <el-table-column prop="transit_stock" label="在途库存" />
        <el-table-column prop="locked_stock" label="冻结库存" />
        <el-table-column prop="warning_stock" label="预警库存" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="success1" size="mini" v-if="checkPermission(['goodsTransfer:add']) && scope.row.transit_stock>0"
              @click="lookTransit(scope.row)">查看在途</el-button>
            <!-- <el-button type="success1" size="mini"
              v-if="scope.row.allowable.submit && checkPermission(['goodsTransfer:submit'])"
              @click="handleSubmitGoodsTransfer(scope.row)">提交</el-button>
            <el-button type="danger" size="mini"
              v-else-if="scope.row.allowable.withdraw && checkPermission(['goodsTransfer:withdraw'])"
              @click="handleWithdrawGoodsTransfer(scope.row)">撤回</el-button> 
            <el-button size="mini" @click="handleEditGoodsTransfer(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" @click="handleDelGoodsTransfer(scope.row)"
              >删除</el-button
            >
            <el-button size="mini" v-if="scope.row.allowable.confirm && checkPermission(['goodsTransfer:confirm'])"
              @click="handleSuccessGoodsTransfer(scope.row)" type="success">确认</el-button>
            <el-button size="mini" v-if="scope.row.allowable.confirm && checkPermission(['goodsTransfer:return'])"
              @click="handleRejectGoodsTransfer(scope.row)" type="danger">退回</el-button> -->
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog title="在途明细" :visible.sync="dialogVisible" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-table :data="transitDetails" border class="sku-table">
        <el-table-column prop="order_sn" label="订单编号" />
        <el-table-column prop="num" label="在途数量" />
        <el-table-column prop="end_time" label="返回日期" />
      </el-table>
      <!-- <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" >确 定</el-button>
          </span> -->
    </el-dialog>
    <el-dialog title="设置预警数量" :visible.sync="numDialogVisible" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" width="30%">
      <el-form ref="numAddForm" :model="numAddForm" :rules="numAddFormRule" label-width="160px" inline
        class="change-form">
        <el-form-item label="预警数量" prop="num" class="change-form-item">
          <el-input v-model="numAddForm.num" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="numDialogVisible = false">取 消</el-button>
        <el-button @click="submitNum" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsTransfer from "@/api/goodsTransfer";
import * as API_Setting from "@/api/setting";
import * as API_BasicSetting from "@/api/basicSetting";
import { mapGetters } from "vuex";
export default {
  name: "GoodsTransfer",
  data() {
    return {
      warehouseList: [],
      goodstransferType: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 50,
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: "",
      // 当前已选择的行
      multipleSelection: [],
      GoodsTransferForm: {},
      dialogVisible: false,
      // 在途明细
      transitDetails: [],
      numDialogVisible: false,
      numAddForm: {},
      stockListId: [],//选择的id
      numAddFormRule: {
        num: [{
          required: true,
          message: '请输入预警库存数量',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            if (/^(?:[1-9]\d*)$/.test(value) == false) {
              callback(new Error("请输入正整数"));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
        ],
      },
      selectedRow: null, // 用于记录当前选中的行
    };
  },
  mounted() {
    this.GET_GoodsTransferList();
    this.GET_DictDataInfo();
    this.GET_WarehouseList();
  },
  watch: {
    $route: function ({ query }) {
      this.params.page_no = 1;
      this.GET_GoodsTransferList();
    },
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    /* 提交预警数量 */
    submitNum() {
      this.$refs["numAddForm"].validate((valid) => {
        if (valid) {
          API_GoodsTransfer.updateWarnStock({stock_id:this.stockListId, warn_num:this.numAddForm.num}).then(res => {
            this.numDialogVisible = false
            this.numAddForm = {}
            this.$message.success('预警库存设置成功!')
            this.GET_GoodsTransferList();
          })
        }
      })
    },
    // 删除
    handleDelGoodsTransfer(row) {
      this.$confirm("确定要删除这些库存吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = []
          ids.push(row.id)
          API_GoodsTransfer.deleteGoodsTransfer({ ids: ids }).then((res) => {
            this.$message.success("删除成功！");
            this.ids = []
            this.GET_GoodsTransferList();
          });
        })
        .catch(() => { });
    },
    // 导出
    checkExport() { },
    // 查看在途
    lookTransit(row) {
      API_GoodsTransfer.transitDetail(row.id).then(res => {
        this.dialogVisible = true;
        this.transitDetails = res
      })
    },
    handleSuccessGoodsTransfer(row) {
      API_GoodsTransfer.successGoodsTransfer(row.id, {
        in_handled_by_id: this.user.uid,
        in_handled_by_name: this.user.username,
      }).then(() => {
        this.$message.success("确认成功！");
        this.GET_GoodsTransferList();
      });
    },
    handleRejectGoodsTransfer(row) {
      API_GoodsTransfer.rejectGoodsTransfer(row.id, {
        in_handled_by_id: this.user.uid,
        in_handled_by_name: this.user.username,
      }).then(() => {
        this.$message.success("退回成功！");
        this.GET_GoodsTransferList();
      });
    },
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
    typeFilter(row) {
      return this.goodstransferType.find((type) => type.value === row).label;
    },
    GET_DictDataInfo() {
      API_Setting.getDictDataInfo("erp_goodstransfer_type").then((res) => {
        this.goodstransferType = res;
      });
    },
    handleSubmitGoodsTransfer(row) {
      if(this.stockListId.length==0) return this.$message.error("请选择")
      /* this.stockId = row.id */
      this.numDialogVisible = true
      /* API_GoodsTransfer.submitGoodsTransfer(row.id).then(() => {
        this.$message.success("提交成功！");
        this.GET_GoodsTransferList();
      }); */
    },
    handleWithdrawGoodsTransfer(row) {
      API_GoodsTransfer.withdrawGoodsTransfer(row.id).then(() => {
        this.$message.success("撤回成功！");
        this.GET_GoodsTransferList();
      });
    },
    /** 调拨单状态 */
    statusFilter(val) {
      switch (val) {
        case "NotSubmit":
          return "未提交";
        case "Submit":
          return "已提交";
        case "Confirm":
          return "已确认";
        case "AuditReject ":
          return "已退回";
        default:
          return "";
      }
    },
    handleDeleteGoodsTransfer() {
      if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$message.error("请先选择！");
      this.$confirm("确定要删除这些库存吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          API_GoodsTransfer.deleteGoodsTransfer({ ids: ids }).then(() => {
            this.$message.success("删除成功！");
            this.GET_GoodsTransferList();
          });
        })
        .catch(() => { });
    },
    /** 多选改变 */
    handleSelectionChange(row) {
      this.stockListId=row.map(el=>{
        return el.id
      })
      /* if (selection.length > 0) {
        const lastSelected = selection[selection.length - 1];
        if (this.selectedRow && this.selectedRow !== lastSelected) {
          this.selectedRow = lastSelected;
        } else {
          this.selectedRow = lastSelected;
        }
      } else {
        this.selectedRow = null;
      } */
    },
    selectableRow(row, index) {
      // 这个方法决定了哪些行是可选的
      return !this.selectedRow || this.selectedRow === row;
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_GoodsTransferList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_GoodsTransferList();
    },

    /** 添加商品调拨 */
    handleAddGoodsTransfer() {
      this.$router.push({
        name: "goodsTransferAdd",
        params: { callback: this.GET_GoodsTransferList },
      });
    },
    /** 编辑商品调拨 */
    handleEditGoodsTransfer(row) {
      this.$router.push({
        name: "goodsTransferDetail",
        params: { id: row.id },
      });
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data,
      };
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key]);
      this.params.page_no = 1;
      this.GET_GoodsTransferList();
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.start_time = parseInt(
          Number(this.advancedForm.purchasePlan_time_range[0]) / 1000
        );
        this.params.end_time = parseInt(
          Number(this.advancedForm.purchasePlan_time_range[1]) / 1000
        );
      }
      delete this.params.purchasePlan_time_range;
      this.params.page_no = 1;
      this.GET_GoodsTransferList();
    },
    /** 获取商品调拨列表 */
    GET_GoodsTransferList() {
      this.loading = true;
      API_GoodsTransfer.productStock(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.search {
  display: flex;
  align-items: center;
  background: #fff;
  overflow: hidden;
  padding: 30px 10px 10px 10px;

  /deep/ .el-form-item {
    .el-form-item__content {
      .el-input {
        width: 200px;
      }
    }
  }

  .el-button {
    margin-top: -19px;
    margin-left: 20px;
  }
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
