<template>
  <ele-modal
    title="新建领料单"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :maxable="true"
    width="90%"
  >
    <div>
      <el-form :model="pickForm" ref="pickForm">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="领料单编号" prop="pickCode" label-width="90px">
              <el-input v-model="pickForm.pickCode" disabled=""></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="领料单名称" prop="pickName" label-width="90px">
              <el-input v-model="pickForm.pickName"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-button type="primary" @click="openPicking">添加物料</el-button>
            <el-button type="primary" @click="batchDelete">批量删除</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-form>
        <el-table
          ref="form222"
          class="table_content"
          :max-height="300"
          :data="objPick.pickList"
          tooltip-effect="dark"
          style="width: 100%"
          stripe
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column label="序号" type="index" width="60">
            <template slot-scope="{ row, $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>

          <el-table-column label="类型" prop="rootCategoryLevelId" width="80">
            <template slot-scope="{ row, $index }">
              <el-tag size="mini">{{
                typeName[Number(row.rootCategoryLevelId)]
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="编码" prop="assetCode" show-overflow-tooltip>
            <template slot-scope="{ row, $index }">
              <span
                v-if="
                  Object.prototype.hasOwnProperty.call(row, 'isBom') &&
                  row.isBom == 1
                "
                style="color: #faad14"
              >
                {{ row.categoryCode }}
              </span>
              <span>
                {{
                  row.rootCategoryLevelId == 4 ? row.codeNumber : row.code
                }}</span
              >
            </template>
          </el-table-column>

          <el-table-column label="批次号" prop="batchNo" show-overflow-tooltip>
          </el-table-column>

          <el-table-column label="名称" prop="name" show-overflow-tooltip>
            <template slot-scope="{ row, $index }">
              <span
                v-if="
                  Object.prototype.hasOwnProperty.call(row, 'isBom') &&
                  row.isBom == 1
                "
              >
                {{ row.categoryName }}
              </span>
              <span> {{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="modelType" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="规格"
            prop="specification"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column label="数量" prop="demandQuantity">
            <template slot-scope="{ row, $index }">
              <el-form-item>
                <el-input
                  v-model="row.demandQuantity"
                  @input="
                    row.demandQuantity > row.measureQuantity
                      ? (row.demandQuantity = row.measureQuantity)
                      : row.demandQuantity
                  "
                  size="mini"
                >
                  <template slot="append">{{ row.measuringUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="计量库存数量" prop="measureQuantity">
            <template slot-scope="{ row, $index }">
              {{ row.measureQuantity }} {{ row.measuringUnit }}
            </template>
          </el-table-column>

          <el-table-column
            label="领料仓库"
            prop="warehouseId"
            show-overflow-tooltip
          >
            <template slot-scope="{ row, $index }">
              <div>
                <el-select
                  v-model="row.warehouseId"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in row.warehouseList"
                    :label="item.warehouse_name"
                    :value="item.warehouse_id"
                    :key="item.warehouse_id"
                  >
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="100px">
            <template slot-scope="{ $index, row }">
              <el-link type="danger" @click="removeItem($index)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <template slot="footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="save()">确 定</el-button>
    </template>

    <newPickingList
      isType="pick"
      ref="pickingListRef"
      @allSelection="allSelection"
    ></newPickingList>
  </ele-modal>
</template>

<script>
  import { getCode } from '@/api/produce/workOrder';
  import newPickingList from './newPickingList.vue';
  import { typeName } from '@/views/produce/components/common.js';

  import { unproductive } from '@/api/produce/picking';
  export default {
    components: {
      newPickingList
    },
    data() {
      return {
        visible: true,

        typeName,

        pickForm: {
          pickCode: null,
          pickName: null
        },
        objPick: {
          pickList: []
        },
        selectionData: []
      };
    },
    created() {
      this.getOrderCode();
    },

    methods: {
      async getOrderCode() {
        this.pickForm.pickCode = await getCode('pick_order_code');
      },

      openPicking() {
        this.$refs.pickingListRef.open(null, this.objPick);
      },

      allSelection(id, list) {
        // this.objPick = {
        //   pickList: list
        // };
        list.forEach((item) => {
          item.code = item.categoryCode;
          item.name = item.categoryName;
          item.modelType = item.categoryModel;
          item.measuringUnit = item.measuringUnit
            ? item.measuringUnit
            : item.measureUnit;
          item.unit = item.unit ? item.unit : item.measureUnit;
        });

        const newData = [];

        if (list.length != 0) {
          list.forEach((it) => {
            newData.push(this.deepCopy(it));
          });
        }

        this.objPick = {
          pickList: newData
        };
        this.$forceUpdate();
      },

      deepCopy(obj, hash = new WeakMap()) {
        if (obj === null) return null;
        if (obj instanceof Date) return new Date(obj);
        if (obj instanceof RegExp) return new RegExp(obj);
        if (typeof obj !== 'object' && typeof obj !== 'function') return obj;
        if (hash.has(obj)) return hash.get(obj);

        const result = Array.isArray(obj) ? [] : {};
        hash.set(obj, result);

        return Object.keys(obj).reduce((acc, key) => {
          acc[key] = this.deepCopy(obj[key], hash);
          return acc;
        }, result);
      },

      batchDelete() {
        if (this.selectionData.length == 0) {
          return this.$message.warning('请选择需要删除的领料数据！');
        }

        this.$confirm('此操作将删除领料数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            for (let item of this.selectionData) {
              const findIndex = this.objPick.pickList.findIndex(
                (it) => item.id == it.id
              );

              this.objPick.pickList.splice(findIndex, 1);
            }
          })
          .catch(() => {});
      },

      handleSelectionChange(val) {
        this.selectionData = val;
      },

      removeItem(index) {
        this.objPick.pickList.splice(index, 1);
      },

      save() {
        if (this.objPick.pickList.length == 0) {
          this.$message.warning('请选择物料');
          return false;
        }
        if (this.objPick.pickList.length > 0) {
          let name;
          let bol2;
          let _i;

          bol2 = this.objPick.pickList.every((e, i) => {
            _i = i;
            name = e.name;
            // e.categoryId = e.id;
            // e.id = e.categoryId
            return (
              Object.prototype.hasOwnProperty.call(e, 'demandQuantity') &&
              Number(e.demandQuantity) > 0 &&
              e.warehouseId
            );
          });

          if (!bol2) {
            this.$message.warning(
              `${this.objPick.pickList[_i].code}的${name}数据不能为空`
            );
            return false;
          }
        }

        let param = {
          detailList: this.objPick.pickList,
          name: this.pickForm.pickName,
          code: this.pickForm.pickCode
        };

        unproductive(param).then((res) => {
          this.$message.success('领料成功');
          this.$emit('close', true);
        });
      },

      handleClose() {
        this.$emit('close');
      }
    }
  };
</script>

<style lang="scss" scoped></style>
