<template>
  <div class="s-page">
    <el-page-header @back="goBack" content="续费"></el-page-header>
    <el-divider></el-divider>
    <el-card class="goods">
      <div class="tishi">请选择需要购买的套餐并用微信扫码支付！</div>
      <div class="flex">
        <div
          class="item"
          v-for="(item, index) in goodsList"
          :key="index"
          @click="
            goodsIndex = index
            goodsId = item.id
          "
        >
          <div class="tj" v-if="item.isFirst == 1">推荐</div>
          <div class="year">{{ item.normName }}</div>
          <div class="new">
            <template v-if="item.id != '000'">
              <span style="font-size: 20px">￥</span>{{ (item.normAmount * 100 - item.discountAmount * 100) / 100 }}
            </template>
            <template v-else>
              <span style="font-size: 20px">￥</span
              >{{
                goodsId != '000'
                  ? 0
                  : serviceProductList
                      .filter(item => !!~formgengduode.serviceProductList.indexOf(item.dictCode))
                      .map(item => item.price)
                      .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * formgengduode.year
              }}
            </template>
          </div>
          <div v-if="item.id != '000'" class="old">￥{{ item.normAmount }}</div>
          <div :class="goodsIndex == index ? 'bottom active' : 'bottom'">立省￥{{ item.discountAmount }}</div>
        </div>
      </div>
      <div style="margin: 20px 0">
        <el-form ref="form" :model="formgengduode" label-width="160px">
          <el-form-item
            label="选择需要购买模块"
            style="text-align: left"
            prop="serviceProductList"
            :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          >
            <el-checkbox-group v-model="formgengduode.serviceProductList">
              <el-checkbox
                :disabled="goodsId != '000'"
                v-for="(item, index) in serviceProductList"
                :key="index"
                :label="item.dictCode"
                name="type"
                >{{ item.dictValue }}（￥{{ item.price }}）</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            label="选择需要购买年限"
            style="text-align: left"
            prop="year"
            :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          >
            <el-input-number
              size="mini"
              style="width: 200px"
              v-model="formgengduode.year"
              :min="1"
              :max="100"
              label="描述文字"
              :disabled="goodsId != '000'"
            ></el-input-number
            ><span style="font-size: 16px; margin-left: 10px">年</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex" style="justify-content: flex-start">
        <el-button style="margin-top: 30px" type="success" @click="confirmPay()">微信支付</el-button>
      </div>
    </el-card>
    <el-dialog
      title="确认支付"
      :visible.sync="is_pay"
      width="50%"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="close"
    >
      <div class="pay" v-if="!isPaySuccess && goodsList[goodsIndex]">
        <div style="font-weight: bold; font-size: 22px">扫码支付</div>
        <div class="ewm" ref="payQRCode" />
        <div>
          <div class="flex" style="align-items: center">
            <div>
              <template v-if="goodsId != '000'">
                实付:<span style="font-size: 20px; color: #ff6804">￥</span
                ><span style="font-size: 36px; color: #ff6804; font-weight: bold">{{
                  (goodsList[goodsIndex].normAmount * 100 - goodsList[goodsIndex].discountAmount * 100) / 100
                }}</span>
              </template>
              <template v-else>
                实付:<span style="font-size: 20px; color: #ff6804">￥</span
                ><span style="font-size: 36px; color: #ff6804; font-weight: bold">{{
                  serviceProductList
                    .filter(item => !!~formgengduode.serviceProductList.indexOf(item.dictCode))
                    .map(item => item.price)
                    .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * formgengduode.year
                }}</span>
              </template>
            </div>
            <div v-if="goodsId != '000'" style="margin: 0 20px">
              已优惠: <span style="font-size: 18px; color: #ff6804">￥</span
              ><span style="font-size: 20px; color: #ff6804">{{ goodsList[goodsIndex].discountAmount }}</span>
            </div>
            <el-tooltip effect="dark" placement="right-start">
              <div slot="content">
                购买年限越大越优惠，优惠价格按年份增加折扣，第1年<br />
                8.8折，第2年8折，第3年7折，第4年6折，第5年5折。<br />
                举例: 原价1000元/年，张三购买了3年限套餐，所需支付<br />
                价格为: 第1年880.00元+第2年800.00元+第三年700.00元，<br />
                需支付金额: 2380.00元
              </div>
              <i class="el-icon-question icon-question"></i>
            </el-tooltip>
          </div>
          <div style="display: flex; align-items: center; justify-content: center; margin-top: 20px">
            <img style="width: 30px; height: 30px" src="@/assets/common/weixin.png" alt="" />
            <span>请使用微信扫码支付</span>
          </div>
        </div>
      </div>
      <div class="pay" v-else-if="goodsList[goodsIndex]">
        <img style="width: 60px; height: 60px" src="@/assets/common/weixin.png" alt="" />
        <div style="font-weight: bold; font-size: 22px; margin: 20px 0">支付成功</div>
        <div class="flex" style="align-items: center">
          <div style="font-size: 16px">
            <template v-if="goodsId != '000'">
              支付金额: <span style="font-size: 20px; color: #ff6804">￥</span
              ><span style="font-size: 36px; color: #ff6804; font-weight: bold">{{
                (goodsList[goodsIndex].normAmount * 100 - goodsList[goodsIndex].discountAmount * 100) / 100
              }}</span>
            </template>
            <template v-else>
              支付金额: <span style="font-size: 20px; color: #ff6804">￥</span
              ><span style="font-size: 36px; color: #ff6804; font-weight: bold">{{
                serviceProductList
                  .filter(item => !!~formgengduode.serviceProductList.indexOf(item.dictCode))
                  .map(item => item.price)
                  .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * formgengduode.year
              }}</span>
            </template>
          </div>
        </div>
        <div style="margin: 50px 0; font-size: 18px">
          您的账号已续费成功，最新到期时间为：<span style="color: #169dff">{{ userInfo.companyExpireTime }}</span>
        </div>
        <div style="display: flex; justify-content: center">
          <el-button size="small" type="primary" @click="goBack">知道了</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserInfo } from '@/api/setting'
