<template>
	<div>
		<SelectGoods ref="selectGoods" @callback="selectGoos" />
		<AddRecommend :shopId="shopId" ref="addRecommend" @getList="getList"/>
		<Preferential :shopId="shopId" ref="preferential" />

		<el-row :gutter="10" class="mb8">
			<el-col :span="18">
				<el-button :type="item.id == btnId ? 'primary' : ''" v-for="item  in options" @click="setData(item)"
					:key="item.id">{{ item.name }}
				</el-button>
			</el-col>
			<el-col :span="6">
				<el-button type="primary" @click="openSelectGoos" plain icon="el-icon-plus" size="small">添加商品
				</el-button>
				<el-button type="danger" @click="soldOutGoos"  plain icon="el-icon-minus" size="small">下架商品</el-button>
			</el-col>
		</el-row>
		<el-table v-loading="loading" :data="list"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
			<el-table-column label="商品名称" align="center" prop="name" width="200">
        <template slot-scope="scope">
          <div style="display: flex;align-items: center">
            <div>
              <span>{{scope.row.name}}</span>
            </div>          
            <div style="margin-left: 8px;margin-right: 8px">
              <el-button v-show="scope.row.recommend=='1'" type="text"> 荐</el-button>
            </div>
            <div>
              <el-button style="color:red" v-show="scope.row.preferential=='1'" type="text">惠</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="缩略图" align="center" prop="" width="150">
        <template slot-scope="scope">              
           <div class="image-tmp">
            <el-image style="width: 100px; height: 100px"  :src="getPicsList(scope.row.pics)" :preview-src-list="getPicsBigList(scope.row.pics)">
              <div slot="error" class="image-slot"></div>            
            </el-image>
          </div>    
        </template>
      </el-table-column>
			<el-table-column label="折扣价" align="center" prop="discount" />
			<el-table-column label="总销量" align="center" prop="salesVolume" />
      <el-table-column label="上架时间" align="center" prop="shelfAt" width="150" /> 
      <el-table-column label="规格"  align="center" prop="" width="150">
        <template slot-scope="scope">
          <div v-for="(item,index) in getSpecList(scope.row.spec)" :key="index" >
            <el-tooltip effect="dark" placement="right-start" >       
              <div slot="content">
                <div v-for="ru in item.specRules" :key="ru.id" style="display: flex;align-items: center;">                  
                  <div style="margin-right: 20px;">{{ru.name}}</div>
                  <div>{{ru.amount}}</div>                  
                </div>
              </div>
              <div>
                <el-button style="height:30px">{{item.name}}</el-button>                
              </div>
            </el-tooltip>
          </div>
          <div style="text-align:center;">已售罄（{{scope.row.selloutCount}}/{{scope.row.skuCount}}）</div>
          <div><el-button size="mini" type="text" @click="clickView(scope.row)">查看</el-button></div>      
        </template>
      </el-table-column>
      <el-table-column label="排序">
        <template slot-scope="scope">
          <div style="display: flex;">
            <div>
              <el-button v-show="scope.$index!=0" size="mini" round icon="el-icon-arrow-up" @click="turnClick(scope.row,'1')"></el-button>
            </div>   
            <div>
              <el-button v-show="scope.$index+1!=total" size="mini" round icon="el-icon-arrow-down" @click="turnClick(scope.row,'2')"></el-button>
            </div> 
          </div>             
        </template>
      </el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" @click="addRecommend(scope.row)" type="text" v-show="scope.row.recommend=='0'">
						推荐
					</el-button>
					<el-button @click="preferential(scope.row)" size="mini" type="text" v-show="scope.row.preferential=='0'">
						特惠
					</el-button>
				</template>
			</el-table-column>
		</el-table>
    <el-pagination
        style="text-align:right;padding-top: 20px;"
        @size-change="configSizeChange"
        @current-change="configCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next,jumper"
        :total="totalNum">
    </el-pagination>
    <el-dialog title="查看规格" :visible.sync="viewSpecDialog" width="800px" append-to-body>
      <div style="margin-bottom: 10px;" >
        <el-row>
          <div>
            <el-col :span='2'>商品名称</el-col>
            <el-col :span='4'>{{goodsName}}</el-col>
          </div>
          <div style="display: flex;justify-content:space-between">
            <div></div>
            <div></div>
            <div>
              <!-- <el-button size="small" type="primary">全选</el-button> -->
              <el-button size="small" type="success" @click="changeMoreState('1')">上架</el-button>
              <el-button size="small" type="danger" @click="changeMoreState('2')">下架</el-button>
            </div>
          </div>
        </el-row>
      </div>
      <el-table :data="specNameList" style="width: 100%" @selection-change="specNameStateChange" ref="multipleTable">
        <el-table-column          
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="商品规格">
          
            <template slot-scope="scope">
              <div style="white-space: pre-wrap;">
              {{scope.row.strName}}
              </div>
            </template>
          
        </el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <div @click="changeOneState(scope.row)"  ><el-switch v-model="scope.row.state"/> </div>
            <span v-if="scope.row.state == false">下架</span>
            <span v-if="scope.row.state == true">上架</span>
          </template>
        </el-table-column>
         
      </el-table>
      <div class="dialog-footer" style="text-align: center;margin-top: 10px;">       
        <el-button @click="cancel" type="primary">关闭</el-button>
		  </div>
    </el-dialog>
	</div>
