<template>
  <ContainerTit>
    <!-- 底部按钮 slot="footerButton" -->
    <div slot="headr">
      <el-button
        type="primary"
        :loading="submitLoading"
        @click="onSubmit('formData')"
      >
        提交
      </el-button>
    </div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <!-- 基本信息 slot="basicInfo"-->
      <el-form ref="formData" :model="formData" label-width="100px" inline>
        <el-form-item label="操作人：" prop="userId">
          {{ formData.operatorName }}
        </el-form-item>
        <el-form-item label="仓库：" prop="warehouseId">
          <el-select
            v-model="formData.warehouseId"
            disabled
            placeholder="请选择"
            style="width: 150px"
          >
            <el-option
              v-for="item in warehouseData"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="formData.remark"
            :rows="3"
            style="width: 369px"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>商品信息</span>
        <div class="table-info clearfix float_right">
          <p class="float_left" style="margin-right: 20px">
            共 {{ selectGoodsData.length }} 件商品，合计金额
            {{ $_common.formattedNumber(priceAllNum) }}。
          </p>
        </div>
      </div>

      <!-- 表格 -->
      <el-table :data="selectGoodsData">
        <el-table-column
          type="index"
          align="center"
          label="#"
          width="60px"
        ></el-table-column>
        <el-table-column prop="materielName" align="center" label="商品名称">
          <template slot-scope="scope">
            <ConditionSelGoods
              v-model="scope.row.materielName"
              :type="true"
              :is-reveal-sku="4"
              :spec-check="spec_check"
              @goodsVisibleChange="goodsVisibleChange($event, scope.$index)"
              @specSelConfirm="specSelConfirm"
              @selGoods="selGoods"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="unitName"
          align="center"
          label="单位"
        ></el-table-column>
        <el-table-column
          prop="skuName"
          align="center"
          label="属性"
        ></el-table-column>
        <el-table-column align="center" label="采购量">
          <template slot="header" slot-scope="scope">
            <el-popover
              v-model="multip_num_show"
              placement="bottom"
              width="260"
            >
              <p style="font-size: 12px; font-weight: bold">批量设置采购量</p>
              <el-input-number
                v-model="multip_num"
                :min="0"
                style="width: 100%; margin: 10px 0"
                size="small"
                placeholder="批量设置采购量"
              ></el-input-number>
              <div style="text-align: right">
                <el-button
                  size="mini"
                  type="text"
                  @click="multip_num_show = false"
                >
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="setMultipNum(scope.$index)"
                >
                  确定
                </el-button>
              </div>
              <div slot="reference">
                <span style="margin-right: 10px">采购量</span>
                <i class="el-icon-edit"></i>
              </div>
            </el-popover>
          </template>
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.num"
              size="small"
              :min="1"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采购价(元)">
          <template slot="header" slot-scope="scope">
            <el-popover
              v-model="multip_pride_show"
              placement="bottom"
              width="260"
            >
              <p style="font-size: 12px; font-weight: bold">批量设置采购价</p>
              <el-input-number
                v-model="multip_pride"
                :min="0"
                style="width: 100%; margin: 10px 0"
                size="small"
                placeholder="批量设置采购价"
              ></el-input-number>
              <div style="text-align: right">
                <el-button
                  size="mini"
                  type="text"
                  @click="multip_pride_show = false"
                >
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="setMultipNum(scope.$index)"
                >
                  确定
                </el-button>
              </div>
              <div slot="reference">
                <span style="margin-right: 10px">采购价(元)</span>
                <i class="el-icon-edit"></i>
              </div>
            </el-popover>
          </template>
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.costPrice"
              :controls="false"
              size="small"
              :precision="2"
              :step="1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计(元)">
          <template slot-scope="scope">
            <p>{{ scope.row.num * scope.row.costPrice || 0 }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="date" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              :disabled="selectGoodsData.length === 1"
              @click="clearGoodsItem(scope.$index)"
            >
              删除
            </el-button>
            <el-button type="text" size="mini" @click="addListGoods">
              新增
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </ContainerTit>
</template>

<script>
  import { getAllWarehouse, addWarehouseBeginning } from "@/api/Stock";

  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  export default {
    name: "NewStart",
    components: {
      ConditionSelGoods,
    },
    data() {
      return {
        multip_num: "",
        multip_num_show: false,
        multip_pride: "",
        multip_pride_show: false,
        show_goods: false,
        submitLoading: false,
        formData: {
          warehouseId: 0,
          operatorName: "",
          remark: "",
          paramsMaterielData: [
            {
              materielId: "",
              materielName: "",
              materielCode: "",
              skuId: "",
              num: "",
              costPrice: "",
            },
          ],
        },
        spec_check: [],
        goods_index: 0,
        selectGoodsData: [
          {
            materielId: "",
            materielName: "",
            materielCode: "",
            skuId: "",
            skuName: "",
            unitName: "",
            num: 1,
            costPrice: 0,
          },
        ], // 页面已选择的商品信息
        warehouseId: "", // 流水单的id
        warehouseData: [], // 所有仓库数据
      };
    },
    computed: {
      priceAllNum() {
        if (this.selectGoodsData.length > 1) {
          let a = 0;
          for (let i = 0; i < this.selectGoodsData.length; i++) {
            const item = this.selectGoodsData[i];
            a += item.num * (item.costPrice || 0);
          }
          return a;
        } else if (this.selectGoodsData.length === 1) {
          return (
            this.selectGoodsData[0].num * this.selectGoodsData[0].costPrice
          );
        } else {
          return 0;
        }
      },
    },
    created() {
      this.getAllWarehouse();
      this.formData.warehouseId = parseInt(this.$route.query.id);
      this.formData.operatorName = this.userName;
    },
    activated() {
      if (this.$_isInit()) return;
      this.getAllWarehouse();
      this.formData.warehouseId = parseInt(this.$route.query.id);
      this.formData.operatorName = this.userName;
    },
    methods: {
      // 多选商品确定
      selGoods(list) {
        let target = this.$_common.deepClone(this.selectGoodsData);
        const goodsD = list.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            materielId: item.id,
            materielName: item.title,
            materielCode: item.code,
            skuId: item.skuId,
            skuName: specGropName,
            unitName: item.unitName,
            num: 1,
            costPrice: 1,
          };
        });
        // 判断是否有内容
        const isBase = target.some((item) => {
          return item.materielId;
        });
        if (!isBase) {
          target = goodsD;
        } else {
          target = this.$_common.unique(target.concat(goodsD), [
            "materielId",
            "skuId",
          ]);
        }
        this.selectGoodsData = target;
      },
      specSelConfirm(params) {
        let target = this.$_common.deepClone(this.selectGoodsData);
        const goodsD = params.goodsD.map((item) => {
          return {
            materielId: params.now_goods_data.materielId,
            materielName: params.now_goods_data.title,
            materielCode: params.now_goods_data.code,
            skuId: item.skuId,
            skuName: item.spec.specGropName,
            unitName: item.spec.unitName,
            num: 1,
            costPrice: 1,
          };
        });

        if (!target[this.goods_index].skuId) {
          target.splice(this.goods_index, 1);
        }
        goodsD.forEach((item) => {
          const targetD = target.find((itemG) => itemG.skuId === item.skuId);
          if (!targetD) {
            target.unshift(item);
          }
        });
        this.selectGoodsData = target;
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      addListGoods() {
        this.selectGoodsData.push({
          materielId: "",
          materielName: "",
          materielCode: "",
          skuId: "",
          skuName: "",
          unitName: "",
          num: 1,
          costPrice: 0,
        });
      },
      //  选择仓库
      async getAllWarehouse() {
        const { data } = await getAllWarehouse({
          page: 1,
          pageSize: 999,
        });

        this.warehouseData = data;
      },
      // 保存提交
      onSubmit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const params = {
              ...this.formData,
              paramsMaterielData: this.$_common
                .deepClone(this.selectGoodsData)
                .map((item) => {
                  delete item.unitName;
                  delete item.skuName;
                  return item;
                }),
            };
            console.log(this.selectGoodsData);
            let flag = false;
            if (!this.selectGoodsData[0].materielId) {
              this.$message.warning("第一项商品不能为空");
              return;
            }
            this.selectGoodsData.forEach((item) => {
              if (!item.materielId) {
                flag = true;
              }
            });
            if (flag) {
              this.$message.warning("所有商品名称不能为空");
              return;
            }
            if (!params.paramsMaterielData.length) {
              return;
            }
            this.submitLoading = true;
            try {
              const data = await addWarehouseBeginning(params);
              this.submitLoading = false;
              this.$message.success("操作成功");
              this.$closeCurrentGoEdit("/stock/WarehouseManagement/Management");
            } catch {
              this.submitLoading = false;
            }
          }
        });
      },
      // 删除已选择的商品
      clearGoodsItem(index) {
        this.selectGoodsData.splice(index, 1);
      },
      // 批量设置
      setMultipNum(index) {
        if (index === 4) {
          this.multip_num_show = false;
        } else {
          this.multip_pride_show = false;
        }

        this.selectGoodsData.forEach((item) => {
          if (index === 4) {
            item.num = this.multip_num;
          } else {
            item.costPrice = this.multip_pride;
          }
        });
      },
    },
  };
</script>

<style scoped>
  .page {
    text-align: center;
    padding: 10px;
  }
  .dialog-footer {
    text-align: center;
  }
  /* 表格内商品信息 */
  .table-list-box {
    display: flex;
    font-size: 12px;
  }
  .table-list-box .goods-info-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .table-list-box .goods-title {
    color: #666666;
    text-align: left;
  }
  .table-list-box .goods-no {
    color: rgb(153, 153, 153);
    text-align: left;
  }
  .table-info {
    color: #333;
    font-size: 12px;
    line-height: 2;
    font-weight: 700;
  }
</style>