import QRCode from 'qrcodejs2'
import request from '@/utils/request'
import { serviceProductList } from '@/api/serviceProductConfig.js'
export default {
  data() {
    return {
      userInfo: {},
      goodsList: [],
      goodsId: '',
      goodsIndex: 0,
      timer: '',
      is_pay: false,
      is_submit: true,
      isPaySuccess: false,
      formgengduode: {
        year: 1,
        serviceProductList: []
      },
      serviceProductList: []
    }
  },
  computed: {
    ...mapGetters(['userid'])
  },
  watch: {
    goodsId() {
      if (this.goodsId == '000') {
        this.formgengduode.serviceProductList = []
      } else {
        this.formgengduode.serviceProductList = this.serviceProductList.map(item => item.dictCode)
      }
      this.formgengduode.year = this.goodsList.find(item => item.id === this.goodsId)?.year || 0
    }
  },

  created() {
    serviceProductList({
      pageNum: 1,
      pageSize: -1,
      params: [{ param: 'a.status', compare: '=', value: 'true' }]
    }).then(res => {
      this.getUserInfo()
      this.getBuyList()
      this.serviceProductList = res.data.records
    })
  },
  destroyed() {
    this.clear()
  },
  methods: {
    // 返回
    goBack() {
      this.is_pay = false
      this.clear()
      this.$emit('back')
    },
    close() {
      this.clear()
    },
    getUserInfo() {
      getUserInfo({ adminUserId: this.userid }).then(res => {
        this.userInfo = res.data
      })
    },
    getBuyList() {
      request({
        url: `/buy/service/config/list`,
        method: 'post',
        data: {}
      })
        .then(res => {
          this.goodsList = [
            ...res.data,
            {
              discountAmount: 0,
              id: '000',
              isFirst: 0,
              month: 0,
              normAmount: 0,
              normName: '自定义',
              remark: '',
              year: 1
            }
          ]
          this.goodsId = res.data[0].id
        })
        .catch(erro => {})
    },
    confirmPay() {
      if (!this.is_submit) {
        return false
      }
      this.is_submit = false
      setTimeout(() => {
        this.is_submit = true
      }, 3000)
      this.getCode()
    },
    checkPay(payId) {
      this.timer = setInterval(() => {
        request({
          url: `/buy/service/query/pay/code`,
          method: 'post',
          params: {
            companyName: this.userInfo.companyName,
            payId
          }
        })
          .then(res => {
            if (res.data == true) {
              this.getUserInfo()
              this.$refs.payQRCode.innerHTML = ''
              this.isPaySuccess = true
              this.clear()
            }
          })
          .catch(erro => {})
      }, 3000)
    },
    clear() {
      clearInterval(this.timer)
    },
    funcsss() {
      request({
        url: `/buy/service/generate/pay/code`,
        method: 'post',
        data: {
          id: this.userInfo.buyCompanyInfo,
          ...(() => {
            if (this.goodsId == '000') {
              return {
                year: this.formgengduode.year,
                serviceProductList: this.formgengduode.serviceProductList
              }
            } else {
              return {
                normId: this.goodsId
              }
            }
          })()
        }
      })
        .then(res => {
          if (res.code == 200) {
            this.$refs.payQRCode.innerHTML = ''
            this.$nextTick(() => {
              new QRCode(this.$refs.payQRCode, {
                text: res.data.codeUrl,
                width: 200,
                height: 200,
                colorDark: '#333333', // 二维码颜色
                colorLight: '#ffffff', // 二维码背景色
                correctLevel: QRCode.CorrectLevel.L // 容错率，L/M/H
              })
              this.checkPay(res.data.id)
            })
          }
        })
        .catch(erro => {})
    },
    getCode() {
      if (this.goodsId == '000') {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.funcsss()
            this.is_pay = true
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.funcsss()
        this.is_pay = true
      }
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
.s-page {
  padding: 20px;
  background-color: #ffffff;
}
.tishi {
  height: 40px;
  padding-left: 40px;
  background-color: #eeeeee;
  text-align: left;
  font-weight: bold;
  line-height: 40px;
  margin-bottom: 50px;
}
.flex {
  display: flex;
}
.goods {
  box-sizing: border-box;
  text-align: center;
  .item {
    width: 200px;
    height: 200px;
    margin-right: 20px;
    background-color: #eeeeee;
    position: relative;
    padding-top: 40px;
    box-sizing: border-box;
    font-weight: bold;
    border-radius: 10px;
    border: 1px solid #dddddd;
    cursor: pointer;
    .year {
      font-size: 20px;
      color: #999999;
    }
    .new {
      font-size: 36px;
      color: #ff6804;
    }
    .old {
      font-size: 16px;
      color: #999999;
      text-decoration: line-through;
    }
    .bottom {
      width: 100%;
      padding: 10px 0;
      color: #b4916d;
      background-color: #e6e6e6;
      position: absolute;
      bottom: 0;
      left: 0;
    }
    .tj {
      padding: 6px 20px;
      position: absolute;
      top: 0;
      left: 0;
      font-size: 20px;
      font-weight: 500;
      color: #ffffff;
      border-radius: 0 0 26px 0;
      background-color: #ff554e;
    }
    .active {
      color: #ffffff;
      background-color: #ff953d;
    }
  }
  .ewm {
    width: 200px;
    height: 200px;
  }
  .icon-question {
    font-size: 20px;
    // color: #189dff;
  }
}
.pay {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  .ewm {
    margin: 30px 0;
  }
}
</style>
