<template>
    <div v-loading="loading">
        <div class="white-box">
            <el-tabs v-model="goodsCategory" @tab-click="handleClick">
                <el-tab-pane v-for="(item, key) in goodsActive" :key="key" :label="item.label" :name="item.name">
                    <el-table v-if="numList.length > 0" :max-height="maxHeight" class="withdraw-table" :data="tableData" stripe style="width: 100%;" ref="multipleTable" @selection-change="handleSelectionChange">
                      <el-table-column
                          type="selection"
                          width="55">
                      </el-table-column>
                      <!-- <el-table-column label="创建时间">
                           <template slot-scope="scope">
                              {{tool.formatDate(scope.row.CREATED_AT)}}
                          </template>
                      </el-table-column> -->
                      <el-table-column label="Product Name" prop="GOODS_NAME"><!--商品名称-->

                      </el-table-column>

                      <el-table-column label="Product picture" ><!--图片-->
                        <template slot-scope="scope">
<!--                          <img :src="scope.row.COVER" alt="" style="width:100px" >-->
                          <el-image style="width: 100px; height: 100px" :src="scope.row.COVER" :preview-src-list="[scope.row.COVER]"></el-image>
                        </template>
                      </el-table-column>

                      <el-table-column label="Product price" prop="SELL_PRICE"><!--商品价格-->
                          <template slot-scope="scope">
                              <span>{{ Math.round(scope.row.SELL_PRICE * 100) / 100 }}</span>
                          </template>
                      </el-table-column>
                      <el-table-column label="Product BV" prop="PRICE_PV" v-if="goodsCategory === '1'"><!--价格PV-->
                          <template slot-scope="scope">
                              <span>{{ Math.round(scope.row.PRICE_PV * 100) / 100 }}</span>
                          </template>
                      </el-table-column>

                      <el-table-column label="Tax rate" prop="TAX_RATE"><!--税率-->
                          <template slot-scope="scope">
                              <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
                          </template>
                      </el-table-column>

                      <el-table-column label="Tax"><!--税额-->
                          <template slot-scope="scope">
                              <span>{{ Math.round((scope.row.SELL_PRICE - scope.row.SELL_PRICE / (1 + scope.row.TAX_RATE / 100)) * 100) / 100 }}</span>
                          </template>
                      </el-table-column>

                      <el-table-column label="Inventory" prop="STORE_NUMS"><!--库存-->
                      </el-table-column>

                      <el-table-column label="Qty"  width="155"><!--数量-->
                        <template slot-scope="scope">
                          <el-input-number size="mini" v-model="numList[scope.$index]"  :min="0" :max="Number(scope.row.STORE_NUMS)" @change="(val)=>{handleInputNumber(val, scope.row)}"></el-input-number>
                        </template>

                      </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <div class="white-box-footer">

                <el-button @click="goToAccounts()">Check Out</el-button><!--去结算-->

                <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
            </div>
        </div>
    </div>
</template>

