<template>
  <div class="content-height p20 warehouseAdd">
    <header>
      <span class="title">{{ formData.code }} {{ formData.name }}</span>
      <div>
        <el-button @click="$router.go(-1)">返回</el-button>
        <el-button type="primary" @click="submit" :loading="loading"
          >保存</el-button
        >
      </div>
    </header>
    <el-divider></el-divider>
    <div class="area">
      <div class="mt20 reservoirArea">
        <span>库区</span>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addArea"
          >添加库区
        </el-button>
      </div>
      <div class="mt10">
        <el-form :model="areaForm" ref="areaFormName" class="areaForm">
          <el-table
            ref="multipleTable"
            :data="areaForm.warehouseAreasSaveList"
            tooltip-effect="dark"
            style="width: 100%"
            stripe
            :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
          >
            <el-table-column label="库区编号" prop="code" min-width="120">
              <template slot-scope="{ row, $index }">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + $index + '.code'"
                  :rules="areaRules.code"
                  v-if="row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    clearable
                    v-model="row.code"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ row.code }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区名称" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.name'"
                  :rules="areaRules.name"
                  v-if="scope.row.isEdit"
                  id="reservoirAreaRef"
                >
                  <el-input
                    placeholder="请输入"
                    clearable
                    v-model="scope.row.name"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区类型" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.type'"
                  :rules="areaRules.type"
                  id="reservoirAreaRef"
                  v-if="scope.row.isEdit"
                >
                  <el-select
                    v-model="scope.row.type"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, idx) in warehouseDefinition_areaType"
                      :key="idx"
                      :value="item.code"
                      :label="item.label"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <span v-else>{{
                  scope.row.type | filterAreaType(warehouseDefinition_areaType)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区属性" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'warehouseAreasSaveList.' + scope.$index + '.attribute'
                  "
                  :rules="areaRules.attribute"
                  v-if="scope.row.isEdit"
                >
                  <el-select
                    v-model="scope.row.attribute"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, idx) in warehouseDefinition_areaAttribute"
                      :key="idx"
                      :value="item.code"
                      :label="item.label"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <span v-else>{{
                  scope.row.attribute
                    | filterAreaType(warehouseDefinition_areaAttribute)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区位置" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.address'"
                  :rules="areaRules.address"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    clearable
                    v-model="scope.row.address"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.address }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区长(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'warehouseAreasSaveList.' + scope.$index + '.areaLength'
                  "
                  :rules="areaRules.areaLength"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    clearable
                    @mousewheel.native.prevent
                    v-model.number="scope.row.areaLength"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.areaLength }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区宽(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.areaWide'"
                  :rules="areaRules.areaWide"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    clearable
                    @mousewheel.native.prevent
                    v-model.number="scope.row.areaWide"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.areaWide }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库区高(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.areaHigh'"
                  :rules="areaRules.areaHigh"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.areaHigh"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.areaHigh }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架数量" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'warehouseAreasSaveList.' + scope.$index + '.num'"
                  :rules="areaRules.num"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    @input="
                      (value) =>
                        (scope.row.num = value.replace(/^(0+)|[^\d]+/g, ''))
                    "
                    v-model.number="scope.row.num"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.num }}</span>
              </template>
            </el-table-column>

            <!-- <el-table-column label="库区条码">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'warehouseAreasSaveList.' + scope.$index + 'areaBarcode'
                  "
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="自动生成"
                    disabled
                    v-model="scope.row.areaBarcode"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.areaBarcode }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="备注" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'warehouseAreasSaveList.' + scope.$index + 'areaRemark'
                  "
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="textarea"
                    clearable
                    :rows="1"
                    v-model="scope.row.areaRemark"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.areaRemark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="{ row, $index }">
                <el-button
                  type="text"
                  v-if="row.isEdit"
                  @click="saveArea($index)"
                  >保存</el-button
                >

                <el-button type="text" v-else @click="addShelf(row, $index)"
                  >添加货架</el-button
                >
                <el-button type="text" @click="remove($index, row)"
                  >删除库区</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <!-- <div
      class="area"
      v-if="
        areaForm.areaGoodsshelvesList &&
        areaForm.areaGoodsshelvesList.length !== 0
      "
    > -->
    <div class="area">
      <div class="mt20 reservoirArea">
        <span>货架</span>
      </div>
      <div class="mt10">
        <el-form :model="areaForm" ref="areaCoodsForm" class="areaForm">
          <el-table
            ref="multipleTable"
            :data="areaForm.areaGoodsshelvesList"
            tooltip-effect="dark"
            style="width: 100%"
            stripe
            :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
          >
            <el-table-column
              label="库区编号"
              prop="warehouseAreaCode"
            ></el-table-column>
            <el-table-column
              label="货架编号"
              prop="goodsshelvesCode"
              min-width="120"
            >
              <template slot-scope="{ row, $index }">
                <el-form-item
                  :prop="'areaGoodsshelvesList.' + $index + '.goodsshelvesCode'"
                  :rules="areaCoodsRules.goodsshelvesCode"
                  v-if="row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    clearable
                    v-model="row.goodsshelvesCode"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ row.goodsshelvesCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架行数" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' + scope.$index + '.goodsshelvesLine'
                  "
                  :rules="areaCoodsRules.goodsshelvesLine"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @input="
                      (value) =>
                        (scope.row.goodsshelvesLine = value.replace(
                          /^(0+)|[^\d]+/g,
                          ''
                        ))
                    "
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsshelvesLine"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesLine }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架列数" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' +
                    scope.$index +
                    '.goodsshelvesColumn'
                  "
                  :rules="areaCoodsRules.goodsshelvesColumn"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @input="
                      (value) =>
                        (scope.row.goodsshelvesColumn = value.replace(
                          /^(0+)|[^\d]+/g,
                          ''
                        ))
                    "
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsshelvesColumn"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesColumn }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架长(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' +
                    scope.$index +
                    '.goodsshelvesLength'
                  "
                  :rules="areaCoodsRules.goodsshelvesLength"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsshelvesLength"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesLength }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架宽(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' + scope.$index + '.goodsshelvesWide'
                  "
                  :rules="areaCoodsRules.goodsshelvesWide"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsshelvesWide"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesWide }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货架高(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' + scope.$index + '.goodsshelvesHigh'
                  "
                  :rules="areaCoodsRules.goodsshelvesHigh"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsshelvesHigh"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesHigh }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货位数量" prop="" min-width="120">
              <template slot-scope="{ row }">
                {{
                  Number.isNaN(row.goodsshelvesLine * row.goodsshelvesColumn)
                    ? ''
                    : row.goodsshelvesLine * row.goodsshelvesColumn
                }}
              </template>
            </el-table-column>
            <el-table-column label="是否规则" prop="isRegular" min-width="120">
              <template slot-scope="{ row }">
                <el-select v-model="row.isRegular" v-if="row.isEdit">
                  <el-option
                    v-for="item in warehouseDefinition_isRegular"
                    :key="item.code"
                    :value="item.code"
                    :label="item.label"
                  ></el-option>
                </el-select>
                <template v-else>
                  {{
                    row.isRegular
                      | filterAreaType(warehouseDefinition_isRegular)
                  }}
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="货架条码"
              prop="goodsshelvesBarcode"
            ></el-table-column> -->
            <el-table-column label="备注" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'areaGoodsshelvesList.' +
                    scope.$index +
                    '.goodsshelvesRemark'
                  "
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.goodsshelvesRemark"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsshelvesRemark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" min-width="120">
              <template slot-scope="{ $index, row }">
                <el-button
                  type="text"
                  v-if="row.isEdit"
                  @click="saveGoods($index, row)"
                  >保存</el-button
                >
                <el-button type="text" @click="removeGoods($index, row)"
                  >删除货架</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>

    <!-- <div
      class="area"
      v-if="
        areaForm.allocationReqList && areaForm.allocationReqList.length !== 0
      "
    > -->
    <div class="area">
      <div class="mt20 reservoirArea">
        <span>货位</span>
        <!-- <el-button type="primary" @click="reuse">复用</el-button> -->
      </div>
      <div class="mt10">
        <el-form :model="areaForm" ref="allocationForm" class="areaForm">
          <el-table
            ref="multipleTable"
            :data="areaForm.allocationReqList"
            tooltip-effect="dark"
            style="width: 100%"
            stripe
            :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
          >
            <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
            <el-table-column label="货架编号" prop="warehouseAreaGoodsCode">
              <template slot-scope="{ row }">
                {{ getWarehouseAreaGoodsCode(row) }}
              </template>
            </el-table-column>
            <el-table-column
              label="货位编号"
              prop="goodsAllocationCode"
              min-width="120"
            >
              <template slot-scope="{ row, $index }">
                <el-form-item
                  :prop="'allocationReqList.' + $index + '.goodsAllocationCode'"
                  :rules="areaLocationRules.goodsAllocationCode"
                  v-if="row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    clearable
                    v-model="row.goodsAllocationCode"
                  ></el-input>
                </el-form-item>
                <span v-else>{{ row.goodsAllocationCode }}</span>
              </template></el-table-column
            >
            <el-table-column label="货位长(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'allocationReqList.' +
                    scope.$index +
                    '.goodsAllocationLength'
                  "
                  :rules="areaLocationRules.allocationReq"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    @blur="
                      onBlur(
                        scope.row,
                        'goodsAllocationLength',
                        'goodsshelvesLength'
                      )
                    "
                    v-model.number="scope.row.goodsAllocationLength"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsAllocationLength }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货位宽(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'allocationReqList.' + scope.$index + '.goodsAllocationWide'
                  "
                  v-if="scope.row.isEdit"
                  :rules="areaLocationRules.allocationReq"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsAllocationWide"
                    @blur="
                      onBlur(
                        scope.row,
                        'goodsAllocationWide',
                        'goodsshelvesWide'
                      )
                    "
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsAllocationWide }}</span>
              </template>
            </el-table-column>
            <el-table-column label="货位高(cm)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'allocationReqList.' + scope.$index + '.goodsAllocationHigh'
                  "
                  v-if="scope.row.isEdit"
                  :rules="areaLocationRules.allocationReq"
                >
                  <el-input
                    placeholder="请输入"
                    @blur="
                      onBlur(
                        scope.row,
                        'goodsAllocationHigh',
                        'goodsshelvesHigh'
                      )
                    "
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.goodsAllocationHigh"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.goodsAllocationHigh }}</span>
              </template>
            </el-table-column>
            <el-table-column label="限重(kg)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'allocationReqList.' + scope.$index + '.weightLimit'"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.weightLimit"
                    clearable
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.weightLimit }}</span>
              </template>
            </el-table-column>
            <el-table-column label="基本货位容积(cm³)" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'allocationReqList.' + scope.$index + '.volumeUnit'"
                  v-if="scope.row.isEdit"
                >
                  <el-input
                    placeholder="请输入"
                    type="number"
                    @mousewheel.native.prevent
                    v-model.number="scope.row.volumeUnit"
                    disabled
                  ></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.volumeUnit }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="货位条码"
              prop="allocationBarcode"
            ></el-table-column> -->
          </el-table>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  // import selectTree from '@/components/selectTree';

  // import {
  //   warehouseDefinition_areaType,
  //   warehouseDefinition_areaAttribute,
  //   warehouseDefinition_isRegular,
  //   useDictLabelFilter
  // } from '@/utils/dict/index'

  // import {
  //   warehouseGoodsshelvesSave,
  //   warehouseDetails,
  //   existGoods
  // } from '@/api/stockManagement/warehouseDefinition';
  // import { pushZero } from '@/utils/index';
  // import { throttle } from 'lodash';
  export default {
    // components: { selectTree },
    // filters: {
    //   filterAreaType: useDictLabelFilter
    // },
    data() {
      // const msg = throttle(
      //   () => this.$message.error('货架总体积不能大于库区体积！'),
      //   500
      // );

      const allocationReqValidator = (column, value, callback) => {
        if (!value) {
          callback(new Error('不能为空！'));
        } else {
          // 货位体积限制
          const index = +column.field.split('.')[1];
          const row = this.areaForm.allocationReqList[index];

          const parent = this.areaForm.areaGoodsshelvesList.find(
            (t) => t.code === row.goodsshelvesCode
          );

          let sameParentSavedSum = this.areaForm.allocationReqList
            .filter((t) => t.warehouseAreaGoodsCode === row.goodsshelvesCode)
            .reduce((sum, item) => {
              if (!item.isEdit) {
                sum +=
                  item.goodsAllocationLength *
                  item.goodsAllocationWide *
                  item.goodsAllocationHigh;
              }
              return sum;
            }, 0);

          if (parent) {
            const max =
              parent.goodsshelvesLength *
              parent.goodsshelvesWide *
              parent.goodsshelvesHigh;

            if (
              max - sameParentSavedSum <
              row.goodsAllocationLength *
                row.goodsAllocationWide *
                row.goodsAllocationHigh
            ) {
              msg();
              callback(new Error('货架总体积不能大于库区体积！'));
              return;
            }
          }
          callback();
        }
      };

      return {
        warehouseDefinition_isRegular,
        warehouseDefinition_areaType,
        warehouseDefinition_areaAttribute,
        loading: false,
        areaForm: {
          warehouseAreasSaveList: [], //库区
          areaGoodsshelvesList: [], //货架
          allocationReqList: [] //货位
        },
        areaCoodsRules: {
          goodsshelvesCode: {
            required: true,
            message: '请输入货架编号',
            trigger: 'blur'
          },
          goodsshelvesLine: {
            required: true,
            message: '请输入货架行',
            trigger: 'blur'
          },
          goodsshelvesColumn: {
            required: true,
            message: '请输入货架列',
            trigger: 'blur'
          },
          goodsshelvesLength: {
            required: true,
            message: '请输入货架长',
            trigger: 'blur'
          },
          goodsshelvesWide: {
            required: true,
            message: '请输入货架宽',
            trigger: 'blur'
          },
          goodsshelvesHigh: {
            required: true,
            message: '请输入货架高',
            trigger: 'blur'
          }
        },
        areaLocationRules: {
          goodsAllocationCode: {
            required: true,
            message: '请输入货位编号',
            trigger: 'blur'
          },
          allocationReq: {
            required: true,
            validator: allocationReqValidator,
            trigger: 'blur'
          }
        },
        isPageEdit: false,
        areaRules: {
          code: { required: true, message: '请输入库区编号', trigger: 'blur' },
          name: { required: true, message: '请输入库区名称', trigger: 'blur' },
          type: {
            required: true,
            message: '请选择库区类型',
            trigger: 'change'
          },
          attribute: {
            required: true,
            message: '请选择库区属性',
            trigger: 'change'
          },
          address: {
            required: true,
            message: '请输入库区位置',
            trigger: 'blur'
          },
          areaLength: {
            required: true,
            message: '请输入库区长',
            trigger: 'blur'
          },
          areaWide: {
            required: true,
            message: '请输入库区宽',
            trigger: 'blur'
          },
          areaHigh: {
            required: true,
            message: '请输入库区高',
            trigger: 'blur'
          },
          num: { required: true, message: '请输入货架数量', trigger: 'blur' }
        },
        areaDisabled: true,
        addressDisabled: true,
        ownerNameDisabled: true,
        areaList: [],
        inventoryList: [
          { value: '1', name: '物料库' },
          { value: '2', name: '产品库' },
          { value: '3', name: '设备库' }
        ],
        statusList: [
          { value: '0', name: '失效' },
          { value: '1', name: '生效' }
        ],
        formData: {
          code: '',
          name: '',
          inventoryType: '',
          factoryName: '',
          factoryId: '',
          ownerId: '',
          ownerName: '',
          contact: '',
          status: '',
          city: '',
          area: '',
          address: '',
          remarks: '',
          departmentCode: '',
          departmentName: ''
        },
        factoryList: [], //所属工厂
        staffList: [],
        multipleSelection: [],
        shelfObj: {},
        longWidthHeightBol: false,
        savedWarehouse: [],
        savedShelves: []
      };
    },
    computed: {},
    created() {
      // const { query } = this.$route;
      // this.formData.code = query.code;
      // this.formData.name = query.name;
      // this.formData.id = query.id;
      // this.getDetail(query.id);
    },

    methods: {
      async getDetail(id) {
        const res = await warehouseDetails({ id });

        if (res?.success) {
          this.areaForm = {
            warehouseAreasSaveList: res.data.warehouseAreasSaveList, //库区
            areaGoodsshelvesList: res.data.areaGoodsshelvesList, //货架
            allocationReqList: res.data.allocationReqList //货位
          };

          this.formData = res.data.warehouseSaveReq;
          //已保存库区货位 ，删除时判断
          this.savedWarehouse = res.data.warehouseAreasSaveList.map(
            (i) => i.id
          );
          this.savedShelves = res.data.areaGoodsshelvesList.map((i) => i.id);
        }
      },
      checkVolume() {
        let falg = true;
        let warehouseAreasSaveList = this.areaForm.warehouseAreasSaveList.map(
          (item) => {
            return {
              id: item.id,
              volumu: item.areaHigh * item.areaLength * item.areaWide
            };
          }
        );

        let areaGoodsshelvesList = this.areaForm.areaGoodsshelvesList.map(
          (item) => {
            return {
              id: item.warehouseAreaId,
              volumu:
                item.goodsshelvesHigh *
                item.goodsshelvesLength *
                item.goodsshelvesWide
            };
          }
        );

        warehouseAreasSaveList.forEach((item) => {
          let arr = areaGoodsshelvesList.filter((it) => it.id == item.id);
          let num = arr.reduce((val, it) => val + it.volumu, 0);
          if (num > item.volumu) {
            falg = false;
          }
        });
        return falg;
      },
      editInfo(index) {
        let obj = this.areaForm.warehouseAreasSaveList[index];
        if (obj.isEdit) {
          this.$set(
            this.areaForm.warehouseAreasSaveList[index],
            'isEdit',
            false
          );
        } else {
          this.$set(
            this.areaForm.warehouseAreasSaveList[index],
            'isEdit',
            true
          );
        }
      },
      addShelf(row, index) {
        this.$prompt('请输入', '添加货架数', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /[1-9]\d*/,
          inputErrorMessage: '请输入正整数'
        })
          .then(({ value }) => {
            row.num = +row.num + +value;
            let obj = this.areaForm.warehouseAreasSaveList[index];

            const pre =
              this.areaForm.areaGoodsshelvesList[
                this.areaForm.areaGoodsshelvesList.length - 1
              ];
            let preCode = 0;
            if (pre) {
              preCode = +(pre.goodsshelvesCode?.substr(1) || 0);
            }
            for (var i = 0; i < value; i++) {
              this.areaForm.areaGoodsshelvesList.push({
                warehouseAreaCode: obj.code,
                warehouseAreaId: obj.id,
                warehouseAreaName: obj.name,
                goodsshelvesCode: ``,
                goodsshelvesLine: '',
                goodsshelvesColumn: '',
                goodsshelvesLength: '',
                goodsshelvesWide: '',
                goodsshelvesHigh: '',
                isRegular: 1,
                // goodsshelvesBarcode: '',
                goodsshelvesRemark: '',
                warehouseName: this.formData.name,
                isEdit: true
              });
            }
          })
          .catch(() => {});
        // let obj = this.areaForm.warehouseAreasSaveList[index],
        //   list = this.areaForm.areaGoodsshelvesList.filter(
        //     item => item.warehouseAreaCode === obj.code
        //   )
        // if (obj.id) {
        //   if (list.length == obj.num)
        //     return this.$message.error('添加货架数量达到上限')
        //   let num = obj.num - list.length
        //   for (var i = 0; i < num; i++) {
        //     this.areaForm.areaGoodsshelvesList.push({
        //       warehouseAreaCode: obj.code,
        //       warehouseAreaId: obj.id,
        //       warehouseAreaName: obj.name,
        //       goodsshelvesCode: `C${pushZero(
        //         this.areaForm.areaGoodsshelvesList.length + 1
        //       )}`,
        //       goodsshelvesLine: '',
        //       goodsshelvesColumn: '',
        //       goodsshelvesLength: '',
        //       goodsshelvesWide: '',
        //       goodsshelvesHigh: '',
        //       // goodsshelvesBarcode: '',
        //       goodsshelvesRemark: '',
        //       warehouseName: this.formData.name,
        //       isEdit: true
        //     })
        //   }
        // } else {
        //   this.saveArea(index)
        // }
      },
      onBlur(item, name, name1) {
        // name当前货位的长宽高,name1货架的长宽高

        if (
          item.goodsAllocationHigh &&
          item.goodsAllocationLength &&
          item.goodsAllocationWide
        ) {
          item.volumeUnit =
            item.goodsAllocationHigh *
            item.goodsAllocationLength *
            item.goodsAllocationWide;
        }
      },
      saveGoods(index, row) {
        // 需要校验的字段 areaGoodsshelvesList
        let list = Object.keys(this.areaCoodsRules),
          obj = this.areaForm.areaGoodsshelvesList[index],
          flag = true;

        list.forEach((item) => {
          this.$refs.areaCoodsForm.validateField(
            'areaGoodsshelvesList.' + index + '.' + item,
            (valid) => {
              if (valid) {
                flag = false;
              }
            }
          );
        });

        // 库区体积限制
        const parent = this.areaForm.warehouseAreasSaveList.find(
          (t) => t.code === row.warehouseAreaCode
        );

        if (
          this.areaForm.areaGoodsshelvesList.filter(
            (item) =>
              item.goodsshelvesCode === row.goodsshelvesCode &&
              row.warehouseAreaCode === item.warehouseAreaCode
          ).length > 1
        ) {
          return this.$message.error('货架编号不能重复！');
        }
        const savedSum = this.areaForm.areaGoodsshelvesList
          .filter((t) => t.warehouseAreaCode === row.warehouseAreaCode)
          .reduce((sum, item) => {
            if (!item.isEdit) {
              sum +=
                item.goodsshelvesLength *
                item.goodsshelvesWide *
                item.goodsshelvesHigh;
            }
            return sum;
          }, 0);
        if (parent) {
          const max = parent.areaLength * parent.areaWide * parent.areaHigh;

          if (
            max - savedSum <
            row.goodsshelvesLength * row.goodsshelvesWide * row.goodsshelvesHigh
          ) {
            return this.$message.error('货架总体积不能大于库区体积！');
          }
        }

        if (flag) {
          this.$set(obj, 'isEdit', false);
          this.shelfObj = obj; //储存货架对象
          let num = obj.goodsshelvesLine * obj.goodsshelvesColumn;

          this.areaIndex = index;
          this.generateAllocation(num, obj);
        }
      },
      generateAllocation(num, obj) {
        console.log('obj', obj);
        const pre =
          this.areaForm.allocationReqList[
            this.areaForm.allocationReqList.length - 1
          ];

        for (var i = 0; i < num; i++) {
          this.areaForm.allocationReqList.push({
            // allocationBarcode: '',
            allocationRemark: '',
            allocationStatus: 1,
            departmentName: this.formData.departmentName,
            goodsAllocationCode: ``,
            goodsAllocationHigh: '',
            goodsAllocationLength: '',
            goodsAllocationWide: '',
            ownerName: this.formData.ownerName,
            volumeUnit: '',
            warehouseAreaGoodsCode: obj.goodsshelvesCode,
            warehouseAreaGoodsId: obj.id,
            warehouseAreaGoodsName: obj.name,
            warehouseAreaId: obj.warehouseAreaId, //?
            warehouseAreaName: obj.warehouseAreaName,
            warehouseAreaCode: obj.warehouseAreaCode,
            warehouseId: this.id, //?
            warehouseName: this.formData.name,
            weightLimit: '',
            isEdit: true
          });
        }
      },
      saveArea(index) {
        let flag = true;
        Object.keys(this.areaRules).forEach((item) => {
          this.$refs.areaFormName.validateField(
            'warehouseAreasSaveList.' + index + '.' + item,
            (valid) => {
              if (valid) {
                // rej()
                flag = false;
              }
            }
          );
        });

        if (!flag) return;
        if (
          this.areaForm.warehouseAreasSaveList.filter(
            (item) =>
              item.code === this.areaForm.warehouseAreasSaveList[index].code
          ).length > 1
        ) {
          return this.$message.error('库区编号不能重复！');
        }

        // let list = this.areaForm.areaGoodsshelvesList.filter(
        //   item =>
        //     item.warehouseAreaCode ===
        //     this.areaForm.warehouseAreasSaveList[index].code
        // )
        // if (list.length == this.areaForm.warehouseAreasSaveList[index].num) {
        //   // this.$message.error('添加货架数量达到上限')
        //   return
        // }

        this.$set(this.areaForm.warehouseAreasSaveList[index], 'isEdit', false);

        let obj = this.areaForm.warehouseAreasSaveList[index];
        let num = this.areaForm.warehouseAreasSaveList[index].num;

        const pre =
          this.areaForm.areaGoodsshelvesList[
            this.areaForm.areaGoodsshelvesList.length - 1
          ];
        let preCode = 0;
        if (pre) {
          preCode = +(pre.goodsshelvesCode?.substr(1) || 0);
        }

        for (var i = 0; i < num; i++) {
          this.areaForm.areaGoodsshelvesList.push({
            warehouseAreaCode: obj.code,
            warehouseAreaId: obj.id,
            warehouseAreaName: obj.name,
            warehouseAreaId: this.id,
            goodsshelvesCode: ``,
            goodsshelvesLine: '',
            goodsshelvesColumn: '',
            goodsshelvesLength: '',
            goodsshelvesWide: '',
            goodsshelvesHigh: '',
            // goodsshelvesBarcode: '',
            goodsshelvesRemark: '',
            warehouseName: this.formData.name,
            isEdit: true,
            isRegular: 1
          });
        }
      },
      async removeGoods(idx, { id, goodsshelvesCode, warehouseAreaCode }) {
        if (
          this.areaForm.areaGoodsshelvesList.filter(
            (item) => item.warehouseAreaCode === warehouseAreaCode
          ).length === 1
        ) {
          return this.$message.error('至少保留一个货架！');
        }
        if (this.savedShelves.includes(id)) {
          let list = this.areaForm.allocationReqList
            .filter((item) => item.warehouseAreaGoodsCode === goodsshelvesCode)
            .map((i) => i.id);

          const res = await existGoods(list);

          if (res?.success && res.data) {
            return this.$message.error('此货架下货位有关联货物，无法删除！');
          }
        }

        this.areaForm.allocationReqList =
          this.areaForm.allocationReqList.filter(
            (item) =>
              item.warehouseAreaGoodsCode !== goodsshelvesCode ||
              warehouseAreaCode !== item.warehouseAreaCode
          );
        let areasIndex = this.areaForm.warehouseAreasSaveList.findIndex(
          (item) =>
            item.code ===
            this.areaForm.areaGoodsshelvesList[idx].warehouseAreaCode
        );
        this.areaForm.areaGoodsshelvesList.splice(idx, 1);
        if (this.areaForm.warehouseAreasSaveList[areasIndex].num - 1 <= 0) {
          this.areaForm.warehouseAreasSaveList.splice(areasIndex, 1);
        } else {
          this.$set(
            this.areaForm.warehouseAreasSaveList[areasIndex],
            'num',
            this.areaForm.warehouseAreasSaveList[areasIndex].num - 1
          );
        }
      },
      async remove(index, { id, code }) {
        // 判断关联货物
        console.log(this.savedWarehouse, id, this.savedWarehouse.includes(id));
        if (this.savedWarehouse.includes(id)) {
          let list = this.areaForm.areaGoodsshelvesList
            .filter((item) => item.warehouseAreaCode === code)
            .map((i) =>
              this.areaForm.allocationReqList.filter(
                (item) => item.warehouseAreaGoodsCode === i.goodsshelvesCode
              )
            )
            .flat()
            .map((i) => i.id);

          const res = await existGoods(list);

          if (res?.success && res.data) {
            return this.$message.error('此库区下货位有关联货物，无法删除！');
          }
        }
        // 货架code
        let list = [];
        this.areaForm.areaGoodsshelvesList.forEach((item) => {
          if (item.warehouseAreaCode === code) {
            list.push(item.goodsshelvesCode);
          }
        });
        this.areaForm.areaGoodsshelvesList =
          this.areaForm.areaGoodsshelvesList.filter(
            (item) => item.warehouseAreaCode !== code
          );

        this.areaForm.allocationReqList =
          this.areaForm.allocationReqList.filter(
            (item) =>
              !list.includes(item.warehouseAreaGoodsCode) ||
              code !== item.warehouseAreaCode
          );
        this.areaForm.warehouseAreasSaveList.splice(index, 1);
      },
      addArea() {
        const pre =
          this.areaForm.warehouseAreasSaveList[
            this.areaForm.warehouseAreasSaveList.length - 1
          ];
        let preCode = 0;
        if (pre) {
          preCode = +(pre.code?.substr(1) || 0);
        }

        this.areaForm.warehouseAreasSaveList.push({
          code: ``,
          name: '',
          type: '',
          attribute: '',
          address: '',
          areaLength: '',
          areaWide: '',
          areaHigh: '',
          num: '',
          // areaBarcode: '',
          areaRemark: '',
          warehouseName: this.formData.name,
          warehouseCode: this.formData.code,
          isEdit: true
        });
      },
      submit() {
        if (this.areaForm.warehouseAreasSaveList.length === 0) {
          return this.$message.error('请添加库区');
        }
        if (this.areaForm.allocationReqList.length === 0) {
          return this.$message.error('请添加货位');
        }
        if (this.areaForm.areaGoodsshelvesList.length === 0) {
          return this.$message.error('请添加货架');
        }
        if (!this.checkVolume()) {
          return this.$message.error('货架总体积不能大于库区体积！');
        }

        let obj = {};
        for (const item of this.areaForm.allocationReqList) {
          const area = this.areaForm.areaGoodsshelvesList.find((itm) => {
            return (
              itm.warehouseAreaName === item.warehouseAreaName &&
              itm.goodsshelvesCode === item.warehouseAreaGoodsCode
            );
          });

          const id = `${
            area && area.warehouseAreaCode + '-' + item.warehouseAreaGoodsCode
          }-${item.goodsAllocationCode}`;

          if (obj[id]) {
            return this.$message.error('货位编号不能重复！');
          } else {
            obj[id] = 1;
          }
        }

        this.$refs.areaFormName.validate(async (valid) => {
          if (valid) {
            this.$refs.areaCoodsForm.validate(async (valid) => {
              if (valid) {
                this.$refs.allocationForm.validate(async (valid) => {
                  if (valid) {
                    let params = {
                      warehouseSaveReq: this.formData,
                      allocationReqList: this.areaForm.allocationReqList,
                      areaGoodsshelvesList: this.areaForm.areaGoodsshelvesList,
                      warehouseAreasSaveList:
                        this.areaForm.warehouseAreasSaveList
                    };
                    this.loading = true;
                    try {
                      let res = await warehouseGoodsshelvesSave(params);
                      if (res.success) {
                        this.$message.success('保存成功');
                        this.$router.push({
                          path: '/warehouseManagement/warehouseDefinition'
                        });
                      }
                    } catch (error) {}
                    this.loading = false;
                  }
                });
              }
            });
          }
        });
      },
      // 货位组装货架编号
      getWarehouseAreaGoodsCode(row) {
        console.log(row);
        const { warehouseAreaGoodsCode, warehouseAreaCode } = row;
        const obj = this.areaForm.areaGoodsshelvesList.find((item) => {
          return (
            item.warehouseAreaCode === warehouseAreaCode &&
            item.goodsshelvesCode === warehouseAreaGoodsCode
          );
        });
        return obj && obj.warehouseAreaCode + '-' + warehouseAreaGoodsCode;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .p20 {
    padding: 20px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .mt10 {
    margin-top: 10px;
  }
  ::v-deep .el-select {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 22px;
  }
  .areaForm {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .warehouseAdd {
    .el-row {
      display: block;
    }
    header {
      display: flex;
      justify-content: space-between;
      .title {
        font-size: 20px;
        color: #333;
        font-weight: bold;
      }
    }
  }
  .reservoirArea {
    display: flex;
    justify-content: space-between;
    span {
      font-size: 14px;
    }
  }
  .center {
    text-align: center;
  }
  .el-select {
    display: block;
  }
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
</style>
