<template>
  <view class="container">
    <view class="item-pay">
      <view class="item-pay-con">
        <view class="item-pay-con-ti">选择支付方式</view>
        <button class="item-pay-con-bu" :class="{'item-pay-con-bu-show': payType === items.value}" v-for="items in payTypeArr" @click="changePayType(items.value)">{{items.title}}</button>
      </view>

      <view class="item-pay-con">
        <view class="item-pay-con-ti">
          标的清单
        </view>
        <view class="item-pay-con-tab">
          <uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据">
            <uni-tr>
              <uni-th width="140" align="center">缩略图</uni-th>
              <uni-th align="center">标的名称</uni-th>
              <uni-th align="center">委托关联编码</uni-th>
              <uni-th align="center">付费类型</uni-th>
              <uni-th align="center">交易方式</uni-th>
              <uni-th align="center">委托方</uni-th>
              <uni-th align="center">单价</uni-th>
              <uni-th align="center">购买年限</uni-th>
              <uni-th align="center">小计</uni-th>
              <uni-th align="center">交易佣金</uni-th>
              <uni-th align="center">合计</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in order_detail_list" :key="index">
              <uni-td align="center">
                <image v-if="item.goods_image" class="td-image" :src="item.goods_image"></image>
                <image v-else-if="img" class="td-image" :src="img"></image>
              </uni-td>
              <uni-td align="center">{{ item.goods_name }}</uni-td>
              <uni-td align="center">{{ item.goods_islicode }}</uni-td>
              <uni-td align="center">{{ item.price > 0 ? '付费' : '免费'}}</uni-td>
              <uni-td align="center">{{ item.goods_entrust_str }}</uni-td>
              <uni-td align="center">{{ item.entrust_name }}</uni-td>
              <uni-td align="center">{{ item.price_str }}</uni-td>
              <uni-td align="center">{{ item.transaction_count_str }}</uni-td>
              <uni-td align="center">{{ item.small_count }}</uni-td>
              <uni-td align="center">￥{{ item.service_charge }}</uni-td>
              <uni-td align="center">{{ item.money_str }}</uni-td>
            </uni-tr>
          </uni-table>
          <view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="change" /></view>
        </view>
      </view>

      <view class="privacy">
        <checkbox :checked="isTick" color="#4399ff" class="ckbox" @click="readpri"></checkbox>
        <view class="privacy_view">
          我已阅读并同意 <text class="atxt" @click="gotopage('purchase')">《文化数据交易协议》</text>
        </view>
      </view>
    </view>


    <!-- 协议弹框 -->
    <whpop v-model="showPopup" :maskCloseAble="true" :mkey="murl"></whpop>

    <view class="item-pay">
      <image class="item-pay-img" v-if="is_show_img" :src="pay_image"></image>
      <text class="item-pay-prompt" v-if="is_show_img">
        温馨提示 请使用 网银、支付宝 App扫码支付
      </text>
      <text class="item-pay-res res-success" v-if="payResult == 1">支付成功！</text>
      <text class="item-pay-res res-error" v-if="payResult == 2">支付失败！</text>
      <button class="item-pay-go" v-if="goBuyOrder" @click="goToBuyOrder">进入买入订单</button>
      <button :class="isDisabled ? 'item-pay-sub2' : 'item-pay-sub'" :disabled="isDisabled" @click="handlerPay">确认支付</button>
    </view>
  </view>
</template>

<script>

import * as GoodsApi from '@/api/goods'
import * as VerifyApi from '@/api/verify'
import uniTable from "@/uni_modules/uni-table/components/uni-table/uni-table"
import uniTr from "@/uni_modules/uni-table/components/uni-tr/uni-tr"
import uniTh from "@/uni_modules/uni-table/components/uni-th/uni-th"
import uniTd from "@/uni_modules/uni-table/components/uni-td/uni-td"
import uniPagination from "@/uni_modules/uni-pagination/components/uni-pagination/uni-pagination"
import whpop from '../../login/components/WhPopup'