<script>
    import network from '@/utils/network'
    import baseInfo from '@/utils/baseInfo'
    import store from '@/utils/vuexStore'
    import tool from '@/utils/tool'
    import Pagination from '@/components/Pagination'
    export default {
        name: "index",
        components: {Pagination},
        mounted() {
            this.getGoodsActive()
            this.getData()
        },
        data() {
            return {
                loading: false,
                num:1,
                form:{

                },
                tableData:[],
                list: [],
                tool: tool,
                currentPage: 1,
                totalPages: 1,
                totalCount: 1,
                pageSize: 20,
                multipleSelection: [],
                is_go_order:true,
                numList: [],
                selectLock:false,
                goodsCategory: '1',
                goodsActive: [],
                maxHeight: tool.getTableHeight(),
            }
        },
        watch: {
            '$route': function () {
                this.getData()
            },
            // 监听多选按钮,判断结算按钮是否可用
            // multipleSelection: function (modern, origin) {
            //     if (modern.length > 0) {
            //         this.$data.disabled = false
            //     }
            // },
        },
        methods: {
            handleChange(val){
                console.log(val);
            },
            goToAccounts() {
                if (this.multipleSelection.length <= 0) {
                  this.$message.error('Please choose the products.')
                  return false
                }

                this.is_go_order=true;
                // this.multipleSelection.map((item,index)=>{
                //     item.chose_num = parseInt(item.chose_num);
                //     if(item.chose_num==0){
                //         this.$message({
                //             message: '请选择商品数量进行结算',
                //             type: 'error'
                //         })
                //         this.is_go_order=false
                //     }
                // });
                setTimeout(()=>{
                    if(this.is_go_order){
                        sessionStorage.setItem('order_goods',JSON.stringify(this.multipleSelection))
                        sessionStorage.setItem('category_type', this.goodsCategory)
                        this.$router.push({path: `/shop/order`})
                    }
                },0)

                // if (rows) {
                // rows.forEach(row => {
                //     this.$refs.multipleTable.toggleRowSelection(row);
                // });
                // } else {
                // this.$refs.multipleTable.clearSelection();
                // }
            },
            handleSelectionChange(val) {
                if( this.selectLock ) return;
                let idx = -1,num;
                for(let i in this.tableData){
                    for(let v in val){
                        if(val[v].ID==this.tableData[i].ID){
                            idx = i;
                            num = this.numList[idx];
                            val[v]["chose_num"] = num;
                            break;
                        }
                    }
                }
                this.multipleSelection[this.currentPage] = val;
                console.log(this.multipleSelection);
            },
            handleInputNumber(val, row){
                let pageList = this.multipleSelection[this.currentPage];
                let selectStatus = false;
                for(let i in pageList){
                    if( pageList[i].ID == row.ID ) {
                        pageList[i].chose_num = val;
                        selectStatus = true;
                        break;
                    }
                }

                if( selectStatus ) {
                    this.multipleSelection[this.currentPage] = pageList;
                }
            },
            getScope(scope){
                console.log(scope);
            },
            handleCurrentChange (page) {
                this.getData(page, this.pageSize)
            },
            handleSizeChange (pageSize) {
                this.getData(this.currentPage, pageSize)
            },
            /*getData() {
                network.getData(`shop/index`).then(response => {
                    console.log(response)
                    this.loading = false;
                    this.list = response.list;
                    let settingObj=this.list;
                    let settingArr = Object.keys(settingObj).map(key => {
                        //console.log(key); //为每个键名
                        return settingObj[key];  //把每个对象返回出去生成一个新的数组中相当于0:{id:1}
                    } );
                    this.tableData=settingArr;
                    console.log(this.tableData)

                  /!*  this.$set(this.main_push,index,{...this.main_push[index],cacheImg:`http://naotianshi.cn/${this.lest[index].IMAGES}`})*!/
                }).catch(() => {
                });
            },*/
            getData (page, pageSize) {
                let obj = this
                network.getPageData(this, `shop/index`, page, pageSize, { categoryType: obj.goodsCategory }, function (response) {
                    obj.loading = false;
                    obj.currentPage = response.currentPage;
                    obj.list = response.list;
                    let settingObj=obj.list;
                    for(let i in settingObj){
                        obj.numList[i] = 1;
                        settingObj[i].chose_num=0;

                        // obj.$refs.multipleTable.toggleRowSelection(settingObj[i],true);
                    }
                    // let settingArr = Object.keys(settingObj).map(key => {
                    //     this.numList[key] = 1;
                    //     // console.log(key); //为每个键名
                    //     settingObj[key].chose_num=0;
                    // } );
                    obj.selectLock = true;
                    obj.tableData=Object.values(settingObj);
                    let pageList = obj.multipleSelection[obj.currentPage];
                    obj.$nextTick(function () {
                        for(let i in obj.tableData){
                            for( let j in  pageList) {
                                if( pageList[j].ID === obj.tableData[i].ID ) {
                                    obj.numList[i] = pageList[j].chose_num;
                                    obj.tableData[i].chose_num = pageList[j].chose_num;
                                    obj.$refs.multipleTable.toggleRowSelection(obj.tableData[i],true);
                                    break;
                                }
                            }
                        }
                        obj.selectLock = false;
                    })

                })
            },
            // 获取商品类型,填充tabs页
            getGoodsActive() {
                network.getData(`shop/goods-active`).then(response => {
                    this.goodsActive = response
                })
            },
            // 切换tab页回调
            handleClick(tab) {
                // 切换标签. 查询商品列表,将当期商品分类传入查询条件filter
                this.goodsCategory = tab.name
                // 查询商品列表
                this.getData()
            },
        }

    }
</script>

<style scoped>
.flex{
    display: flex;
}
</style>
