<!--
 * @Descripttion:
 * @version:
 * @Author: kBank
 * @Date: 2022-11-21 15:11:22
-->
<template>
  <view class="content">
    <view class="context">
      <view
        class="kuang"
        v-for="(item, index) in shopCarList"
        :key="item.specialArea"
      >
        <view class="kuang_t">
          <u-checkbox-group
            v-model="item.isSelectAll"
            @change="checkAll(index, $event)"
          >
            <u-checkbox
              activeColor="#005BAC"
              shape="circle"
              :name="item.specialArea"
            >
            </u-checkbox>
            {{ item.specialAreaVal }}
          </u-checkbox-group>
        </view>
        <u-checkbox-group
          v-model="item.isSelect"
          shape="circle"
          placement="column"
          @change="checkboxChange($event, item)"
        >
          <view
            v-for="(ctem, cndex) in item.shoppingCartList"
            :key="cndex"
            class="goodList"
          >
            <u-checkbox
              activeColor="#005BAC"
              :name="ctem.shoppingId"
            ></u-checkbox>
            <view class="goodList_i">
              <view class="goodList_it">
                <img :src="ctem.cover1" class="cover" alt="" />
                <view class="goodList_ir">
                  <view class="tit1">
                    {{ ctem.waresName }}
                  </view>
                  <view class="goodList_ib">
                    <view class="tit2">
                      {{ ctem.waresPrice | numberToCurrency | isLocal }}
                    </view>
                    <view class="tit3"
                      >业绩:
                      {{ ctem.achieve | numberToCurrency | isLocal }}</view
                    >
                  </view>
                </view>
              </view>
              <view
                v-for="(stem, sndex) in ctem.productParams"
                :key="sndex"
                class="product_i"
              >
                <img :src="stem.cover" alt="" />
                <view class="product_il">
                  <view class="tit4"
                    >{{ stem.productName
                    }}{{
                      (stem.waresItemsParamsList.length > 0 &&
                        stem.waresItemsParamsList[0].specsName) ||
                      ''
                    }}</view
                  >
                  <!-- <view class="tit4"></view> -->
                  <view class="tit5"
                    >x{{
                      (stem.waresItemsParamsList.length > 0 &&
                        stem.waresItemsParamsList[0].quantity) ||
                      ''
                    }}</view
                  >
                </view>
              </view>
              <view class="goodsSet">
                <u-number-box
                  :min="1"
                  @change="changeCar($event, item, ctem)"
                  v-model="ctem.number"
                ></u-number-box>
                <u-icon
                  name="trash"
                  @tap="delOne(ctem)"
                  size="26"
                  color="#BFBFBF"
                ></u-icon>
              </view>
            </view>
          </view>
        </u-checkbox-group>
      </view>
    </view>
    <view class="kong_t">
      <img
        class="kong"
        v-show="shopCarList.length == 0"
        src="@/static/images/kong.png"
        alt=""
    /></view>
    <view class="zhan"></view>
    <!-- 底部 -->
    <view class="footer_f">
      <view class="footer">
        <view class="footer_l">
          <view class="footer_ll">
            <u-icon size="36" name="shopping-cart"> </u-icon>
            <view class="footer_lr">
              <view class="r1">{{
                totalPrice | numberToCurrency | isLocal
              }}</view>
              <view class="l1">业绩:{{ totalAchive | numberToCurrency }}</view>
            </view>
          </view>
        </view>
        <view class="footer_r">
          <u-button
            type="success"
            class="uBtn"
            shape="circle"
            :loading="isLoading"
            :loadingText="'购买中'"
            @tap="goBuy"
            :disabled="checkoutDisabled"
            color="#005BAC"
            >去结算
          </u-button>
        </view>
      </view>
    </view>
    <cl-tabbar :current="3"></cl-tabbar>
    <view class="pp">
      <u-popup
        :show="dialogVisible2"
        :closeable="true"
        :closeOnClickOverlay="false"
        mode="center"
        @close="dialogVisible2 = false"
      >
        <view class="popList">
          <u-checkbox-group
            v-model="allTable"
            placement="column"
            @change="handleSelectionChange"
          >
            <view class="popList_i" v-for="item in tableData" :key="item.pkId">
              <u-checkbox :name="item.pkId"> </u-checkbox>
              <view class="popList_ii">
                <img :src="item.cover || item.cover1" alt="" />
                <view>
                  <view>{{ item.waresName }}</view>
                  <view>{{ item.waresCode }}</view>
                  <view>{{ item.waresPrice }}</view>
                  <!-- <view>{{ item.quantity }}</view> -->
                  <u-number-box v-model="item.quantity" :min="1"></u-number-box>
                </view>
              </view>
            </view>
          </u-checkbox-group>
          <view class="popBtm">
            <view>合计:{{ total | toThousandthAndKeepDecimal }}</view>
            <view class="que" @click="tableTrue">确定</view>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
