<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel">
      <el-row :gutter="10" class="mb8">

<!--        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleCk"
            v-hasPermi="['system:orderdetail:edit']"
          >出库
          </el-button
          >
        </el-col>-->
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:orderdetail:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
          >重置
          </el-button>
        </el-col>
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch" showColumnsType="transfer" :columns="columns"/>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <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="locationId">
          <el-select v-model="queryParams.locationId" placeholder="请选择库位编号" clearable>
            <el-option
              v-for="dict in locationList"
              :key="dict.locationId"
              :label="dict.pyName"
              :value="dict.locationId"
            />
          </el-select>
        </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="unit">
          <el-select v-model="queryParams.unit" placeholder="请选择单位" clearable>
            <el-option
              v-for="dict in dict.type.goods_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="storageId">
          <el-select v-model="queryParams.storageId" placeholder="请选择仓库" clearable>
            <el-option
              v-for="dict in storageList"
              :key="dict.storageId"
              :label="dict.storageShortName"
              :value="dict.storageId"
            />
          </el-select>
        </el-form-item>
<!--
        <el-form-item label="物料分类" prop="goodsTypeId">
          <el-select v-model="queryParams.goodsTypeId" placeholder="请选择物料分类" clearable>
            <el-option
              v-for="dict in dict.type.goods_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
-->
<!--
        <el-form-item label="供应商" prop="providerId">
          <el-select v-model="queryParams.providerId" placeholder="请选择供应商：特殊标识为K时候必填" clearable>
            <el-option
              v-for="dict in providerList"
              :key="dict.providerId"
              :label="dict.providerName"
              :value="dict.providerId"
            />
          </el-select>
        </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="storageAreaId">
          <el-select v-model="queryParams.storageAreaId" placeholder="请选择库区" clearable>
            <el-option
              v-for="dict in locationList"
              :key="dict.locationId"
              :label="dict.pyName"
              :value="dict.locationId"
            />
          </el-select>
        </el-form-item>
-->
<!--
        <el-form-item label="条形码" prop="barcode">
          <el-input
            v-model="queryParams.barcode"
            placeholder="请输入条形码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
