<template>
  <div class="app-container">
    <el-descriptions title="基本信息"> </el-descriptions>
    <el-form
      :model="form"
      ref="Form"
      size="small"
      :inline="true"
      label-width="120px"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="storeOdd" label="入库单号">
            <el-input
              v-model="form.storeOdd"
              placeholder="不输入自动生成"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库订单名称" prop="storeOddName">
            <el-input
              v-model="form.storeOddName"
              placeholder="请输入入库订单名称"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库单位" prop="storeUnit">
            <el-select
              v-model="form.storeUnit"
              placeholder="请选择入库单位"
              style="width: 300px"
            >
              <el-option label="斤" value="斤" />
              <el-option label="瓶" value="瓶" />
              <el-option label="包" value="包" />
              <el-option label="个" value="个" />
            </el-select>
            <br />
            <span>入库时，请按照售卖出库时，最小单位入库，以免利润计算错误</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库时间" prop="storeDate">
            <el-date-picker
              v-model="form.storeDate"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 300px"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <span slot="label"> <span style="color: red">*</span> 入库商品</span>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="selectProduct"
              >选择</el-button
            >
            <span style="margin-left: 10px"
              >选择需要入库的商品,再将对应商品规格进行入库，需填写规格单位与入库单位的换算值，如规格为箱，入库单位为斤，1箱约等于xx斤</span
            >
          </el-form-item>
        </el-col>
        <el-col
          :span="20"
          style="text-align: center"
          v-if="form.storeGoodsList.length > 0"
        >
          <el-form-item>
            <el-table
              :data="form.storeGoodsList"
              @selection-change="handleSelectionChange"
              row-key="id"
            >
              <el-table-column label="商品ID" align="center" prop="spuId" />
              <el-table-column label="商品名称" align="center" prop="spuName" />
              <el-table-column label="分类" align="center" prop="categoryName" />
              <el-table-column label="规格计量单位" align="center" prop="spuUnit" />
              <el-table-column label="skuId" align="center" prop="skuId" />
              <el-table-column label="规格名称" align="center" prop="skuSpecName">
                <template slot-scope="scope">
                  {{
                    scope.row.skuSpecName
                      ? JSON.parse(scope.row.skuSpecName)[0].specsName
                      : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column label="规格内容" align="center" prop="skuSpecName">
                <template slot-scope="scope">
                  {{
                    scope.row.skuSpecName
                      ? JSON.parse(scope.row.skuSpecName)[0].specsValue
                      : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column label="单位换算" align="center" width="200">
                <template slot-scope="scope">
                  <div style="display: flex; flex-direction: row; align-items: center">
                    <div style="width: 70px">1{{ scope.row.spuUnit }} ≈</div>
                    <el-input
                      v-model="scope.row.unitConversion"
                      clearable
                      style="widht: 70px"
                    >
                      <span slot="suffix">{{ form.storeUnit }}</span>
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="浮动重量" align="center" width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.floatingWeight"
                    clearable
                    oninput="value=value.replace(/[^\d.]/g,'')"
                  >
                    <span slot="suffix">{{ form.storeUnit }}</span>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="入库数量" align="center" width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.storeNum"
                    clearable
                    oninput="value=value.replace(/[^\d.]/g,'')"
                  >
                    <span slot="suffix">{{ scope.row.spuUnit }}</span>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="入库单价" align="center" width="150">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.storeUnitPrice"
                    clearable
                    oninput="value=value.replace(/[^\d.]/g,'')"
                  >
                    <span slot="suffix"> 元/{{ form.storeUnit }}</span>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="销售单价" align="center" width="150">
                <template slot-scope="scope">
                  {{ scope.row.salePrice }}元/{{ scope.row.spuUnit }}
                  <!-- <el-input
                    v-model="scope.row.salePrice"
                    clearable
                    oninput="value=value.replace(/[^\d.]/g,'')"
                  >
                    <span slot="suffix"> </span>
                  </el-input> -->
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="removetable(scope.row, scope.$index)"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产日期" prop="produceDate">
            <el-date-picker
              v-model="form.produceDate"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保质期" prop="shelfLife">
            <el-input-number
              v-model="form.shelfLife"
              @change="passValue"
              label="请输入保质期"
            ></el-input-number>
            <el-select
              v-model="form.shelfLifeUnit"
              placeholder="请选择"
              style="width: 100px"
            >
              <el-option label="天" :value="0" />
              <el-option label="月" :value="1" />
              <el-option label="年" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预警天数" prop="warningDay">
            <el-input-number
              v-model="form.warningDay"
              @change="passValue"
              label="请输入预警天数"
            ></el-input-number>

            <!-- <el-input
              v-model="form.warningDay"
              placeholder="请输入预警天数"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购员" prop="buyer">
            <el-input
              v-model="form.buyer"
              placeholder="请输入采购员"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
              v-model="form.supplierName"
              placeholder="请输入供应商名称"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商电话" prop="supplierPhone">
            <el-input
              v-model="form.supplierPhone"
              placeholder="请输入供应商电话"
              clearable
              style="width: 300px"
              show-word-limit
              @input="passValue"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              style="width: 1180px"
              type="textarea"
              placeholder="请输入内容"
              v-model="form.remark"
              maxlength="300"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 4 }"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer" style="text-align: center">
      <el-button @click="submitCancel">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="btnLading"
        >确认新增</el-button
      >
    </div>

    <el-dialog
      title="入库商品"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="handleClose"
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="120px"
      >
        <el-form-item prop="key" label="商品名称/ID">
          <el-input
            v-model="queryParams.key"
            placeholder="请输入商品名称/商品ID"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-cascader
            v-model="queryParams.categoryId"
            ref="formCascader"
            placeholder="请选择分类"
            :props="categoryprops"
            style="width: 240px"
            @change="cascaderChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getTableList"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="productList"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品ID" align="center" prop="spuId" />
        <el-table-column label="商品名称" align="center" prop="spuName" />
        <el-table-column label="分类" align="center" prop="categoryName" />
        <el-table-column label="实际库存" align="center">
          <template slot-scope="scope">
            {{ scope.row.skuStock }}{{ scope.row.spuUnit }}
          </template>
        </el-table-column>
        <el-table-column label="商品状态" align="center">
          <template slot-scope="scope">
            {{
              scope.row.spuStatus == 2
                ? "售罄"
                : scope.row.spuStatus == 0
                ? "上架"
                : scope.row.spuStatus == 1
                ? "下架"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.skuCreateTime }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getClassificationListPage } from "@/api/common/index";
import {
  getStoreGoodsListByShopId,
  storeManageSave,
  getSkuMsgBySpuId,
} from "@/api/manage/storage";
export default {
  data() {
    return {
      dialogVisible: false,
      queryParams: {
        spuName: "",
        categoryId: "",
        pageNo: 1,
        pageSize: 10,
      },
      categoryprops: {
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.categoryLazyLoad,
      },
      total: 0,
      productList: [],
      form: {
        buyer: "",
        produceDate: "",
        remark: "",
        shelfLife: "",
        shelfLifeUnit: 0,
        storeDate: "",
        storeGoodsList: [],
        storeOdd: "",
        storeOddName: "",
        storeUnit: "",
        supplierName: "",
        supplierPhone: "",
        warningDay: "",
      },
      multipleSelection: [],
      rules: {
        shelfLife: [{ required: true, message: "保质期不能为空", trigger: "blur" }],
        storeOddName: [
          { required: true, message: "入库订单名称不能为空", trigger: "blur" },
        ],
        storeUnit: [{ required: true, message: "入库单位不能为空", trigger: "blur" }],
        storeDate: [{ required: true, message: "入库时间不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm() {
      console.log(this.form);
      if (this.form.storeGoodsList.length < 1) {
        this.$message.error("请选择入库商品！");
        return;
      }
      for (let index = 0; index < this.form.storeGoodsList.length; index++) {
        const e = this.form.storeGoodsList[index];
        if (!e.unitConversion) {
          this.$message.error("请输入入库商品的单位换算");
          return;
        } else if (!e.floatingWeight) {
          this.$message.error("请输入入库商品的浮动重量");
          return;
        } else if (!e.storeNum) {
          this.$message.error("请输入入库商品的入库数量");
          return;
        } else if (!e.storeUnitPrice) {
          this.$message.error("请输入入库商品的入库单价");
          return;
        }
      }
      this.$refs.Form.validate((valid) => {
        if (valid) {
          storeManageSave(this.form).then((res) => {
            if (res.code == 200) {
              this.$message.success("新增成功！");
              this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
              this.$router.replace({ path: "/storage/storage/index" });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    removetable(row, index) {
      console.log(index);
      this.form.storeGoodsList.splice(index, 1);
    },
    dialogOk() {
      if (this.multipleSelection.length < 1) {
        this.$message.error("请选择入库商品");
        return;
      }
      this.dialogVisible = false;
      console.log("this.", this.multipleSelection);
      let ids = [];

      for (let index = 0; index < this.multipleSelection.length; index++) {
        ids.push(this.multipleSelection[index].spuId);
      }

      getSkuMsgBySpuId(ids).then((res) => {
        if (res.code == 200) {
          res.data.forEach((e) => {
            let params = {
              unitConversion: "",
              floatingWeight: "",
              storeNum: "",
              storeUnitPrice: "",
            };
            let obj = { ...e, ...params };
            this.form.storeGoodsList.push(obj);
          });
          this.form.storeGoodsList = this.unique(this.form.storeGoodsList);
        }
      });
    },

    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.skuId) && res.set(arr.skuId, 1));
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectProduct() {
      this.getTableList();
    },
    getTableList() {
      this.loading = true;
      getStoreGoodsListByShopId(this.queryParams).then((res) => {
        this.dialogVisible = true;
        this.productList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      });
    },

    submitCancel() {
      this.$confirm("是否取消新增,所填写的信息将会消失?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
          this.$router.replace({ path: "/storage/storage/index" });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.getTableList();
    },
    cascaderChange(val) {
      if (val.length == 1) {
        this.queryParams.categoryId = val[0];
      } else if (val.length == 2) {
        this.queryParams.categoryId = val[1];
      } else if (val.length == 3) {
        this.queryParams.categoryId = val[2];
      }
    },
    categoryLazyLoad(node, resolve) {
      let level = node.level;
      console.log(node);
      if (!node.data) {
        getClassificationListPage({ parentId: 0 }).then((res) => {
          //接口
          const nodes = Array.from(res.data).map((item, index) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 2,
          }));
          console.log("111", node);
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else if (level == 1) {
        getClassificationListPage({ parentId: node.data.value }).then((res) => {
          const nodes = Array.from(res.data).map((item) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 2,
            // level: 2,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else if (level == 2) {
        getClassificationListPage({ parentId: node.data.value }).then((res) => {
          const nodes = Array.from(res.data).map((item) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 1,
            level: 1,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else {
        resolve({});
      }
    },
  },
};
</script>

<style></style>
