<template>
    <div v-loading="loading">
        <div class="white-box">
            <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="Product Name" prop="GOODS_NAME"></el-table-column><!--商品名称-->
              <el-table-column label="Product Picture"><!--图片-->
                  <template slot-scope="scope">
                      <el-image style="width: 100px; height: 100px" :src="tool.getArImage(scope.row.COVER, '/files/')" :preview-src-list="[tool.getArImage(scope.row.COVER, '/files/')]"></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="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>

            <div class="white-box-footer">
                <el-button type="primary" size="small" @click="goToAccounts()">Check Out</el-button><!--去结算-->
                <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
            </div>
            <div class='flex data' style="line-height: 35px; font-size: 14px;margin-top: 20px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 15px;">
              <div style="margin-right: 2rem;">Price：₦ {{ sell_price_sum }}</div><!--商品价格-->
              <div>Tax：₦ {{ tax_sum }}</div><!--商品税额-->
            </div>
        </div>
    </div>
</template>

<script>
import network from '@/utils/network'
import tool from '@/utils/tool'
import Pagination from '@/components/Pagination'

export default {
    name: "ba-product-list",
    components: {
        Pagination
    },
    async created() {
        await 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,
            maxHeight: tool.getTableHeight() - 35,
            sell_price_sum: 0.00,
            tax_sum: 0.00,
        }
    },
    watch: {
        '$route': function () {
            this.getData()
        },
    },
    methods: {
        async getData (page, pageSize) {
            let obj = this
            await network.getPageData(this, `shop/ba-product-list`, page, pageSize, {}, 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.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;
                                break;
                            }
                        }
                    }
                    obj.selectLock = false;
                })
            })
        },
        goToAccounts() {
            if (this.multipleSelection.length <= 0) {
                this.$message.error('Please choose the products.')
                return false
            }

            this.is_go_order = true;
            setTimeout(() => {
                if(this.is_go_order) {
                    // 填充商品信息到购物车
                    sessionStorage.setItem('order_goods', JSON.stringify(this.multipleSelection))
                    this.$router.push({path: `/shop/ba-shopping-cart`});
                }
            })
        },
        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;

            // 计算统计
            this.handleSureChange()
        },
        handleSureChange() {
            if (this.multipleSelection.length > 0) {
                let accumulatorSellPrice = 0, accumulatorPricePv = 0, accumulatorTax = 0;
                this.multipleSelection.forEach(item => {
                    item.forEach(accumulator => { accumulatorSellPrice += accumulator.SELL_PRICE * accumulator.chose_num * accumulator.DISCOUNT / 100; });
                    item.forEach(accumulator => { accumulatorPricePv += Number(accumulator.PRICE_PV) * Number(accumulator.chose_num) * (Number(accumulator.DISCOUNT) / 100); });
                    item.forEach(accumulator => { accumulatorTax += tool.calculateTax(Number(accumulator.SELL_PRICE), Number(accumulator.TAX_RATE), Number(accumulator.chose_num)); });
                })

                this.sell_price_sum = parseFloat(accumulatorSellPrice).toFixed(2);
                this.price_pv_sum = parseFloat(accumulatorPricePv).toFixed(2);
                this.tax_sum = parseFloat(accumulatorTax).toFixed(2);
            } else {
                this.sell_price_sum = 0.00;
                this.price_pv_sum = 0.00;
                this.tax_sum = 0.00;
            }
        },
        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;
                // 计算统计
                this.handleSureChange()
            }
        },
        handleCurrentChange (page) {
            this.getData(page, this.pageSize)
        },
        handleSizeChange (pageSize) {
            this.getData(this.currentPage, pageSize)
        },
    }
}
</script>

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