-->
<!--
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
-->
      </el-form>
    </div>

    <div class="table-container">
      <div ref="mainTablePanel" :style="{height: mainTableDivHeight}">
        <el-table :key="rndKey" ref="mainTablePanel" v-loading="loading" border size="mini" :height="mainTableHeight"
                  :data="orderdetailList" @selection-change="handleSelectionChange"
                  @header-dragend="handleHeaderDragEnd">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column sortable v-for="item in columns" :key="item.key" :label="item.label" align="center"
                           :prop="item.columnName" v-if="item.visible" :width="item.width">

            <template v-slot="scope">
              <dict-tag v-if="item.columnName === 'unit'" v-slot="scope" :options="dict.type.goods_unit"
                        :value="scope.row[item.columnName]"/>
              <dict-tag v-else-if="item.columnName === 'confirmStatus'" v-slot="scope" :options="dict.type.out_status"
                        :value="scope.row[item.columnName]"/>
              <dict-tag v-else-if="item.columnName === 'goodsTypeId'" v-slot="scope" :options="dict.type.goods_type"
                        :value="scope.row[item.columnName]"/>
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </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>


    <!-- 添加或修改出库物料明细对话框 -->
    <el-dialog id="dialog-container" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="主表id" prop="orderId">
                <el-input v-model="form.orderId" placeholder="请输入主表id"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="子需求编号" prop="businessId">
                <el-input v-model="form.businessId" placeholder="请输入子需求编号"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料编号" prop="goodsId">
                <el-input v-model="form.goodsId" placeholder="请选择物料编号"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料名称" prop="goodsName">
                <el-input v-model="form.goodsName" placeholder="请输入物料名称"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="库位编号" prop="locationId">
                <el-select v-model="form.locationId" placeholder="请选择库位编号">
                  <el-option
                    v-for="dict in locationList"
                    :key="dict.locationId"
                    :label="dict.pyName"
                    :value="dict.locationId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格" prop="specification">
                <el-input v-model="form.specification" placeholder="请输入规格"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位" prop="unit">
                <el-select v-model="form.unit" placeholder="请选择单位">
                  <el-option
                    v-for="dict in dict.type.goods_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="仓库" prop="storageId">
                <el-select v-model="form.storageId" placeholder="请选择仓库">
                  <el-option
                    v-for="dict in storageList"
                    :key="dict.storageId"
                    :label="dict.storageName"
                    :value="dict.storageId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="订单需求数量" prop="shelvesNum">
                <el-input v-model="form.shelvesNum" placeholder="请输入订单需求数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="本次出库数量" prop="goodsNum">
                <el-input v-model="form.goodsNum" placeholder="请输入本次出库数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="呼叫数量" prop="callShelvesNum">
                <el-input v-model="form.callShelvesNum" placeholder="请输入呼叫数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="标准价" prop="price">
                <el-input v-model="form.price" placeholder="请输入标准价"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料分类" prop="goodsTypeId">
                <el-select v-model="form.goodsTypeId" placeholder="请选择物料分类">
                  <el-option
                    v-for="dict in dict.type.goods_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商：特殊标识为K时候必填" prop="providerId">
                <el-select v-model="form.providerId" placeholder="请选择供应商：特殊标识为K时候必填">
                  <el-option
                    v-for="dict in providerList"
                    :key="dict.providerId"
                    :label="dict.providerName"
                    :value="dict.providerId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料描述" prop="recoil">
                <el-input v-model="form.recoil" placeholder="请输入物料描述"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="库区" prop="storageAreaId">
                <el-input v-model="form.recoil" placeholder="请输入库区"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总出库数量" prop="pickNum">
                <el-input v-model="form.pickNum" placeholder="请输入总出库数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="确认出库数量" prop="trNum">
                <el-input v-model="form.trNum" placeholder="请输入确认出库数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="条形码" prop="barcode">
                <el-input v-model="form.barcode" placeholder="请输入条形码"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.common_status"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="AGV站台" prop="toLoc">
                <el-input v-model="form.toLoc" placeholder="请输入AGV站台"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出库状态" prop="confirmStatus">
                <el-radio-group v-model="form.confirmStatus">
                  <el-radio
                    v-for="dict in dict.type.out_status"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到期时间" prop="expiryDate">
                <el-date-picker clearable
                                v-model="form.expiryDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择到期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="库存数量" prop="stockNum">
                <el-input v-model="form.stockNum" placeholder="请输入库存数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="呼叫任务号" prop="taskId">
                <el-input v-model="form.taskId" placeholder="请输入呼叫任务号"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrderdetail,
  getOrderdetail,
  delOrderdetail,
  addOrderdetail,
  updateOrderdetail,
  disabled,
  enabled,
  changeStatus
} from "@/api/system/orderdetail";
import {listCOLUMN} from "@/api/system/column";

import {listLocation} from "@/api/system/location";
import {listStorage} from "@/api/system/storage";
import {listProvider} from "@/api/system/provider";
import TableMixin from "@/api/tableMixin";


