<template>
  <el-dialog title="调整库存" :visible.sync="dialogVisible" width="750px" @close="cancelSubmit()">
    <div v-loading="loading">
      <div v-if="goodsSkuList.length > 0">
        <div class="fr mb20">
          <el-select v-model="stockType" style="width:100px;margin-right:10px">
            <el-option label="增加" :value="0"></el-option>
            <el-option label="减少" :value="1"></el-option>
          </el-select>
          <el-input placeholder="输入库存" style="width:85px;margin-right:10px" v-model="banthStock" precision="0" :min="0" :max="999999"></el-input>
          <el-button type="primary" @click="handleStock">批量填充</el-button>
        </div>
        <!-- <el-table :data="tableData" :span-method="objectSpanMethod" border>
          <el-table-column label="颜色" prop="color" width="90px">
            <template slot-scope="scope">{{ scope.row.color }}</template>
          </el-table-column>
          <el-table-column label="尺码" prop="size" width="90px">
            <template slot-scope="scope">{{ scope.row.size }}</template>
          </el-table-column>
          <el-table-column label="当前可占用" prop="remainedStock" width="100px">
            <template slot-scope="scope">{{ scope.row.remainedStock }}</template>
          </el-table-column>
          <el-table-column label="增加/减少" width="150px">
            <template slot-scope="scope">
              <el-select v-model="scope.row.stockType" style="width:100px">
                <el-option label="增加" :value="0"></el-option>
                <el-option label="减少" :value="1"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template slot-scope="scope">
              <dm-input-amount width="200px" @change="changeSingleStock(scope.row.giftSkuId, scope.row.stock, scope.row.stockType)" v-model.trim="scope.row.stock" precision="0" :min="0" :max="999999"></dm-input-amount>
            </template>
          </el-table-column>
        </el-table> -->
        <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 slot-scope="scope">
              <dm-input-amount width="200px" @change="changeSingleCost(skuSellObj[scope.row.mapId].giftSkuId, skuSellObj[scope.row.mapId].giftSkuCostPrice)" v-model.trim="skuSellObj[scope.row.mapId].giftSkuCostPrice" precision="2" :min="0" :max="999999.99"></dm-input-amount>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-select v-model="stockType" style="width:100px;display:inline-block;margin-right:10px">
          <el-option label="增加" :value="0"></el-option>
          <el-option label="减少" :value="1"></el-option>
        </el-select>
        <el-input-number v-model="stock" precision="0" :min="0" :max="999999"  style="width:300px"></el-input-number>
      </div>
      <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: [],
      tableData: [
        {
          color: '红色',
          size: 'L',
          remainedStock: '10',
          giftSkuId: '1111',
          stock: '10',
          stockType: 1
        },
        {
          color: '红色',
          size: 'XL',
          remainedStock: '20',
          giftSkuId: '2222',
          stock: '20',
          stockType: 1
        },
        {
          color: '红色',
          size: 'M',
          remainedStock: '30',
          giftSkuId: '3333',
          stock: '12',
          stockType: 1
        },
        {
          color: '黑色',
          size: 'L',
          remainedStock: '10',
          giftSkuId: '4444',
          stock: '13',
          stockType: 1
        },
        {
          color: '黑色',
          size: 'M',
          remainedStock: '20',
          giftSkuId: '55555',
          stock: '14',
          stockType: 1
        }
      ],
      spanArr: [], // 用于存放每一行记录的合并数
      // costChangeObj: [], // 用于存放批量修改后的数据
      banthStock: '',
      stockType: 0,
      updateList: [],
      textarea: '',
      giftId: '',
      skuSellObj: {},
      stockObj: {},
      skuCols: [],
      goodsSkuList: [],
    };
  },
  created() {
    this.dialogVisible = true;
    this.giftId = this.stockData.id;
    this.getData();
    this.getSpanArr(this.tableData);
  },
  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
              });
              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 = JSON.parse(this.giftSpecInfo); // 礼品规格信息
          console.log(this.goodsStandardInfo);
          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();
          }
        }
      });
      console.log('获取成本数据');
    },
    submitProNanme() {
      if(this.loading) return;
      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() {
      console.log(this.goodsStandardInfo);
      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.specStandardName);
        arr.push(item.valueList);
        console.log(arr);
      }
      console.log(this.skuCols);
      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);
      console.log(this.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);
      console.log(this.skuSellObj);
      let skuSellObjCopy = deepClone(this.skuSellObj);
      console.log(skuSellObjCopy);
      // this.skuSellObj = {};
      console.log(goodsSkuListCopy);
      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,
            // skuId: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].skuId : ''
          };
          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: '',
            // skuId: ''
          };
        }
      }
      this.skuSellObj = deepClone(this.skuSellObj);
      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是排列组合后的数据与
    },
    // 合并单元格，行合并
    getSpanArr(data) {
      // data就是我们从后台拿到的数据
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].color === data[i - 1].color) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
        // console.log(this.spanArr);
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // if (columnIndex === 0 || columnIndex === 1) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        // console.log(`rowspan:${_row} colspan:${_col}`);
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 批量修改成本
    handleStock(){
      // for (let item in this.costChangeObj) {
      //   this.costChangeObj[item].costPrice = this.banthCost;
      //   // this.costChangeObj[item].stockType = this.stockType;
      // }
      this.updateList = [];
      // if(this.stockType === 1){
      //   this.tableData.forEach(item => {
      //     // item.stock = Number(item.stock) + Number(this.banthStock);
      //     item.stock = this.banthStock;
      //     item.stockType = this.stockType;
      //     this.updateList.push({ giftSkuId: item.giftSkuId, stock: item.stock, stockType: item.stockType });
      //   });
      // }else{
      //   this.tableData.forEach(item => {
      //     // item.stock = Number(item.stock) - Number(this.banthStock);
      //     item.stock = this.banthStock;
      //     item.stockType = this.stockType;
      //     this.updateList.push({ giftSkuId: item.giftSkuId, stock: item.stock, stockType: item.stockType });
      //   });
      // }
      this.tableData.forEach(item => {
        item.stock = this.banthStock;
        item.stockType = this.stockType;
        this.updateList.push({ giftSkuId: item.giftSkuId, stock: item.stock, stockType: item.stockType });
      });
      console.log(this.updateList);
    },
    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;
        }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>
