<template>
  <div>
    <el-card shadow="never">
<!--      <el-row :gutter="20" class="algin-items-stretch d-flex height-400">-->
<!--        <el-col :span="6" :offset="6">-->
<!--          <el-card shadow="always" class="height-percentage-100">-->
<!--            <div class="color-333 font-size-14 mb-3">短信余额</div>-->
<!--            <div class="text-center mb-3">-->
<!--              <span class="color-e94848 font-size-32 font-weight-600">{{infoData.balance?(infoData.balance/10):0}}</span>-->
<!--              <span class="color-666 font-size-16 font-weight-600">条</span>-->
<!--            </div>-->
<!--            <div class="text-center">-->
<!--              <el-button type="primary" size="small" class="width-percentage-50" round block @click="rechargeMethods">充值-->
<!--              </el-button>-->
<!--            </div>-->
<!--          </el-card>-->
<!--        </el-col>-->
        <!-- <el-col :span="6">
          <el-card shadow="always" class="height-percentage-100">
            <Echart :options="cdata" id="centreLeft1Chart" height="9vw" width="90%"></Echart>
          </el-card>
        </el-col> -->
<!--      </el-row>-->
      <el-row :gutter="20" class="">
        <el-table :data="tableData" style="width: 100%;" :header-row-style="{textAlign:'center'}" :height="documentHeight" align="center" >
          <el-table-column prop="createTime" label="日期">
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号">
          </el-table-column>
          <el-table-column prop="totalFee" label="金额">
          </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              <span>{{scope.row.orderType==0?'短信充值':scope.row.orderType==1?'交租':scope.row.orderType==2?'语音电话费用充值':scope.row.orderType==3?'系统续费':'未知'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付方式">
            <template slot-scope="scope">
              <span>{{scope.row.payType==0?'微信支付':scope.row.payType==1?'支付宝支付':scope.row.payType==2?'现金支付':scope.row.payType==3?'银联支付':scope.row.payType==4?'积分支付':'未知'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="状态">
            <template slot-scope="scope">
              <span>{{scope.row.orderStatus==0?'支付成功':scope.row.orderStatus==1?'转入退款':scope.row.orderStatus==2?'未支付':scope.row.orderStatus==3?'已关闭':scope.row.orderStatus==4?'已撤销（付款码支付）':scope.row.orderStatus==5?'用户支付中（付款码支付）':scope.row.orderStatus==6?'支付失败(其他原因，如银行返回失败)':'支付失败'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="describe" label="操作人">
            <template slot-scope="scope">
              <span>{{scope.row.expand?scope.row.expand.nickname:''}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="describe" label="备注">
          </el-table-column>
          <el-table-column label="操作" v-if="info.type === 0">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="drawback(scope.row.orderNo)" v-if="scope.row.orderStatus==0" style="background: #FA8E00; border: none;">退款</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="text-right mt-2 d-flex flex-wrap justify-space-between">
          <div class="d-inlie-block">
            <div class="d-inlie-block">短信余额：<span class="color-e94848 font-size-24 font-weight-600">{{infoData.balance?(infoData.balance/10):0}}</span><span class="color-666 font-size-14 font-weight-600">条</span></div>
            <el-button type="primary" size="small" @click="drawerPay=true" style="background: #FA8E00; border: none;">充值结算</el-button>
          </div>
          <div class="d-inlie-block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[20,100, 200, 300, 400]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal">
          </el-pagination>
          </div>
        </div>
      </el-row>
    </el-card>
    <el-drawer
      title="充值结算"
      :visible.sync="drawerPay"
      direction="rtl" size="90%"
      :before-close="handleClose" class="position-relative">
      <el-card shadow="never" style="border:none;" :body-style="{border:'none'}">
        <div>
          <el-radio v-model="drawRadio" label="1" border>短信充值</el-radio>
          <el-radio v-model="drawRadio" label="2" border>线下交租</el-radio>
        </div>
        <div class="mt-2" v-if="drawRadio == 1">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="短信数量">
              <el-input v-model="form.payValue" type="number" @input="payTotalMethods"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.remark"></el-input>
            </el-form-item>
            <el-form-item label="账单金额">
              <el-link type="danger" disabled>{{form.total}}</el-link>
            </el-form-item>
            <el-form-item label="扫码支付">
              <div class="text-center" v-if="qrcodeStatus">
                <qriously :value="codeUrl" :size="150" />
                <div class="remark text-center">使用微信扫码支付</div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="mt-2" v-else>
          <el-table
            ref="multipleTable"
            :data="tableDataLease"
            tooltip-effect="dark"
            style="width: 100%" height="500px"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="number" label="合同编号" align="center"></el-table-column>
            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="phone" label="电话" align="center"></el-table-column>
            <el-table-column prop="sex" label="性别" align="center">
              <template #default="scope">
                {{scope.row.sex === 1?'男':scope.row.sex === 2?'女':'' }}
              </template>
            </el-table-column>
            <el-table-column prop="address" label="房间" align="center"></el-table-column>
            <el-table-column label="租期" align="center">
              <template #default="scope">
                {{scope.row.signingTime }}<br/> 至 <br/>{{ scope.row.contractTime }}
              </template>
            </el-table-column>
            <el-table-column prop="monthRent" label="租金/¥" align="center"></el-table-column>
            <el-table-column label="合约状态" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status===0?'':scope.row.status===1?'success':scope.row.status===2?'danger':scope.row.status===3?'warning':scope.row.status===4?'info':''">
                  {{ scope.row.status===0?'待签约':scope.row.status===1?'已签约':scope.row.status===2?'已欠费':scope.row.status===3?'已退租':scope.row.status===4?'已删除':scope.row.status===5?'已到期':'未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建日期" align="center"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
          <div class="mt-2 font-size-16 color-666">
            <el-form ref="form" :model="form" label-width="100px">
              <el-form-item label="支付方式：">
                <el-select v-model="form.payType" size="small" placeholder="请选择支付方式" class="d-inlie-block">
                  <el-option
                    v-for="item in payOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="总数：">
                {{LeasePageTotal}} 条
              </el-form-item>
              <el-form-item label="选择合计：">
                <span class="font-size-20 color-e94848 font-weight-600">¥ {{multipleSelectionTotal}}</span>（{{multipleSelection.length}}笔）
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
      <div class="text-right box-sizing-border-box pa-2  width-percentage-100">
        <el-button size="small" @click="drawerPay = false">取消</el-button>
        <el-button size="small" type="primary" @click="getRadioLable">结算</el-button>
      </div>
    </el-drawer>
    <!-- 微信支付二维码 -->
<!--    <el-dialog :visible.sync="codeDialogVisible" :show-close="false" @close="closeDialog" width="40%" center>-->
<!--      <el-form ref="form" :model="form" label-width="80px">-->
<!--        <el-form-item label="短信数量">-->
<!--          <el-input size="small" class="mb-2" v-model="form.payValue" type="number" placeholder="请输入充值短信条数">-->
<!--            <el-button slot="append"  @click.stop="getRadioLable">确认</el-button>-->
<!--          </el-input>-->
<!--        </el-form-item>-->
<!--&lt;!&ndash;        <el-button size="small" type="primary" @click="getRadioLable">确认</el-button>&ndash;&gt;-->
<!--      </el-form>-->
<!--      <div class="text-center" v-if="qrcodeStatus">-->
<!--        <qriously :value="codeUrl" :size="150" />-->
<!--        <div class="remark text-center">使用微信扫码支付</div>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
  import {
    httpPost,
    httpGet
  } from "../../api/index.js";
  import Echart from "@/common/echart";
  import moment from 'moment'
  import utils from "../../utils/util";
  export default {
    name: "contrast",
    data() {
      return {
        payOptions: [
          {label: '现金', value: 1},
          {label: '刷卡', value: 2},
          {label: '支付宝', value: 3},
          {label: '微信', value: 4}
        ],
        multipleSelection:[],
        multipleSelectionTotal:0,
        tableDataLease:[],
        LeasePageTotal:0,
        form:{
          payValue:1,
          total:0,
          remark:' ',
          payType:1,
        },
        drawRadio:'1',
        drawerPay:false,
        qrcodeStatus:false,
        pageNum: 1,
        pageSize: 20,
        radio3: '1',
        tableData: [],
        pageTotal:0,
        payValue: 0,
        codeDialogVisible: false, //微信支付二维码弹窗
        codeUrl: '', // 二维码
        cdata: {
          title: {
            text: '交易统计',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [{
            name: '交易统计',
            type: 'pie',
            radius: '70%',
            data: [{
                value: 1048,
                name: '消费'
              },
              {
                value: 735,
                name: '充值'
              }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        },
        info: {
          balance: 0
        },
        infoData: {
          balance: 0
        },
        documentHeight:0,
      }
    },
    components: {
      Echart
    },
    created() {
      this.info = JSON.parse(localStorage.getItem('info'))
      this.getOrderList()
      this.payTotalMethods()
      this.getLeasesList()
      this.documentHeight = document.documentElement.clientHeight - 200
    },
    mounted() {
      this.getUserlist()
    },
    methods: {
      // 获取合同列表
      getLeasesList(){
        let QData = utils.validObject({
          status: 2,
        })
        let data={
          pageNum:0,
          pageSize:0,
          orderBy: "create_time desc",
          q:JSON.stringify(QData)
        }
        if(data.q == '{}'){
          delete data.q
        }
        httpPost(data,this.$api.postLeasesList).then(res=>{
          if(res.success){
            res.data.list.map(li=>{
              li.signingTime = moment(li.signingTime).format('YYYY-MM-DD HH:mm:ss')
              li.contractTime = moment(li.contractTime).format('YYYY-MM-DD HH:mm:ss')
              li.createTime = moment(li.createTime).format('YYYY-MM-DD HH:mm:ss')
            })
            this.tableDataLease = res.data.list
            this.LeasePageTotal = res.data.total
          }else{
            this.$message.error(res.message)
          }
        })
      },
      // 多选
      handleSelectionChange(val) {
        this.multipleSelection = val;
        let multipleSelectionTotal = 0
        val.map(li=>{
          multipleSelectionTotal+=parseInt(li.monthRent)
        })
        this.multipleSelectionTotal = parseFloat(multipleSelectionTotal).toFixed(2)
      },
      // 计算充值短信金额
      payTotalMethods(){
        if(this.form.payValue == ''){
          this.$message.error('数量不能为0')
          this.form.payValue = 1
          return
        }
        this.form.total = parseInt(this.form.payValue)/10
      },
      // 隐藏充值界面
      handleClose(){
        this.drawerPay = false
      },
      // 退款
      drawback(no){
        let url = `/v1/pay/refunds/${no}/退款`
        httpGet('',url).then(res=>{
          if(res.data.success){
            this.$message.success('退款成功')
            this.getUserlist()
            this.getOrderList()
          }else{
            this.$message.error(res.data.msg)
          }
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.getOrderList()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.getOrderList()
      },
      getUserlist() {
        httpGet('', this.$api.getBalance).then(res => {
          if (res.code == 200) {
            this.infoData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
      },
      getOrderList() {
        let data = {
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          orderBy: "create_time desc"
        }
        httpGet(data, this.$api.getOrderList).then(res => {
          if (res.code == 200) {
            res.data.list.map(li => {
              li.totalFee = (li.totalFee / 100).toFixed(2)
              li.createTime = moment(li.createTime).format('YYYY-MM-DD HH:mm:ss')
              li.expand = JSON.parse(li.expand)
            })
            this.tableData = res.data.list
            this.pageTotal = res.data.total
          } else {
            this.$message.error(res.message)
          }
        })
      },
      getRadioLable() {
        this.goPay()
      },
      closeDialog() {
        this.codeDialogVisible = false
        this.getOrderList()
        this.getUserlist()
      },
      goPay() {
        let info = JSON.parse(localStorage.getItem('info'))
        if(this.drawRadio == 1){
          let data = {
            description: this.form.remark,
            productName: this.drawRadio==1?"短信服务":'交租',
            total: parseInt(this.form.payValue)*10,
            userId: info.id,
            cardId:info.id,
            orderType:this.drawRadio==1?0:1,
            payType:0,
            expand:JSON.stringify({
              phone:info.phone,
              nickname:info.username
            })
          }
          console.log(data)
          httpPost(data, this.$api.createOrder).then(res => {
            console.log(res)
            if (res.success) {
              this.codeUrl = res.data.code_url
              this.qrcodeStatus = true
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }else if(this.drawRadio == 2){
          this.multipleSelection.map(li=>{
            let data = {
                description: "交租",
                productName: "交租",
                total: parseInt(li.monthRent)*100,//parseInt(this.data.leases.expand.rent)*100,
                userId: li.cardId,
                cardId:li.cardId,
                appid:'wx20de9fe5943934a1',
                uid:info.id,
                eid:info.enterpriseId,
                orderType:1,
                payType:this.form.payType,
                expand:JSON.stringify({
                  phone:li.phone,
                  nickname:li.name
                })
            }
            console.log(this.$api.rentPrepayOrder);
            httpPost(data, this.$api.rentPrepayOrder).then(res=>{
              if(res.success){
                this.$message.success('结算成功')
                this.getLeasesList()
              }else{
                this.$message.error(`结算失败：${res.message}`)
              }
            })
          })
        }
      },
      rechargeMethods() {
        this.codeDialogVisible = true
      }
    }
  }
</script>

<style scoped>

</style>