export default {
  name: "Orderdetail",
  dicts: ['goods_unit', 'common_status', 'out_status', 'goods_type'],
  mixins: [TableMixin],
  data() {
    return {
      rndKey: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库物料明细表格数据
      orderdetailList: [],
      // 库位 表格数据
      locationList: [],
      //仓库集合
      storageList: [],
      //报价商集合
      providerList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "orderdetail",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        orderId: null,
        businessId: null,
        goodsId: null,
        goodsName: null,
        locationId: null,
        specification: null,
        unit: null,
        storageId: null,
        shelvesNum: null,
        goodsNum: null,
        callShelvesNum: null,
        price: null,
        goodsTypeId: null,
        providerId: null,
        recoil: null,
        storageAreaId: null,
        pickNum: null,
        trNum: null,
        barcode: null,
        status: null,
        toLoc: null,
        confirmStatus: null,
        expiryDate: null,
        stockNum: null,
        taskId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          {required: true, message: "主表id不能为空", trigger: "blur"}
        ],
      },
      columns: []
    };
  },
  created() {
    this.getList();
    this.getStorageList();
    this.getLocationList();
    this.getProviderList();
  },

  mounted() {
    this.computedTableHeight();
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    }
  },
  methods: {
    /** 查询用户展示字段定义管理列表 */

    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;

        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = (tablePanelHeight - 25) + "px";

      })
    },

    /** 获取库位列表 */
    getLocationList() {
      listLocation().then(response => {
        this.locationList = response.rows;
      });
    },
    /** 获取仓库列表 */
    getStorageList() {
      listStorage().then(response => {
        this.storageList = response.rows;
      });
    },
    /** 报价商集合 */
    getProviderList() {
      listProvider().then(response => {
        this.providerList = response.rows;
      });
    },
    /** 查询出库物料明细列表 */
    getList() {
      this.loading = true;
      listOrderdetail(this.queryParams).then(response => {
        // 处理每行数据，将null值转换为空字符串
        this.orderdetailList = response.rows.map(row => {
          return Object.keys(row).reduce((acc, key) => {
            // 检查每个值，如果为null则替换为''，否则保留原值
            acc[key] = row[key] === 'null' ? '' : row[key];
            return acc;
          }, {});
        });
        this.total = response.total;
        if (this.columns.length == 0) {
          this.columns = response.columns.map(column => {
            // 如果columns中也可能有null值，同样进行处理
            return column === null ? '' : column;
          });
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        businessId: null,
        goodsId: null,
        goodsName: null,
        locationId: null,
        specification: null,
        unit: null,
        storageId: null,
        shelvesNum: null,
        goodsNum: null,
        callShelvesNum: null,
        remark: null,
        price: null,
        goodsTypeId: null,
        providerId: null,
        recoil: null,
        storageAreaId: null,
        pickNum: null,
        trNum: null,
        barcode: null,
        status: null,
        toLoc: null,
        confirmStatus: null,
        expiryDate: null,
        stockNum: null,
        taskId: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库物料明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrderdetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出库物料明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderdetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderdetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出库物料明细编号为"' + ids + '"的数据项？').then(function () {
        return delOrderdetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"id为"' + row.id + '"数据项？').then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认启用出库物料明细编号为"' + ids + '"的数据项？').then(function () {
        return enabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启用成功");
      }).catch(() => {
      });
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认禁用出库物料明细编号为"' + ids + '"的数据项？').then(function () {
        return disabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("禁用成功");
      }).catch(() => {
      });
    },
    /** 修改按钮操作 */
    handleCk(row) {
      const ckIds = row.ckId || this.ids;
      if (ckIds == "" || ckIds == undefined || ckIds.length == 0) {
        this.$modal.msgError("请选择待出库的库存！");
        return;
      }
      var reqArr = [];
      var isError = false;
      var isSame = true;
      var isOver = false;
      var salsNo = "";
      for (var j = 0; j < ckIds.length; j++) {
        for (var i = 0; i < this.orderdetailList.length; i++) {
          var obj = this.orderdetailList[i];
          if (ckIds[j] == obj.ckId) {
            if (obj.goodsNum > obj.stocknum) {
              isError = true;
              break;
            }
            if (obj.sts != "0") {
              isError = true;
              break;
            }
            if (salsNo == "") {
              salsNo = obj.salesOrderNo;
            } else {
              if (salsNo != obj.salesOrderNo) {
                isSame = false;
                break;
              }
            }
            console.log(obj);
            // if (obj.confirmStatus == "2") {
            //   isOver = true;
            //   break;
            // }
            reqArr.push(obj);
            break;
          }
        }
        if (isError || !isSame || isOver) {
          break;
        }
      }
      if (isError) {
        this.$modal.msgError("出库数量不能大于库存数量或者订单已冻结");
        return;
      }
      if (!isSame) {
        this.$modal.msgError("一次出库，必须为同一个出库单号");
        return;
      }
      // if (!isOver) {
      //   this.$modal.msgError("该物料已出库完成，不能再次出库");
      //   return;
      // }
      this.$modal
        .confirm("如果出库数量等于库存，则为整出，不会自动产生回库任务！")
        .then(function () {
          return addTaskList(reqArr);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("出库任务创建成功");
        })
        .catch(() => {
          this.$modal.msgSuccess("出库任务创建异常");
        });
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/orderdetail/importTemplate",
        {},
        `template_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "出库订单导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orderdetail/export', {
        ...this.queryParams
      }, `orderdetail_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
