<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">调拨单据</div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >选择库存
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >刷新
          </el-button>
        </el-col>


      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form
        :model="params"
        ref="queryForm"
        size="mini"
        :inline="true"
        v-show="showSearch"
        label-width="68px">

        <el-form-item label="创建人" prop="auditMan">
          <el-input
            v-model="params.creator"
            placeholder="请输入创建人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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>

    <el-table
      :data="orderList"
      stripe
      style="width: 100%">
      <el-table-column prop="id" label="行号" width="180"  align="center"></el-table-column>
      <el-table-column prop="creator" label="创建人" width="180"   align="center"></el-table-column>
      <el-table-column prop="transferContent" label="调拨内容" width="creator"  align="center"></el-table-column>
      <el-table-column prop="transferStatus" label="状态" width="180"  align="center"></el-table-column>
      <el-table-column prop="creationTime" label="创建时间" width="180"  align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagePanel">
      <pagination
        v-show="orderTotal>0"
        :total="orderTotal"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="getOrderList"
      />
    </div>


    <el-dialog
      id="dialog-container"
      :title="title"
      :visible.sync="open"
      width="1500px"
      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="物料编号" 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="specification">
              <el-input
                v-model="queryParams.specification"
                placeholder="请输入物料规格"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料描述" prop="recoil">
              <el-input
                v-model="queryParams.recoil"
                placeholder="请输入物料描述"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="库级选择" prop="levelType">
              <el-select v-model="queryParams.levelType" placeholder="请择选库级">
                <el-option
                  v-for="dict in dict.type.level_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </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 ref="mainTablePanel">
          <el-table
            ref="goodsTable"
            v-loading="loading"
            border
            size="mini"
            height="300"
            :data="tMiStockList"
            @selection-change="handleSelectionChange"
            @row-click="handleClick"
          >
            <el-table-column type="selection" :selectable="selectable" width="55" align="center"/>
            <el-table-column label="所在仓库" align="center" prop="storageId" sortable/>
            <el-table-column label="仓库名称" align="center" prop="storageShortName" sortable/>
            <el-table-column label="子需求编号" align="center" prop="salesOrderNumber" sortable/>
            <el-table-column label="物料编号" align="center" prop="goodsId" sortable/>
            <el-table-column label="物料名称" align="center" prop="goodsName" sortable/>
            <el-table-column label="规格" align="center" prop="specification" sortable/>
            <el-table-column label="物料描述" align="center" prop="recoil" sortable/>
            <el-table-column label="用途" align="center" prop="useType" sortable/>
            <el-table-column label="单价" align="center" prop="price" sortable/>
            <el-table-column label="总价" align="center" prop="totalMoney" sortable/>
            <el-table-column label="库存数量" align="center" prop="shelvesNum" sortable/>
            <el-table-column label="调拨数量" align="center" width="200px">
              <template slot-scope="scope">
                <div class="quantity-input-wrapper">
                  <el-button
                    size="mini"
                    icon="el-icon-minus"
                    @click.stop="decreaseQuantity(scope.row)"
                    :disabled="!scope.row.transferQuantity || scope.row.transferQuantity <= 1"
                  />
                  <el-input-number
                    v-model="scope.row.transferQuantity"
                    :min="1"
                    :max="scope.row.shelvesNum"
                    size="mini"
                    @change="(value) => handleQuantityChange(value, scope.row)"
                    @click.stop
                    controls-position="right"
                    :disabled="scope.row.status !== '0' || scope.row.isFreeze !== '0'"
                  />
                  <el-button
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="increaseQuantity(scope.row)"
                    :disabled="!scope.row.transferQuantity || scope.row.transferQuantity >= scope.row.shelvesNum"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unit" sortable/>
            <el-table-column label="需求部门" align="center" prop="needDept" sortable/>
            <el-table-column label="需求人" align="center" prop="needPerson" sortable/>
            <el-table-column label="占用数量" align="center" prop="occupyNum" sortable/>
            <el-table-column label="锁定状态" align="center" prop="status" sortable>
              <template slot-scope="scope">
                <dict-tag :options="dict.type.common_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="锁定数量" align="center" prop="occupyNum" sortable/>
            <el-table-column label="冻结状态" align="center" prop="isFreeze" sortable>
              <template slot-scope="scope">
                <dict-tag :options="dict.type.is_freeze" :value="scope.row.isFreeze"/>
              </template>
            </el-table-column>
            <el-table-column label="库级" align="center" prop="leveType" sortable>
              <template slot-scope="scope">
                <dict-tag :options="dict.type.level_type" :value="scope.row.levelType"/>
              </template>
            </el-table-column>
          </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 slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 仓库选择弹窗 -->
      <el-dialog
        id="dialog-container"
        :title="titles"
        :visible.sync="openStroage"
        width="500px"
        height="480px"
        append-to-body
      >
        <el-select
          v-model="storageId"
          filterable
          placeholder="选择仓库"
          @change="mxStash"
        >
          <el-option
            v-for="storage in storageList"
            :key="storage.storageId"
            :label="storage.storageShortName"
            :value="storage.storageId"
          />
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>


  </div>
