<template>
  <el-dialog title="调整库存" :visible.sync="dialogVisible" width="750px" @close="cancelSubmit()">
    <div v-loading="loading">
      <div v-if="goodsSkuList.length > 1">
        <el-table :data="goodsSkuList" :span-method="objectSpanMethod" border>
          <el-table-column width="140px" v-for="(i, k) in skuCols" :label="i" :key="k" :class-name="k == skuCols.length - 1 ? 'pad-l-20' : 'right-border'">
            <template slot-scope="scope">{{ scope.row.cols[k] }}</template>
          </el-table-column>
          <el-table-column label="当前可占用" width="130px">
            <template slot-scope="scope">
              {{ skuSellObj[scope.row.mapId].remainedStock || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template v-slot:header>
              <span>库存</span>
              <el-popover placement="top" trigger="click" ref="popover">
                <div>
                  <el-select v-model="banthStockType" style="width:100px">
                    <el-option label="增加" :value="1"></el-option>
                    <el-option label="减少" :value="0"></el-option>
                  </el-select>
                  <dm-input-number v-model="banthStock" width="140" style="margin-left:-2px;" controls-position="right" precision="0" :min="0" :max="999999"></dm-input-number>
                </div>
                <div class="popver-button" style="margin-top:18px;text-align:right">
                  <el-button type="dafault" size="small" @click="$refs.popover.showPopper = false">取消</el-button>
                  <el-button type="primary" size="small" class="ml10 ml10" @click="handleStock">确认</el-button>
                </div>
                <el-tooltip slot="reference" content="批量编辑">
                  <i class="el-icon-edit-outline"></i>
                </el-tooltip>
              </el-popover>
            </template>
            <template slot-scope="scope">
              <el-select v-model="skuSellObj[scope.row.mapId].stockType" style="width:100px" @change="changeType">
                <el-option label="增加" :value="1"></el-option>
                <el-option label="减少" :value="0"></el-option>
              </el-select>
              <dm-input-number v-model="skuSellObj[scope.row.mapId].stageStock" width="140" style="margin-left:-2px;" controls-position="right" @blur="changeSingleStock(skuSellObj[scope.row.mapId].giftSkuId, skuSellObj[scope.row.mapId].stageStock, skuSellObj[scope.row.mapId].stockType)" precision="0" :min="0" :max="999999"></dm-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form class="mt20" v-else>
        <el-form-item label="可占库存" required>
          <template>
            <el-select v-model="stockType" style="width:100px;">
              <el-option label="增加" :value="1"></el-option>
              <el-option label="减少" :value="0"></el-option>
            </el-select>
            <dm-input-number v-model="stock" width="140" style="margin-left:-1px;" controls-position="right" @blur="changeSingleStock(giftSkuId, stock, stockType)" precision="0" :min="0" :max="999999"></dm-input-number>
          </template>
        </el-form-item>
      </el-form>
      <el-form class="mt20">
        <el-form-item label="调整备注" required>
          <template>
            <el-input style="width:260px" type="textarea" :rows="3" placeholder="请填入调整备注" v-model="textarea" :maxlength="240" show-word-limit></el-input>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelSubmit()">取消</el-button>
      <el-button type="primary" @click="submitProNanme()">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import request from '../service/request.js';
import { deepClone } from '../../../utils/index';
import api from '@/api/gift.js';
const { realStockUpdate, giftGet } = api;
export default {
  props: {
    stockData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      // tableData: [],
      spanArr: [], // 用于存放每一行记录的合并数
      // costChangeObj: [], // 用于存放批量修改后的数据
      banthStock: undefined,
      stockType: 1,
      banthStockType: 1,
      updateList: [],
      textarea: '',
      giftId: '',
      skuSellObj: {},
      stockObj: {},
      skuCols: [],
      goodsSkuList: [],
      stock: 0,
      giftSkuId: ''
    };
  },
  created() {
    this.dialogVisible = true;
    this.giftId = this.stockData.id;
    this.getData();
  },
  methods: {
    getData(){
      if(this.loading) return;
      let params = {
        id: this.giftId
      };
      giftGet(params).then(res =>{
        if(res.code === '0000'){
          this.giftSpecInfo = res.result.giftSpecInfo;
          let skuList = res.result.skuList || []; // 礼品规格值信息

          let mapData = [];
          let skuSellObj = {};
          if (skuList.length > 0) {
            for (let i = 0; i < skuList.length; i++) {
              mapData.push({
                mapId: '',
                id: [],
                giftSkuId: skuList[i].giftSkuId,
                giftSkuCostPrice: skuList[i].giftSkuCostPrice, // 成本价
                giftSkuCode: skuList[i].giftSkuCode, // sku编码
                skuBarCode: skuList[i].skuBarCode, // 礼品条形码
                stock: skuList[i].stock, // 库存
                remainedStock: skuList[i].remainedStock, // 库存
                giftSkuStrand: skuList[i].giftSkuStrand, // 礼品sku规格信息
                giftId: skuList[i].giftId
              });
              if(skuList[i].giftSkuStrand){
                for (let j = 0; j < JSON.parse(skuList[i].giftSkuStrand).length; j++) {
                  mapData[i].id.push(JSON.parse(skuList[i].giftSkuStrand)[j].specStandardValueId);
                }
                mapData[i].mapId = mapData[i].id.join('_');
              }
            }
            for (let item of mapData) {
              skuSellObj[item.mapId] = {
                skuBarCode: item.skuBarCode,
                giftSkuCode: item.giftSkuCode,
                giftSkuCostPrice: item.giftSkuCostPrice,
                stock: item.stock,
                giftSkuCostPriceStatus: true,
                stockStatus: true,
                giftSkuId: item.giftSkuId,
                remainedStock: item.remainedStock,
              };
            }
            console.log(skuSellObj);
            this.skuSellObj = deepClone(skuSellObj);
            console.log(this.skuSellObj);
          }
          this.goodsStandardInfo = this.giftSpecInfo ? JSON.parse(this.giftSpecInfo) : []; // 礼品规格信息
          if (this.goodsStandardInfo.length > 0) {
            this.isStdImg = this.goodsStandardInfo[0].standardimg === 2 ? true : false;
          } else {
            this.isStdImg = false;
          }
          if (this.goodsStandardInfo.length > 0) {
            this.getSkuList();
          }else{
            this.giftSkuId = skuList[0].giftSkuId;
          }
        }
      });
      console.log('获取成本数据');
    },
    changeType(value){
      console.log(value);
    },
    submitProNanme() {
      if(this.loading) return;
      let totalStock = 0;
      this.updateList.forEach((item) =>{
        totalStock = Number(totalStock) + Number(item.stock);
      });
      if(!totalStock){
        this.$message.error('库存更改不可为0');
      }else{
        let params = {
          giftId: this.stockData.id,
          updateList: this.updateList,
          remark: this.textarea
        };
        this.loading = true;
        realStockUpdate(params).then(res =>{
          if(res.code === '0000'){
            this.dialogVisible = false;
            setInterval(() => {
              this.$emit('closeUpdateStock');
            }, 10);
            this.$message.success('修改成功');
          }else{
            this.$message.error(res.message);
          }
        }).finally(() => this.loading = false);
      }
    },
    // 取消修改
    cancelSubmit() {
      this.dialogVisible = false;
      setInterval(() => {
        this.$emit('closeUpdateStock');
      }, 10);
    },
    // 获取sku数据
    getSkuList() {
      let goodsStandardInfoCopy = deepClone(this.goodsStandardInfo);
      let arr = [];
      this.skuCols = [];
      /** ****组合sku的数据*****/
      for (let item of goodsStandardInfoCopy) {
        for (let i of item.valueList) {
          i.specStandardName = item.specName;
          i.specStandardId = item.specId;
        }
        this.skuCols.push(item.specName);
        arr.push(item.valueList);
      }
      let arrCopy = this.combine(deepClone(arr));
      let goodsSkuList = [];
      for (let i = 0; i < arrCopy.length; i++) {
        goodsSkuList.push({
          data: arrCopy[i],
          cols: [],
          id: [],
          mapId: ''
        });
        for (let j = 0; j < arrCopy[i].length; j++) {
          goodsSkuList[i].cols.push(arrCopy[i][j].specStandardValueName);
          goodsSkuList[i].id.push(arrCopy[i][j].specStandardValueId);
        }
        goodsSkuList[i].mapId = goodsSkuList[i].id.join('_');
      }
      this.goodsSkuList = deepClone(goodsSkuList);
      /** ****获取合并单元格的数组值start *****/
      let numArr = [];
      this.stValCount = [];
      for (let k = 0; k < goodsStandardInfoCopy.length; k++) {
        if (goodsStandardInfoCopy[k].valueList.length > 0) {
          numArr[k] = goodsStandardInfoCopy[k].valueList.length;
        }
      }
      let num = 1;
      for (let m = 0; m < numArr.length; m++) {
        num = num * numArr[m];
        this.stValCount[m] = num;
      }
      /** ****获取合并单元格的数组值 this.stValCount   end *****/

      // 组合sku的销售值信息 价格，库存，sku编码 ，商品条形码
      let goodsSkuListCopy = deepClone(goodsSkuList);
      let skuSellObjCopy = deepClone(this.skuSellObj);
      // this.skuSellObj = {};
      for (let item of goodsSkuListCopy) {
        console.log(item);
        console.log(item.mapId);
        console.log(skuSellObjCopy[item.mapId]);
        if (skuSellObjCopy[item.mapId]) {
          this.skuSellObj[item.mapId] = {
            giftSkuCostPrice: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].giftSkuCostPrice : '',
            stock: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].stock : '',
            giftSkuCode: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].giftSkuCode : '',
            skuBarCode: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].skuBarCode : '',
            giftSkuId: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].giftSkuId : '',
            remainedStock: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].remainedStock : '',
            stockStatus: true,
            giftSkuCostPriceStatus: true,
            stockType: 1,
            stageStock: ''
          };
          this.stockObj[item.mapId] = Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].stock : '';
        } else {
          this.skuSellObj[item.mapId] = {
            giftSkuCostPrice: '',
            stock: undefined,
            giftSkuCode: '',
            skuBarCode: '',
            stockStatus: true,
            giftSkuCostPriceStatus: true,
            giftSkuId: '',
            remainedStock: '',
            stockType: 1,
            stageStock: ''
          };
        }
      }
      this.skuSellObj = deepClone(this.skuSellObj);
      // this.giftSkuId = this.skuSellObj[this.goodsSkuList[0].mapId].giftSkuId;
      console.log(this.skuSellObj);
      this.refash = !this.refash;
    },
    combine(arr) {
      arr.reverse();
      let r = [];

      (function f(t, a, n) {
        if (n == 0) return r.push(t);
        for (let i = 0; i < a[n - 1].length; i++) {
          f(t.concat(a[n - 1][i]), a, n - 1);
        }
      })([], arr, arr.length);
      // var t = r;
      return r; // r是排列组合后的数据与
    },
    objectSpanMethod({ rowIndex, columnIndex }) {
      let len = this.stValCount.length;
      if (columnIndex < len) {
        let count1 = this.stValCount[columnIndex];
        let count2 = this.stValCount[len - 1];
        if (!(count1 && count2)) {
          return { rowspan: 0, colspan: 0 };
        }
        let rowspan = count2 / count1;
        if (rowIndex % rowspan === 0) {
          return { rowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
    },
    // 批量修改成本
    handleStock(){
      this.updateList = [];
      this.stock = this.banthStock;
      for(let item in this.skuSellObj){
        this.skuSellObj[item].stock = this.banthStock;
        this.skuSellObj[item].stageStock = this.banthStock;
        this.skuSellObj[item].stockType = this.banthStockType;
        this.updateList.push({ giftSkuId: this.skuSellObj[item].giftSkuId, stock: this.skuSellObj[item].stock, stockType: this.banthStockType });
      }
      console.log(this.updateList);
      this.banthStock = undefined;
    },
    changeSingleStock(id, stock, stockType){
      if(!stock){
        this.$message.error('请完善库存');
      }
      if(this.updateList.length > 0){
        let iii;
        let result = this.updateList.some((item, index) =>{
          if(item.giftSkuId == id){
            iii = index;
            return true;
          }
        });
        if(result){ // 如果存在
          this.updateList[iii].stock = stock;
          this.updateList[iii].stockType = stockType;
        }else{
          this.updateList.push({ giftSkuId: id, stock: stock, stockType: stockType });
        }
      }else{
        this.updateList.push({ giftSkuId: id, stock: stock, stockType: stockType });
      }
      console.log(this.updateList);
    }
  }
};
</script>
<style scoped></style>
<style>
.right-border {
  border-right: 1px solid #ebeef5;
}
</style>