import * as api from '@/config/goods'
import clTabbar from '@/components/cl-tabbar.vue'
import RaisedTabbar from '@/components/raised-tabbar.vue'
import { canOrder } from '@/config/order'
export default {
  components: {
    'cl-tabbar': RaisedTabbar,
  },
  data() {
    return {
      isSelectAll: [],
      shopCarList: [],
      isLoading: false,
      goodsCheck: [],
      totalPrice: 0,
      totalAchive: 0,
      num: 0,
      pkCountry: 1,
      tableData: [],
      dialogVisible2: false,
      selTable: [],
      allTable: [],
      total: '0.00',
    }
  },
  computed: {
    checkoutDisabled() {
      return this.shopCarList.filter(item => item.isSelected).length !== 1
    },
  },
  watch: {
    selTable: {
      handler(n, o) {
        let total = 0
        n.forEach(item => {
          total += Number(item.waresPrice) * item.quantity
        })
        this.total = total
      },
      deep: true,
    },
  },
  onLoad(options) {
    // this.getCarList()
  },
  onShow() {
    this.getCarList()
    this.initCarList()
  },
  methods: {
    tableTrue() {
      if (this.selTable.length > 0) {
        let a = {
          specialArea: this.goodsCheck[0].specialArea,
          orderItemsParams: [],
        }
        a.orderItemsParams = this.selTable.map(item => {
          return {
            waresCode: item.waresCode,
            quantity: item.quantity,
            waresItemsParamList: item.productGroup,
            energySilo: 1,
          }
        })
        a.orderItemsParams.forEach(item => {
          item.waresItemsParamList = item.waresItemsParamList.map(ctem => {
            return {
              pkWaresSpecsSku: ctem.pkSkuId,
              quantity: ctem.quantity,
            }
          })
        })
        api.energyShopSilo(a).then(res => {
          if (res.code == 200) {
            this.dialogVisible2 = false
            let shoppArr = this.goodsCheck[0].orderItemsParams.map(item => {
              return item.shoppingId
            })
            if (this.goodsCheck[0].specialArea == 1) {
              uni.navigateTo({
                url:
                  '/pages/regiest/index?specialArea=' +
                  this.goodsCheck[0].specialArea +
                  '&shoppArr=' +
                  JSON.stringify(shoppArr) +
                  '&selTable=' +
                  JSON.stringify(this.selTable),
              })
            } else if (this.goodsCheck[0].specialArea == 2) {
              uni.navigateTo({
                url:
                  '/pages/other/index?specialArea=' +
                  this.goodsCheck[0].specialArea +
                  '&shoppArr=' +
                  JSON.stringify(shoppArr) +
                  '&selTable=' +
                  JSON.stringify(this.selTable),
              })
            }
          }
        })
      } else {
        uni.showToast({
          title: '请选择赠品',
          icon: 'none',
        })
      }
    },
    handleSelectionChange(val) {
      let arr = []
      this.tableData.forEach(item => {
        val.forEach(ctem => {
          if (item.pkId == ctem) {
            arr.push(item)
          }
        })
      })
      this.selTable = arr
    },
    checkAll(index, e) {
      if (e.length > 0) {
        this.$set(this.shopCarList[index], 'isSelected', true)
        this.shopCarList[index].shoppingCartList.forEach(ctem => {
          this.shopCarList[index].isSelect.push(ctem.shoppingId)
        })
        this.checkArea()
      } else {
        this.$set(this.shopCarList[index], 'isSelected', false)
        this.shopCarList[index].shoppingCartList.forEach(ctem => {
          this.$set(this.shopCarList[index], 'isSelect', [])
        })
        this.checkArea()
      }
    },
    canOrder(shoppingIds, specialArea) {
      return new Promise((resolve, reject) => {
        canOrder({
          shoppingIds,
          specialArea,
        }).then(res => {
          if (res.code == 200 && res.data?.flag === 0) {
            resolve(true)
          } else {
            reject(res.data?.msg)
          }
        })
      })
    },
    async goBuy() {
      let shoppArr = this.goodsCheck[0].orderItemsParams.map(item => {
        return item.shoppingId
      })
      try {
        await this.canOrder(shoppArr, this.goodsCheck[0].specialArea)
      } catch (msg) {
        uni.showToast({
          title: msg,
          icon: 'none',
        })
        return
      }

      if (
        this.goodsCheck[0].specialArea == 1 ||
        this.goodsCheck[0].specialArea == 24
      ) {
        let deleteList = []
        shoppArr.forEach(item => {
          deleteList.push({
            shoppingId: item,
          })
        })
        uni.navigateTo({
          url:
            '/pages/regiest/index?specialArea=' +
            this.goodsCheck[0].specialArea +
            '&shoppArr=' +
            JSON.stringify(shoppArr),
        })
      } else if (this.goodsCheck[0].specialArea == 21) {
        uni.setStorageSync(
          'haiConfirm',
          JSON.stringify(this.goodsCheck[0].orderItemsParams)
        )
        uni.navigateTo({
          url: '/pages/other/haiConfirm?shoppArr=' + JSON.stringify(shoppArr),
        })
      } else if (this.goodsCheck[0].specialArea == 7) {
        uni.navigateTo({
          url:
            '/pages/hiFans/index?specialArea=' +
            this.goodsCheck[0].specialArea +
            '&shoppArr=' +
            JSON.stringify(shoppArr),
        })
      } else {
        if (this.goodsCheck[0].specialArea == 2) {
          let deleteList = []
          shoppArr.forEach(item => {
            deleteList.push({
              shoppingId: item,
            })
          })
          uni.navigateTo({
            url:
              '/pages/other/index?specialArea=' +
              this.goodsCheck[0].specialArea +
              '&shoppArr=' +
              JSON.stringify(shoppArr),
          })
        } else if (this.goodsCheck[0].specialArea == 30) {
          if (this.goodsCheck[0].orderItemsParams.length > 1) {
            uni.showToast({
              title: '续约专区每次只能购买一件商品',
              icon: 'none',
            })
            return false
          } else {
            let num = this.goodsCheck[0].orderItemsParams.some(
              item => item.quantity > 1
            )
            if (num) {
              uni.showToast({
                title: '续约专区每次只能购买一件商品',
                icon: 'none',
              })
              return false
            } else {
              uni.navigateTo({
                url:
                  '/pages/other/index?specialArea=' +
                  this.goodsCheck[0].specialArea +
                  '&shoppArr=' +
                  JSON.stringify(shoppArr),
              })
            }
          }
        } else if (this.goodsCheck[0].specialArea == 31) {
          if (this.totalPrice < 1000) {
            uni.showToast({
              title: '购买商品总价格不能低于1000元',
              icon: 'none',
              duration: 1500,
            })
          } else {
            uni.navigateTo({
              url:
                '/pages/other/index?specialArea=' +
                this.goodsCheck[0].specialArea +
                '&shoppArr=' +
                JSON.stringify(shoppArr),
            })
          }
        } else {
          uni.navigateTo({
            url:
              '/pages/other/index?specialArea=' +
              this.goodsCheck[0].specialArea +
              '&shoppArr=' +
              JSON.stringify(shoppArr),
          })
        }
      }
    },
    // 修改数量
    changeCar(e, item, ctem) {
      api
        .plusReduceShopping({
          shoppingId: ctem.shoppingId,
          number: e.value,
          specialArea: item.specialArea,
        })
        .then(res => {
          if (res.code == 200) {
            this.checkArea()
          } else {
            this.getCarList()
          }
          this.$store.dispatch('getCarLength')
        })
    },
    checkArea() {
      let arr = []
      this.shopCarList.forEach(item => {
        item.shoppingCartList.forEach(ctem => {
          if (item.isSelect.indexOf(ctem.shoppingId) > -1) {
            arr.push({
              specialArea: item.specialArea,
              orderItemsParams: [
                {
                  waresCode: ctem.waresCode,
                  shoppingId: ctem.shoppingId,
                  waresName: ctem.waresName,
                  achieve: ctem.achieve,
                  waresPrice: ctem.waresPrice,
                  cover1: ctem.cover1,
                  quantity: ctem.number,
                  waresItemsParamList: ctem.waresItemsParamList,
                  waresSkuList: ctem.waresSkuList || [],
                  source: ctem.source || '',
                },
              ],
            })
          }
        })
      })
      const arrayHashmap = arr.reduce((obj, item) => {
        obj[item.specialArea]
          ? obj[item.specialArea].orderItemsParams.push(
              ...item.orderItemsParams
            )
          : (obj[item.specialArea] = item)
        return obj
      }, {})
      this.goodsCheck = Object.values(arrayHashmap)
      this.checkPrice()
    },
    // 计算价格
    checkPrice() {
      let totalPrice = 0
      let totalAchive = 0
      let num = 0
      this.goodsCheck.forEach(item => {
        item.orderItemsParams.forEach(ctem => {
          totalPrice += parseFloat(ctem.waresPrice * ctem.quantity)
          totalAchive += parseFloat(ctem.achieve * ctem.quantity)
          num += ctem.quantity
        })
      })
      // if (this.goodsCheck.length != 1) {
      this.totalPrice = totalPrice.toFixed(2)
      this.totalAchive = totalAchive.toFixed(2)
      this.num = num
      // }
    },
    checkboxChange(e, item) {
      if (e.length > 0) {
        this.$set(item, 'isSelected', true)
        this.$set(item, 'isSelect', e)
        this.checkArea()
      } else {
        this.$set(item, 'isSelected', false)
        this.$set(item, 'isSelect', e)
        this.checkArea()
      }
    },
    // 单删
    delOne(ctem) {
      let deleteList = [
        {
          shoppingId: ctem.shoppingId,
        },
      ]
      api.batchDelShopping({ deleteList: deleteList }).then(res => {
        this.getCarList()
        this.$store.dispatch('getCarLength')
        // this.getShoppingCount()
        uni.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1500,
        })
      })
    },
    initCarList() {
      this.shopCarList = []
      this.goodsCheck = []
      this.totalPrice = 0
      this.totalAchive = 0
      this.num = 0
    },
    getCarList() {
      api.getShopping().then(res => {
        res.data.forEach(item => {
          item.isSelected = false
          item.isSelect = []
          item.isSelectAll = []
          item.shoppingCartList.forEach(ctem => {
            ctem.waresItemsParamList = []
            if (item.specialArea != 21) {
              ctem.productParams.forEach(stem => {
                if (stem.waresItemsParamsList.length > 0) {
                  stem.waresItemsParamsList[0].pkWaresSpecsSku =
                    stem.waresItemsParamsList[0].pkSkuId
                  stem.waresItemsParamsList[0].productName = stem.productName
                  ctem.waresItemsParamList.push(stem.waresItemsParamsList[0])
                }
              })
            }
          })
        })
        this.shopCarList = res.data
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  background: #f9f9f9;
  height: 100vh;
}

.context {
  // padding: 24rpx;
}

.kuang {
  // padding: 20rpx 40rpx;
  background: #fff;
  box-shadow: 0px 2px 10px 0px rgba(204, 204, 204, 0.5);
  border-top: 20rpx solid #f6f5f3;
}

.kuang_t {
  border-bottom: 1px solid #eeeeee;
  padding: 40rpx 24rpx;
}

.goodList {
  display: flex;
  padding: 0 20rpx;
  border-bottom: 1px solid #eee;
}

.cover {
  width: 136rpx;
  height: 136rpx;
  background: #ffffff;
  border: 1px solid #eeeeee;
  border-radius: 10rpx;
}

.goodList_i {
  flex: 1;
}

.goodList_it {
  display: flex;
  padding: 20rpx 0;
  .goodList_ir {
    margin-left: 20rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .goodList_ib {
      display: flex;
      align-items: center;
      justify-content: space-between;
      img {
        width: 56rpx;
        height: 56rpx;
      }
    }
  }
}

.goodsSet {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 26rpx 0;
}

.product_i {
  display: flex;
  align-items: center;
  background: #f6f6f6;
  padding: 15rpx;
  .product_il {
    display: flex;
    align-items: center;
    flex: 1;
    justify-content: space-between;
    margin-left: 20rpx;
  }
  img {
    width: 50rpx;
    height: 50rpx;
    background: #ffffff;
    border: 1px solid #dddddd;
    border-radius: 10rpx;
  }
}

.tit1 {
  font-size: 28rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #333333;
}

.tit2 {
  font-size: 36rpx;
  font-family: Source Han Sans CN;
  font-weight: bold;
  color: #f82c1a;
}

.tit3 {
  font-size: 26rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #999999;
}

.tit4 {
  font-size: 28rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #333333;
}

.tit5 {
  font-size: 24rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #999999;
}

.footer_f {
  position: fixed;
  bottom: 80px;
  width: 100%;
  z-index: 1;
  box-shadow: 0px -2px 20px 0px rgba(204, 204, 204, 0.5);
}

.footer {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 24rpx;
  background: #fff;
  .footer_l {
    display: flex;
    align-items: center;
    .footer_ll {
      position: relative;
      display: flex;
      align-items: center;
      .pop {
        position: absolute;
        top: -16rpx;
        right: -16rpx;
        width: 28rpx;
        height: 28rpx;
        line-height: 28rpx;
        background: #005bac;
        box-shadow: 0rpx 3rpx 7rpx 0rpx rgba(0, 0, 0, 0.25);
        border-radius: 50%;
        text-align: center;
        font-size: 22rpx;
        font-family: Arial;
        font-weight: bold;
        color: #f1f2f7;
      }
    }
  }
  .footer_lr {
    margin-left: 20rpx; // display: flex;
    // align-items: center;
  }
  .footer_r {
    // flex: 1;
    display: flex;
    align-items: center;
    font-size: 20rpx;
    font-weight: 500;
    color: #333333;
  }
}

.disFlex {
  display: flex;
  align-items: center;
}

.h1 {
  font-size: 10px;
  font-family:
    PingFang SC-Medium,
    PingFang SC;
  font-weight: 500;
  color: #333333;
  margin-right: 20rpx;
}

.r1 {
  font-size: 36rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #f82c1a;
  margin-right: 20rpx;
}

.l1 {
  font-size: 24rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #333333;
  margin-right: 20rpx;
}

.uBtn {
  padding: 20rpx 70rpx;
}

.zhan {
  height: 240rpx;
}

.deldel {
  color: #005bac;
  margin-left: 20rpx;
}

.sel {
  position: relative;
}

.kong_t {
  text-align: center;
  padding-top: 60%;
}

.kong {
  width: 576rpx;
  height: 406rpx;
}
::v-deep .pp .u-popup__content {
  width: 80%;
  height: 60%;
  overflow-y: auto;
}
.popList {
  padding-top: 40rpx;
}
.popList_i {
  display: flex;
  align-items: center;
  padding: 0rpx 40rpx 0rpx 20rpx;
  margin-bottom: 40rpx;
  .popList_ii {
    display: flex;
    align-items: center;
  }
  img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8px;
    margin-right: 20rpx;
  }
}
.popBtm {
  position: sticky;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  box-shadow: 0px 2px 20px 0px rgba(204, 204, 204, 1);
  padding: 20rpx 40rpx;
  font-size: 14px;
  .que {
    background: #e03030;
    border-radius: 20px;
    color: #fff;
    text-align: center;
    padding: 10rpx 20rpx;
  }
}
</style>