</template>

<script>
import { getCategoryGoods, addGoods ,offGoods,turnList,getSpecSku,updateSpecState} from "@/api/system/shop";
import SelectGoods from '@/components/SelectGoods';
import AddRecommend from './addRecommend.vue'
import Preferential from './preferential.vue';
import { TagsView } from '../../../../layout/components';

export default {
	props: ['shopId'],
	watch: {
		zshopId() {
			this.options = []
			this.btnId = '';
			this.list = []
			this.getList()
		}
	},
	components: { SelectGoods, AddRecommend, Preferential },
	data() {
		return {
      pageNum:1,
      pageSize:10,
      totalNum:0,
			loading: false,
			list: [],
			options: [],
			btnId: '',
      outIds: '',
      total: null,
      goodsList:[],
      viewSpecDialog:false,      
      goodsId:null,
      goodsName:"",
      specNameList:[],
      ids:"",
		}    
	},
	mounted() {
		//this.getList()
	},
	methods: {
    //新增接口1
    cancel(){
      this.viewSpecDialog=false;
    },
    specNameStateChange(val) {
      this.ids="";
      for(let i=0;i<val.length;i++){
        this.ids +=val[i].id+","
      }
      this.ids=this.ids.substring(0,this.ids.length-1)      
    },
    //新增接口2
    changeOneState(row){        
      let tag=2;      
      if(row.state){
        tag=1;
      }
      this.updateSpecState(row.id,tag);      
    },
    //新增接口3
    changeMoreState(tag){
      this.updateSpecState(this.ids,tag);      
    },
    updateSpecState(ids,tag){
      updateSpecState(ids,tag,this.shopId,this.goodsId).then((response) => {
        if(response.code=="200"){          
          let idsList=ids.split(",");
          for(let i=0;i<idsList.length;i++){
            let selectedId=idsList[i]
            for(let j=0;j<this.specNameList.length;j++){
              if(this.specNameList[j].id==selectedId){
                this.specNameList[j].state=(tag == 1?true:false)
              }
            }
          }
          if(tag==1){
            this.$modal.msgSuccess("上架成功!");
          }else{
            this.$modal.msgSuccess("下架成功!");
          } 
          this.$refs.multipleTable.clearSelection();
        }else{
          if(tag==1){
            this.$message.error("上架失败!");
          }else{
            this.$message.error("下架失败!");
          }
        }
      })
    },
    //新增接口3
    clickView(row){
      this.specNameList=[];
      this.viewSpecDialog=true;  
      this.goodsId=row.id; 
      this.goodsName=row.name;
      let specList=JSON.parse(row.spec);      
      getSpecSku(this.shopId,row.id).then((response) => {
        if(response.code=="200"){
          let list=response.data;
          for(let i=0;i<list.length;i++){
            let ruleList=JSON.parse(list[i].ruleList);
            let strName = '';
            for(let j=0;j<ruleList.length;j++){             
              ruleList[j].specName=this.findSpecNameById(specList,ruleList[j].specId); 
              strName +=ruleList[j].specName+":"+ruleList[j].name+"\n"; 
            }
            list[i].state=(list[i].state == 1?true:false)
            this.specNameList.push({"id":list[i].id,"strName":strName,"state":list[i].state})                               
          }      
        }        
      });      
    },
    //根据id找name
    findSpecNameById(specList,p_specId){      
      let specName = '';
      for(let i=0;i<specList.length;i++){
          let specId = specList[i].id;
          if(specId == p_specId){
              specName = specList[i].name;
              break;
          }
      }
      return specName;
    },
    turnClick(row,tag){
      turnList({"shopId":this.shopId,"goodsId": row.id,"pointer":tag}).then((response) => {
        if(response.code=="200"){
          this.getList();
        }
      });      
    },
    getPicsList(str){   
      let picObj = JSON.parse(str);  
      return picObj.thumbnail
    },
    getPicsBigList(str){
      let list=[];
      let picObj = JSON.parse(str);  
      list.push(picObj.thumbnail)
      return list;
    },
		addRecommend(data) {
			this.$refs.addRecommend.openModal(data)
		},
		preferential(data) {
			this.$refs.preferential.openModal(data)
		},
		setData(data) {
			this.list = data.goodsList;
      this.goodsList=data.goodsList;
			this.btnId = data.id;
      this.total=this.list.length;      
      this.totalNum=this.list.length;
		},
		getList() {
			if (!this.shopId) return;
      this.list=[];
			getCategoryGoods(this.shopId).then(({ data }) => {        
				if (data && data.length > 0) {
					this.options = data;        
          if(this.btnId==''){
            this.list = data[0].goodsList;
            this.btnId = data[0].id;
          }else{
            for(let i=0;i<data.length;i++){
              if(this.btnId==data[i].id){
                this.list = data[i].goodsList;
              }
            }
          }
          this.goodsList=this.list;  
          this.total=this.list.length;
          this.totalNum=this.list.length;
				}else{
          this.options=[];
        }
			})
		},
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.outIds = selection.map((item) => item.id);
    },
    soldOutGoos(){      
      if(this.outIds.length==0){
        this.$message.error('请选择所需下架的商品!');
        return;
      }    
      this.$confirm('是否确认下架所选商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          offGoods({"shopId":this.shopId,"goodsIds":this.outIds}).then(res => {
            if(res.code=="200"){
              this.getList();
              this.$message({
                type: 'success',
                message: '所选商品下架成功!'
              });
            }
			    })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下架所选商品!'
          });          
      });
    },
		openSelectGoos() {
			this.$refs.selectGoods.openModal(this.shopId)
		},
		selectGoos(ids) {
      this.$confirm('是否确认添加所选商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addGoods({"shopId":this.shopId,"goodsIds":ids.join(',')}).then(res => {
            if(res.code=="200"){
              this.$refs.selectGoods.open = false;
              this.getList();
              this.$message({
                type: 'success',
                message: '所选商品添加成功!'
              });
            }
			    })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消所选的商品!'
          });          
      });
		},
    getPageList(){            
      let startRow = (this.pageNum - 1) * this.pageSize+1-1;//开始显示的行  
      let endRow = this.pageNum * this.pageSize;//结束显示的行
      endRow = (endRow > this.totalNum)? this.totalNum : endRow;
      this.list=this.goodsList.slice(startRow,endRow);  
    },
    configSizeChange(size){        
      this.pageNum=1;
      this.pageSize=size;
      this.getPageList();
    },
    configCurrentChange(current){
      this.pageNum=current;
      this.pageSize=this.pageSize;
      this.getPageList();
    },
    getSpecList(value){
      return JSON.parse(value);      
    }
	}
}
</script>

<style>
.flex {
	height: 50px;
	align-items: center;
	text-align: right;
}

</style>
