<template>
    <div v-loading="loading">
      <div class="radio">
        <el-radio-group v-model="cateId" @change="cateIdChange">
          <el-radio :label="1">国内商品</el-radio>
          <el-radio :label="2" v-if="baseInfo.overseasShopOpen === '1'">海外商品</el-radio>
        </el-radio-group>
      </div>
        <div class="white-box">
            <el-table v-if="numList.length > 0" 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="商品名称" prop="GOODS_NAME">

                </el-table-column>


                <el-table-column label="商品来源" prop="CATE"></el-table-column>

                <el-table-column label="图片" >
                     <template slot-scope="scope">
                        <el-image style="width: 100px; height: 100px" :src="tool.getLocaleLink(scope.row.COVER, '/files/')" :preview-src-list="[tool.getLocaleLink(scope.row.COVER, '/files/')]"></el-image>
                     </template>
                </el-table-column>

                <el-table-column label="商品价格" prop="SELL_PRICE">
                </el-table-column>
                <el-table-column label="价格PV" prop="PRICE_PV">
                </el-table-column>
                <el-table-column label="库存" prop="STORE_NUMS">
                </el-table-column>

                <el-table-column label="数量"  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 @click="goToAccounts()">去结算</el-button>
                <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
            </div>
        </div>

      <!--    微信内打开提示-->
      <transition name="el-fade-in-linear">
        <div v-show="isWeChat" class="isWeChatModal">
          <div class="modal-box">
            <div class="transition-box">
              <img class="arrow" src="../../static/img/arrow_icon.png" alt="">
              <div>
                检测到您正在微信中使用系统
              </div>
              <div>
                在微信中无法完成海外商品的付款
              </div>
              <div class="browser">
                <span>请点击右上角“<i class="el-icon-more"></i>”</span>
              </div>
              <div class="browser">
                <span>选择“</span>
                <img src="../../static/img/browser.png" alt="" style="width: 20px">
                <span>在浏览器中打开 ”</span>
              </div>
            </div>
            <div>
              <i class="el-icon-close closeWechat" style="font-size: 45px" @click="closeIsWeChatModal"></i>
            </div>
          </div>

        </div>
      </transition>
    </div>
</template>

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

export default {
        name: "index",
        components: {Pagination},
        mounted() {
            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,
                cate: [],
                cateId: 1,
                baseInfo: JSON.parse(localStorage.getItem('baseInfo')),
                isWeChat: false,
            }
        },
        watch: {
            '$route': function () {
                this.getData()
            }
        },
        created() {
          // network.getData('shop/logistics').then(response => {
          //   console.log(response);
          // }).catch(err => {
          //   console.log(err);
          // })
        },
        methods: {
            cateIdChange(val){
              if(val === 2){
                this.isWeChat = this.is_weixn();
              }
              if(val){
                this.getData(this.currentPage, this.pageSize)
              }
            },
            handleChange(val){
                console.log(val);
            },
            goToAccounts() {
                if (this.cate.length > 1) {
                  this.$message({
                    message: '海内商品、海外商品只能选择一种',
                    type: 'warning'
                  })
                  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))
                        this.$router.push(this.cate[0] == '1' ? {path: `/shop/order`} : {path: `/shop/order-overseas`})
                    }
                },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;
                this.cate = []
                let cateList = []
                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;
                            cateList.push(val[v].CATE_ID)
                            break;
                        }
                    }
                }

                for (let i = 0; i < cateList.length; i++) {
                    if (cateList.indexOf(cateList[i]) === i) {
                       this.cate.push(cateList[i])
                    }
                }

                if ((this.cate.length > 1)) {
                    // 海内/海外商品只能选择一种
                    if (this.cate.length > 1) {
                        this.$message({
                          message: '海内商品、海外商品只能选择一种',
                          type: 'warning'
                        })
                        return false
                    }
                }

                this.multipleSelection[this.currentPage] = val
            },
            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
                let filterData = {
                  cateId: obj.cateId
                }
                network.getPageData(this, `shop/index`, page, pageSize, filterData, 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;
                    })

                })
            },
          is_weixn(){
            const ua = navigator.userAgent.toLowerCase();
            return ua.indexOf('micromessenger') !== -1;
          },
          closeIsWeChatModal(){
            this.isWeChat = false
          }
        }

    }
</script>

<style scoped>
.flex{
    display: flex;
}
.radio{
  margin-bottom: 1rem;
}
.isWeChatModal{
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.8); /* 黑色背景，50% 透明度 */
  z-index: 9999;
  color: white;
  font-size: 24px;
}
.transition-box{
  display: flex;
  align-items: center;
  flex-direction: column;
}
.transition-box div{
  padding: 20px 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.browser img, i{
  padding: 0 6px;
}
.closeWechat{
  transform: translateY(-8rem);
}
.arrow{
  width: 30%;
  align-self: flex-end;
  transform: translateX(-60px);
}
.modal-box{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
</style>
