<template>
  <view class="">
    <view class="flex items-center px-40rpx text-32rpx bg-white py-30rpx sticky top-0 z-99">
      <view class="mr-15rpx">商品信息</view>
      <u-search @search="searchGoods" class="flex-1" placeholder="货号或名称" v-model="keyword" :show-action="false">
      </u-search>
       <u-icon @tap="onQR" class="ml-20rpx" name="scan" color="#333333" size="48"></u-icon>
    </view>
    <!-- 有商品时 -->
    <block v-if="!isShow">
      <!-- 搜索的商品列表 -->
      <view class="px-30rpx bg-white" v-if="goodsList.length">
        <block v-for="(item,index) in goodsList" :key="index">
          <GoodsItem :isAdd="true" :goods="item" @addGood="addGood" />
        </block>
      </view>
       <view v-if="chooseList.length>0" class="py-20rpx text-40rpx font-extrabold text-center">下单商品</view>
      <!-- 提货数量 -->
      <view class=" bg-white">
        	<u-swipe-action   v-for="(item, index) in chooseList" :key="item.id" :show="item.show" :index="index" 	@click="click" @open="open" :options="options"
		>
        <view  class="py-20rpx flex w-full items-start px-30rpx" >
          <view
            class="w-38rpx mt-8rpx h-38rpx rounded-full border border-hex-ef4444 border-solid text-center leading-38rpx text-hex-ef4444">
            {{index+1}}
          </view>
          <view class="flex-1 ml-15rpx">
            <view class="flex items-center">
              <view class="flex flex-1 items-center justify-between">
                <view>默认已提货量》</view>
                <view>
                  <u-number-box :min="0" v-model="item.defaultNum" :max="item.num">
                  </u-number-box>
                </view>
              </view>
            </view>
            <GoodsItem class="px-0" :goods="item" @numChange="numChange" />
          
          </view>
        </view>
          <u-line v-if="chooseList.length-1!=index" :hair-line="false" color="#c8c9cc"></u-line>
        	</u-swipe-action>
      </view>
      <view class="h-180rpx"></view>
      <!-- 底部按钮 -->
      <view class="flex items-center justify-end bg-white bottom-card z-99 fixed inset-x-0">
        <view class="flex items-center">
          <view>
            合计
            <text class="ml-10rpx price-text text-hex-ef4444">{{totalPrice}}元</text>
          </view>
          <view class="ml-10rpx">
            vip
            <text class="ml-10rpx price-text text-hex-ef4444">{{vipPrice}}元</text>
          </view>
        </view>
        <view @click="qrCode" class="bg-hex-ef4444 h-100rpx w-210rpx text-white text-center leading-100rpx ml-30rpx">
          生成二维码</view>
      </view>
    </block>
    <!-- 无商品时 -->
    <block v-else>
      <view class="flex items-center justify-center flex-col mt-80rpx">
        <image src="http://cdn.uviewui.com/uview/empty/car.png" mode="aspectFill"></image>
        <view class="text-hex-909399 -mt-20rpx">请搜索您需要的商品</view>
      </view>
    </block>
    <cu-modal v-model="modeShow" @confirm="confirm" confirm-color="#378264" show-cancel-button content="是否生成二维码？"
      confirmText="确认" cancelText="再想想">
    </cu-modal>
  </view>
</template>

<script>
  import GoodsItem from './components/goods-item.vue'
  export default {
    components: {
      GoodsItem
    },
    data() {
      return {
        modeShow: false,
        isShow: true,
        id: '',
        keyword: '',
        list: [], //搜索的商品
        chooseList: [], //选择的商品
        goodItem: {},
        options: [
					{
						text: '删除',
						style: {
							backgroundColor: '#ef4444'
						}
					}
				]
      };
    },
    onLoad({
      id
    }) {
      this.id = id
    },
    computed: {
      //普通价格合计
      totalPrice() {
        const total = this.chooseList.reduce((pr, cu) => {
          return pr + cu.sell_price * cu.num
        }, 0)
        return total.toFixed(2)
      },
      //会员价合计
      vipPrice() {
        const total = this.chooseList.reduce((pr, cu) => {
          return pr + cu.vip_price * cu.num
        }, 0)
        return total.toFixed(2)
      },
      goodsList(){
        return this.list?.map(e=>{
          return {
            ...e,
            defaultNum:1,
            num:1
          }
        })
      }
    },
    methods: {
      click(index,index1) {
       
        if(index1==0){
          this.$nextTick(()=>{
            this.chooseList.splice(index, 1)
             this.chooseList[index].show = false;
          })
        }
			},
			open(index) {
				 this.chooseList[index].show = true;
				 this.chooseList.forEach((val, idx) => {
					if(index != idx) this.chooseList[idx].show = false;
				})
			},
      //扫码
      onQR(){
        uni.scanCode({
           onlyFromCamera: true,
        	success: ({result})=>{
             this.keyword=result
             this.searchGoods()
        	},
          fail:err=>{
            this.$u.toast('扫码失败，请重新扫描')
          }
        });

      },
      async searchGoods() {
        const resDate = await this.$api.get(`/v1/store/${this.id}/products`, {
          params: {
            keyword: this.keyword
          }
        })
        this.list = resDate.data
        if (this.list.length == 0) {
          return this.$u.toast('暂未搜索到该商品')
        }
        this.isShow = false
        // this.goodList=
        // let goodsObj = resDate.data.length > 0 ? resDate.data[0] : {}
        // goodsObj.defaultNum = 1
        // goodsObj.num = 1
        // this.goodItem = goodsObj
      },
      //添加商品
      addGood(e) {
        const result = this.chooseList.findIndex(item => item.id == e)
        if (result == -1) {
          const goodsItem=this.goodsList?.find(el=>el.id==e)
          this.chooseList.push(Object.assign(goodsItem,{show:false}))
        } else {
          const num = this.chooseList[result].num + 1
          this.getUpdate(result, num)
        }
      },
      //商品数量改变
      numChange(id, value) {
        const Index = this.chooseList.findIndex(item => item.id == id)
        this.getUpdate(Index, value)
      },
      //刷新页面
      getUpdate(Index, val) {
        this.chooseList[Index].num = val
        this.chooseList[Index].defaultNum = val
        this.chooseList = [...this.chooseList]
      },
      qrCode() {
        if (this.chooseList.length == 0) {
          return this.$u.toast('至少选选择一件商品')
        }
        this.modeShow = true
      },
      //生成二维码
      async confirm() {
        uni.showLoading({
          title: '二维码生成中',
          mask: true
        });
        try {
          const arrList = this.chooseList.map(item => {
            return {
              sku_id: item.id,
              quantity: item.num,
              send: item.defaultNum
            }
          })
          const obj = {
            store_id: this.id,
            products: arrList,
            note: ''
          }
          const {
            image
          } = await this.$api.post(`/v1/order-pre`, obj);
          this.$u.route('/pageB/code/index', {
            image
          })
          this.keyword = ''
          this.list = []
          this.chooseList = []
          this.goodItem = {}
          this.isShow = true
          uni.hideLoading()
        } catch (err) {}finally{

        }
      }
    }
  }
</script>
<style>
</style>
<style lang="scss">
  .bottom-card {
    box-shadow: 0px -4rpx 8rpx rgba(0, 0, 0, 0.25);
    bottom: var(--window-bottom);
  }
</style>