</template>


<script>
import {listCOLUMN} from "@/api/system/column";
import {countList} from "@/api/system/tMiStock";
import {selectStorageList} from "@/api/system/storage";
import {updateTckOrderDetails, create, listOrder} from "@/api/system/ckOrders";

export default {
  name: "GoodsSelect",
  dicts: ["storage_classification", "common_status", "is_freeze", "level_type"],
  props: ["storageIdFrom"],

  data() {
    return {
      loading: false, // 确保初始时不加载
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tMiStockList: [],
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "tMiStock",
      rightToolbarShow: false,
      tableNo: 0,
      open: false,
      openStroage: false,
      storageList: [],
      storageId: '',
      titles: '',
      selectedItems: [],
      orderList: [], // 确保初始化为空数组
      params: {
        pageNum: 1,
        pageSize: 10,
        creator: null,
        creationTime: null,
        transferContent: null,
        transferStatus: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        storageId: null,
        storageAreaId: null,
        locationId: null,
        goodsId: null,
        shelvesNum: null,
        version: null,
        storageMode: null,
        providerId: null,
        productionDate: null,
        wareDate: null,
        doctNumber: null,
        goodsVolume: null,
        occupyNum: null,
        noticeId: null,
        oriBill: null,
        ctl: null,
        barcode: null,
        wgh: null,
        high: null,
        goodsName: null,
        status: null,
        customerId: null,
        batchNo: null,
        dueDate: null,
        checkDate: null,
        standard: null,
        flag: null,
        mark: null,
        orderNum: null,
        problem: null,
        price: null,
        packingNum: null,
        boxType: null,
        scaleUnit: null,
        goodsSku: null,
        factoryId: null,
        salesOrderNo: null,
        salesOrderNumber: null,
        supplier: null,
        onOrder: null,
        recordPerson: null,
        lotId: null,
        decid: null,
        unit: null,
        specification: null,
        goodsAge: null,
        arraMount: null,
        recoil: null,
        operatorId: null,
        operateDate: null,
        purchaseId: null,
        applicant: null,
        respDept: null,
        planDate: null,
        planTime: null,
        needCycle: null,
        needType: null,
        goodsTypeId: null,
        brand: null,
        totalMoney: null,
        expiryDate: null,
        providerName: null,
        receiver: null,
        needDept: null,
        purchaseDept: null,
        produclotId: null,
        receiverDept: null,
        receivingArea: null,
        packageId: null,
        useType: null,
        telephone: null,
        totalVolume: null,
        totalRoughWeight: null,
        totalNetWeigh: null,
        defaultStorageAreaId: null,
        qualityInspecStatus: null,
        periodUnit: null,
        period: null,
        reportTime: null,
        consignment: null,
      },
      orderTotal: 0,

      // 表单参数
      form: {},

      // 表单校验规则
      rules: {},


    };
  },

  created() {
    this.open = true;
    this.getList();
    this.getOrderList();
  },

  methods: {



    // 过滤状态
    filterStatus(value, row, column) {
      return row.status === value;
    },

    // 判断行是否可选
    selectable(row, index) {
      return row.status === '0' && row.isFreeze === '0';
    },

    // 阻止行选择事件冒泡
    preventRowSelection(row, event) {
      event.stopPropagation();
    },

    getOrderList() {
      this.loading = true;
      listOrder(this.params).then(response => {
        this.orderList = response.rows;
        this.orderTotal = response.total;
        this.loading = false;
        this.getHideColumn();
      });
    },

    // 获取物料列表
    getList() {
      this.loading = true;
      countList(this.queryParams).then((response) => {
        this.tMiStockList = response.rows.map(item => ({
          ...item,
          transferQuantity: 1 // 初始化调拨数量为1
        }));
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.openStroage = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        storageId: null,
        // ... (其他字段重置)
      };
      this.resetForm("form");
    },


    handleAdd(){
      this.open = true;
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.params.pageNum = 1;
      this.getOrderList();
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.getOrderList()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      selection.forEach((item) => {
        this.$refs.goodsTable.toggleRowSelection(item, true);
      });
      this.selectItem = selection[selection.length - 1];
      this.selectedItems = selection;
    },

    // 减少调拨数量
    decreaseQuantity(row) {
      if (row.transferQuantity > 1) {
        row.transferQuantity--;
      }
    },

    // 增加调拨数量
    increaseQuantity(row) {
      if (row.transferQuantity < row.shelvesNum) {
        row.transferQuantity++;
      }
    },

    // 处理数量变化
    handleQuantityChange(value, row) {
      if (value <= 0) {
        row.transferQuantity = 1;
        this.$message.warning('调拨数量不能小于1');
        return;
      }

      if (value > row.shelvesNum) {
        row.transferQuantity = row.shelvesNum;
        this.$message.warning('调拨数量不能超过库存数量');
        return;
      }
    },

    // 提交表单
    submitForm() {
      if (this.selectedItems.length === 0) {
        this.$modal.msgError("请选择一个或多个物料");
        return;
      }
      this.openStroage = true;
      this.titles = '调拨仓库';
      this.getStorageList();
    },

    // 提交调拨
    submit() {
      if (this.storageId === '') {
        this.$modal.msgError("请选择要调拨的目标仓库");
        return;
      }

      // 验证数量
      const invalidItems = this.selectedItems.filter(item => {
        return !item.transferQuantity || item.transferQuantity <= 0 || item.transferQuantity > item.shelvesNum;
      });

      if (invalidItems.length > 0) {
        this.$modal.msgError("请检查调拨数量是否正确");
        return;
      }
      // 准备提交数据
      const transferData = {
        targetStorageId: this.storageId,
        data: this.selectedItems
      };

      create(transferData).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("创建调拨成功！");
          this.getList();
          this.open = false;
          this.openStroage = false;
          this.getOrderList();
        } else {
          this.$modal.msgError("创建调拨失败！");
        }
      });

      console.log('调拨数据:', transferData);
      // 这里添加调用后端API的代码
    },

    // 仓库选择变更
    mxStash(value) {
      this.stash = value;
    },

    // 获取仓库列表
    getStorageList() {
      selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = response.data.map((element, index) => ({
            ...element,
            key: element.id || `unique-${index}`
          }));
        } else {
          this.$modal.msgError("查询仓库失败");
        }
      });
    },

    // 处理行点击
    handleClick(row, event) {
      event.stopPropagation();
      this.$refs.goodsTable.toggleRowSelection(row);
      this.selectItem = row;
    }
  }
};
</script>

<style scoped>
.app-container {
  height: calc(100vh - 84px);
}

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

.quantity-input-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.quantity-input-wrapper .el-input-number {
  width: 130px;
}

.el-input-number.is-controls-right .el-input__inner {
  padding-left: 5px;
  padding-right: 30px;
}

.row-disabled {
  pointer-events: none;
  opacity: 0.6;
}

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

  .el-pagination {
    left: 0;
  }
}
</style>