export default {
  name: "payment",
  components: {
    'uni-table': uniTable,
    'uni-tr': uniTr,
    'uni-th': uniTh,
    'uni-td': uniTd,
    'uni-pagination': uniPagination,
    'whpop': whpop,
  },
  data () {
    return {
      tableList: [],
      payTypeArr: [
        {
          title: '网银支付',
          value: 15
        },{
          title: '支付宝',
          value: 12
        },
      ],
      payType: 15,
      loading: false,
      selectedIndexs: [],
      pageSize: 10, // 每页数据量
      pageCurrent: 1, // 当前页
      total: 0, // 数据总量
      good_money: 0, // 交易金额
      isDisabled: false, // 按钮禁用
      is_show_img: false, // 显示图片
      pay_image: '', // 显示图片
      batchcode: '', // 订单编号
      isTick: false, // 隐私政策
      showPopup: false, // 协议展示
      murl: '', // 协议标识
      dateS: 180, // 3分钟
      quantitySaleDate: [],// 统计数据超市销售量
      Client_date: {
        entrustingPartyName: [],//委托方名称
        identityCode: [],//身份认证编码
        entrustSignNumber: 0,//委托标的数
        orderNumber: 1//订单总数
      },
      marketislicode: '',
      payResult: 0, // 支付结果提示
      goBuyOrder: false, // 是否显示跳转到订单页面按钮
      img: '', // 默认支付订单图
      order_detail_list: [], // 默认支付订单图
    }
  },
  watch: {
    dateS: function (newValue, oldValue) {
      if (newValue === 0) {
        this.$error('由于长时间未支付，即将进入买入订单！')
        setTimeout(function () {
          uni.navigateTo({
            url:'/pages/user/order/buyOrder'
          })
        },3000)
      }
    }
  },
  onLoad(options) {
    this.selectedIndexs = []
    this.batchcode = options.batchcode
    this.img = options.img
    this.getTableList()
  },
  methods: {
    // 切换支付类型
    changePayType(val) {
      this.payType = val
    },
    // 分页触发
    change(e) {
      this.$refs.table.clearSelection()
      this.selectedIndexs.length = 0
      this.getData(e.current)
    },
    // 隐私政策勾选
    readpri() {
      this.isTick = true;
    },
    // 阅读注册协议和隐私
    gotopage(str){
      this.murl = str
      this.showPopup = ! this.showPopup
    },
    // 获取订单列表
    getTableList(pageNo = 1) {
      const app = this
      let param = {
        user_isli : uni.getStorageSync("isliCode"),
        user_role : 1,
        batchcode : app.batchcode
      }
      return new Promise((resolve, reject) => {
        GoodsApi.orderPaymentList(param).then(res => {
          if (res.resultCode === "00000000" && res.data.length > 0) {
            app.loading = false
            app.tableList = res.data
            app.good_money = res.data[0].total_money
            app.order_detail_list = app.tableList[0].order_detail
            app.handlerTableList()
            app.quantitySale(app.tableList[0].order_detail)
          } else {
            app.$error(res.errMsg);
          }
          resolve()
        }).catch(reject)
      })
    },
    // 处理table数据
    handlerTableList() {
      const app = this
      app.order_detail_list.map(items => {
        if (items.goods_entrust == 1) {
          items.goods_entrust_str = "转让"
        } else if (items.goods_entrust == 2) {
          items.goods_entrust_str = "授权"
        }
        items.price_str = app.handlerPrice(items.price)
        if (items.transaction_count == "-" && items.goods_entrust == "1") {
          items.transaction_count_str = "永久"
        } else if (items.price == 0) {
          items.transaction_count_str = "永久"
        } else {
          items.transaction_count_str = items.transaction_count + '年'
        }

        items.small_count = ''
        if (items.goods_entrust == "2" && Number(items.price) > 0) {
          let total = Math.floor(parseFloat(items.price * 100 * items.transaction_count)) / 100;
          items.small_count = app.handlerPrice(total)
        } else {
          items.small_count = app.handlerPrice(items.price)
        }

        items.money_str = app.handlerPrice(items.money)
      })

      if (this.tableList[0].total_money > 20000) {
        // 禁用支付按钮
        app.isDisabled = true
      }
    },
    //计算销售量
    quantitySale(orderDate) {
      const app = this
      orderDate.forEach(function (item) {
        if (Number(item.price) > 0) {
          if (item.goods_entrust == 2) {
            app.quantitySaleDate.push({
              chargesType: 2,//1-免费 2-付费
              clickCount: 0,//点击量
              contractualPeriod: item.contractual_period,//1-永久性委托 3-阶段性委托 2-一次性委托
              countType: 2,//统计类型 1-点击量 2-销售量
              goodsEntrust: item.goods_entrust,//交易方式；1-转让；2-授权
              goodsIsliCode: item.goods_islicode,//标的isli标识
              goodsName: item.goods_name,//标的名称
              goodsOwnershipStr: item.goods_ownership_str,//权益
              goodsType: item.goods_type,//1-文化资源数据 2-文化数字内容
              salesVolume: 1 //销售量
            });
          }
        }
      });
    },
    // 处理金额显示角分
    handlerPrice(price) {
      let f = parseFloat(price);
      if (!isNaN(f)) {
        f = Math.round(price * 100) / 100;
        let s = f.toString();
        let rs = s.indexOf('.');
        if (rs < 0) {
          rs = s.length;
          s += '.';
        }
        while (s.length <= rs + 2) {
          s += '0';
        }
        return '￥' + s;
      }
      return '￥' + price
    },
    // 确认支付
    handlerPay () {
      const app = this
      if (app.isTick) {

        let Merchant_id = uni.getStorageSync("Merchant_id")
        let user_isli = uni.getStorageSync("isliCode")//用户isli

        let agreement = {
          agreementIds: "7",
          userId: uni.getStorageSync("cuser").cellPhone
        }
        // 保存协议
        VerifyApi.preservation(agreement);

        let paramArr = {
          marketislicode: [],
          manyName: [],
          shopname: [],
          shop_price: [],
          new_shop_Name: [],
        }
        //拼接标的名称
        let new_user_year = [];
        //计算年限
        let user_year = null;

        for (let i = 0; i < app.order_detail_list.length; i++) {

          let item = app.order_detail_list[i]

          //销售量参数
          paramArr.marketislicode.push(item.goods_islicode)
          //委托方名称
          app.Client_date.entrustingPartyName.push(item.entrust_name)
          //身份认证编码
          app.Client_date.identityCode.push(item.entrust_islicode)

          paramArr.manyName.push(item.goods_name)
          paramArr.shopname.push(item.entrust_islicode)
          paramArr.shop_price.push(item.price)

          if (item.transaction_count == "-") {
            item.transaction_count = 99;
            new_user_year.push(item.transaction_count);
          } else {
            new_user_year.push(item.transaction_count);
          }
          //拼接撤销数据的名称
          if (item.goods_status != "1" && item.goods_status != "5") {
            paramArr.new_shop_Name.push(item.goods_name)
          }
        }

        app.Client_date.entrustingPartyName = app.Client_date.entrustingPartyName.join(',')
        app.Client_date.identityCode = app.Client_date.identityCode.join(',')
        app.marketislicode = paramArr.marketislicode.join(',');
        let manyName = paramArr.manyName.join(',');
        let shopname = paramArr.shopname.join(',');
        let shop_price = paramArr.shop_price.join(',');
        let new_shop_Name = paramArr.new_shop_Name.join(',');

        new_user_year.forEach(function (item) {
          user_year += Number(item);
        });

        //计算交易金额
        let manyMony = 0;
        manyMony = (Number(app.good_money * 100)).toFixed(0);

        let newmanyName = manyName; //将标的名称拼接起来给新的

        if (manyName.length > 100) {
          manyName = manyName.split(",")[0];
        }

        let payment = {
          amount: manyMony, //交易金额
          app_id: Merchant_id, //发送请求的公司id
          body: manyName, //订单描述
          businesstype: 1001, //交易类型1001-销售收款，2001-消费付款
          ordernumber: app.batchcode, //订单号
          paymenttypeid: app.payType, //12支付宝，13微信 15 网银支付
          subpaymenttypeid: app.payType, //12支付宝，13微信 15 网银支付
          businesstime: app.getDayTimer(new Date()),
          buyer: user_isli, //客户(买方)  用户isli
          chargeuptype: 2, //收支类型1-收入2-支出,
          goodsname: newmanyName, //商品名称
          orderamount: manyMony, //订单金额(单位分)
          payorderid: app.batchcode, //交易流水号
          price: shop_price, //商品单价(单位分)
          seller: shopname, //商户(卖方)
          settlementamount: manyMony, //结算金额(分)
          settlementtype: 2, //结算方式:1-转账充值;2-内部转账
          totalqty: user_year, //商品数量
        }

        if (new_shop_Name == "") {

          // 禁用按钮
          app.isDisabled = true

          GoodsApi.userOrderpay(payment).then(res => {
            if (res.resultCode === "00000000") {

              if (app.payType != "15" && app.payType != "15") {

                app.is_show_img = true
                app.pay_image = res.data.qrcodeurl

                setInterval(app.handelRote,5000)
                app.countDown()
                app.isDisabled = false
              } else {

                app.isDisabled = false
                setInterval(app.handelRote,5000)
              }

            } else {
              app.$error(res.resultMsg);
            }
          })

        } else {
          app.$error(new_shop_Name + "无法购买")
        }

      } else {
        app.$error('请勾选《文化数据交易协议》')
      }
    },
    // 支付后操作
    handelRote() {
      const app = this
      let param = {
        user_isli : uni.getStorageSync("accountId"),
        user_role : 1,
        batchcode : app.batchcode
      }
      GoodsApi.orderPaymentList(param).then(res => {
        if (res.resultCode === "00000000" && res.data.length > 0) {
          app.loading = false
          app.tableList = res.data

          this.tableList.map(item => {
            let order_detail = item.order_detail[0]

            let status = order_detail.pay_status;
            if (status == 2) {
              GoodsApi.marketleader(app.quantitySaleDate);//计算销售量
              GoodsApi.addClient(app.Client_date);//计算销售量
              GoodsApi.addClickmarket(app.marketislicode);
              app.payResult = 1
              app.goBuyOrder = true
            } else if (status == 3) {
              app.payResult = 2
              app.goBuyOrder = true
            }
          })
        } else {
          app.$error(res.resultMsg);
        }
      })
    },
    goToBuyOrder () {
      uni.navigateTo({
        url:'/pages/user/order/buyOrder'
      })
    },
    // 倒计时
    countDown(){
      let app = this
      // console.log(qq)
      setTimeout(function(){
        if(app.dateS>1){
          app.dateS--
          app.countDown(app.dateS)
        }else{
          app.dateS=0
        }
      },1000)

    },
    //转换时间
    getDayTimer (data) {
      let date = new Date(data)
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let currentdate = y + '-' + m + '-' + d;
      let hh = date.getHours()
      hh = hh < 10 ? ('0' + hh) : hh
      let mm = date.getMinutes()
      mm = mm < 10 ? ('0' + mm) : mm
      let ss = date.getSeconds()
      ss = ss < 10 ? ('0' + ss) : ss
      let time = hh + ':' + mm + ':' + ss;
      return currentdate + " " + time
    },

  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;

  .item-pay {


    .item-pay-con {
      margin-top: 30rpx;
      padding-top: 30rpx;

      .item-pay-con-ti {
        height: 50rpx;
        margin-left: 20rpx;
        padding-left: 10px;
        border-left: #407ac4 10rpx solid;
        display: flex;
        align-items: center;
        text-align: center;
      }

      .item-pay-con-bu {
        width: 240rpx;
        margin-top: 30rpx;
        margin-left: 50rpx;
        border-radius: 15rpx;
        display: inline-block;
        border: #e5e5e5 1rpx solid;
        background-color: #e5e5e5;
      }
      .item-pay-con-bu-show {
        background-color: #defedc;
      }

      .item-pay-con-tab {
        margin-top: 20rpx;

        .td-image {
          width: 200rpx;
          height: 200rpx;
        }
      }
    }

    .item-pay-res {
      margin-left: calc(50% - 80rpx);
      font-size: 38rpx;
    }

    .res-success {
      color: green;
    }

    .res-error {
      color: red;
    }

    .item-pay-sub {
      color: #ffffff;
      margin-top: 200rpx;
      background-color: #407ac4;
    }

    .item-pay-sub2 {
      color: #ffffff;
      margin-top: 200rpx;
      background-color: #9F9F9F;
    }

    .item-pay-go {
      color: #ffffff;
      background-color: orange;
    }

    .item-pay-img {
      width: 200px;
      height: 200px;
      margin-top: 15%;
      margin-left: 25%;
      background-color: #eeeeee;
    }

    .item-pay-prompt {
      display: block;
      text-align: center;
      color: red;
    }
  }

  // 协议
  .privacy{
    display: flex;
    margin-top: 50rpx;
    margin-bottom: 50rpx;
    margin-left: 15rpx;

    .ckbox{
      border-radius: 50%;
    }

    .privacy_view {
      margin-left: 20rpx;
    }

    .atxt{
      color: #4399ff;
    }
  }
}
</style>