<template>
  <div class="app-container" v-loading="loading">
    <el-row :gutter="12">
      <el-col :span="18">

        <el-card class="box-card">
          <el-descriptions title="基本信息" :column="4">
            <template #extra>
              <el-button size="small" plain icon="el-icon-refresh" v-if="canRefresh(detail)" @click="refreshPayResult"> 刷新支付结果</el-button>
              <el-button size="small" plain type="success" icon="el-icon-s-promotion" v-if="canRechargeDevice(detail)" @click="rechargeDevice"> 手动设备充值</el-button>
              <el-button size="small" plain type="warning" icon="el-icon-bank-card" v-if="canRefund(detail)" @click="showRefund = true">退款</el-button>
              <el-button size="small" plain type="danger" icon="el-icon-close" v-if="canClose(detail)" @click="handleClose"> 结束订单</el-button>
            </template>

            <el-descriptions-item label="订单编号">{{detail.billNo | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{detail.createTime | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="交易状态">
              <dict-tag :value="detail.status" :options="dict.type.sm_transaction_bill_status" size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="交易金额">
              {{detail.money | money | defaultValue}} 元
              <template v-show="detail.refundAmount">（退款{{detail.refundAmount | money | defaultValue}} 元）</template>
            </el-descriptions-item>
            <el-descriptions-item label="渠道成本">{{detail.channelCost | money | defaultValue}} 元</el-descriptions-item>
<!--            <el-descriptions-item label="商户到账">-->
<!--              {{detail.arrivalAmount | money | defaultValue}} 元-->
<!--              <template v-show="detail.refundMchAmount">（退款{{detail.refundMchAmount | money | defaultValue}} 元）</template>-->
<!--            </el-descriptions-item>-->
<!--            <el-descriptions-item label="服务费">-->
<!--              {{detail.serviceCharge | money | defaultValue}} 元-->
<!--              <template v-show="detail.refundServiceAmount">（退款{{detail.refundServiceAmount | money | defaultValue}} 元）</template>-->
<!--            </el-descriptions-item>-->
<!--            <el-descriptions-item label="平台渠道成本">{{detail.channelCost | money | defaultValue}} 元</el-descriptions-item>-->
<!--            <el-descriptions-item label="平台利润">{{detail.serviceCharge - detail.channelCost | money | defaultValue}} 元</el-descriptions-item>-->
          </el-descriptions>
        </el-card>
        <el-card class="box-card">
          <el-descriptions title="设备信息" :column="4">
            <el-descriptions-item label="设备名称">
              <device-link :id="detail.deviceId" :text="detail.deviceName"/>
            </el-descriptions-item>
            <el-descriptions-item label="设备SN">
              <device-link :id="detail.deviceId" :text="detail.deviceNo"/>
            </el-descriptions-item>
            <el-descriptions-item label="MAC-1">
              <device-link :id="detail.deviceId" :text="detail.deviceMac"/>
            </el-descriptions-item>
            <el-descriptions-item label="MAC-2">
              <device-link :id="detail.deviceId" :text="detail.deviceMac2"/>
            </el-descriptions-item>
            <el-descriptions-item label="服务模式">
              <dict-tag :value="detail.deviceServiceMode" :options="dict.type.device_service_mode" size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="使用状态">
              <el-tag type="warning" v-if="detail.isUsing" size="small">使用中</el-tag>
              <el-tag type="success" v-else-if="detail.isFinished" size="small">已结束</el-tag>
              <el-tag type="info" v-else size="small">未开始</el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions :column="4" title="设备操作日志">
            <el-descriptions-item label="设备充值状态">
              <dict-tag :value="detail.deviceRechargeStatus"
                        :options="dict.type.sm_transaction_bill_device_recharge_status"
                        size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="充值状态描述" :span="3">
              {{detail.openMsg | defaultValue}}
            </el-descriptions-item>
            <template v-if="detail.isFinished">
              <el-descriptions-item label="设备关闭状态">
                <dict-tag :value="detail.closeStatus" :options="dict.type.recharge_close_status" size="small"/>
              </el-descriptions-item>
              <el-descriptions-item label="关闭状态描述" :span="3">
                {{detail.closeResult | defaultValue}}
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-card>

        <el-card class="box-card">
          <el-descriptions title="套餐信息" :column="4">
            <el-descriptions-item label="套餐名称">{{detail.suitName | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="计费模式">
              <dict-tag :value="detail.suitFeeMode" :options="dict.type.suit_fee_mode" size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="计费类型">
              <dict-tag :value="detail.suitFeeType" :options="dict.type.suit_fee_type" size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="套餐价格" >
              <template v-if="SuitFeeType.TIMING === detail.suitFeeType">
                {{detail.suitPrice | money}} 元 / {{detail.suitTime}} {{suitTimeUnit(detail.suitTimeUnit)}}
              </template>
              <template v-else-if="SuitFeeType.COUNT === detail.suitFeeType">
                {{detail.suitPrice | money}} 元 / {{detail.suitTime}} 度
              </template>
              <template v-else>
                <el-link type="primary" @click="showSuitTimePrice = true">点击查看</el-link>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="套餐押金" >{{detail.suitDeposit | money | defaultValue}} 元</el-descriptions-item>
            <el-descriptions-item label="使用时长" v-if="SuitFeeType.timeList().includes(detail.suitFeeType)">{{toDescriptionFromSecond(detail.totalUse).text | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{detail.suitStartTime | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{detail.suitEndTime | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="失效时间">{{detail.suitExpireTime | defaultValue}}</el-descriptions-item>
            <template v-if="SuitFeeType.eleList().includes(detail.suitFeeType)">
              <el-descriptions-item label="使用电量">{{detail.totalUse | defaultValue}} 度</el-descriptions-item>
              <el-descriptions-item label="开始电量">{{detail.suitStartEle | money | defaultValue}} 度</el-descriptions-item>
              <el-descriptions-item label="结束电量">{{detail.suitEndEle | money | defaultValue}} 度</el-descriptions-item>
            </template>
          </el-descriptions>
          <el-descriptions :column="4">
            <el-descriptions-item label="低功率自动关闭" :span="2" v-if="SuitFeeType.eleList().includes(detail.suitFeeType)">
              <template v-if="detail.suitEnableLowPowerClose">
                <span style="color: green;margin-right: 0.5em;">已开启<i class="el-icon-check"/></span>
                设备功率低于 {{detail.suitLowPower | money | defaultValue}} 瓦将自动关闭设备并结束订单
              </template>
              <template v-else>
                <span style="color: red">未启用<i class="el-icon-close"/></span>
              </template>
            </el-descriptions-item>

            <el-descriptions-item label="语音播报" :span="2" v-if="SuitFeeType.timeList().includes(detail.suitFeeType)">
              <template v-if="detail.suitEnabledVoid">
                <span style="color: green;margin-right: 0.5em;">已开启<i class="el-icon-check"/></span>
                设备时长低于 {{detail.suitVoidMinute | money | defaultValue}} 分钟将播放语音通知
              </template>
              <template v-else>
                <span style="color: red">未启用<i class="el-icon-close"/></span>
              </template>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <el-descriptions title="用户信息" :column="1">
            <el-descriptions-item label="用户名称">
              <user-link :id="detail.userId" :name="detail.userName"/>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              <dict-tag :value="detail.channelId" :options="dict.type.channel_type" size="small"/>
            </el-descriptions-item>
            <el-descriptions-item label="支付时间">{{detail.payTime | defaultValue}}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="box-card">
          <el-descriptions title="收款方信息" :column="1">
            <el-descriptions-item label="代理商" v-if="DeviceServiceMode.AGENT === detail.deviceServiceMode">
              <user-link :id="detail.agentId" :name="detail.agentMobile"/>
            </el-descriptions-item>
            <el-descriptions-item label="商户">
              <user-link :id="detail.mchId" :name="detail.mchName"/>
            </el-descriptions-item>
            <el-descriptions-item label="商户手机号">{{detail.mchMobile | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="店铺名称">{{detail.storeName | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="店铺地址">{{detail.storeAddress | defaultValue}}</el-descriptions-item>
            <el-descriptions-item label="商户查看手机号功能开启状态">
              <boolean-tag :value="detail.mchShowMobile" true-text="已开启" false-text="未开启" size="small"/>
            </el-descriptions-item>
            <template v-if="detail.mchShowMobile">
              <el-descriptions-item label="商户查看手机号价格">{{detail.mchShowMobilePrice | money | defaultValue}} 元</el-descriptions-item>
              <el-descriptions-item label="商户查看手机号状态">
                <dict-tag :value="detail.mchShowMobileStatus" :options="dict.type.recharge_mch_show_mobile_status" size="small"/>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <el-tabs>
        <el-tab-pane label="收益列表" lazy>
          <bonus v-if="detail.billId != null" :query="{billId: detail.billId}" :view="views.recharge"/>
        </el-tab-pane>
        <el-tab-pane label="支付信息" lazy>
          <pay-bill :query="{bstId: detail.billId}" :view="views.recharge"/>
        </el-tab-pane>
        <el-tab-pane label="电量记录" lazy>
          <bill-ele-record :query="{billId: detail.billId}" :view="views.recharge"/>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--退款对话框-->
    <refund-dialog :show.sync="showRefund" :bill-id="detail.billId" :amount="detail.money - detail.refundAmount" @success="getDetail"/>

    <el-dialog title="查看套餐详情" :visible.sync="showSuitTimePrice" width="700px">
      <suit-time-price
        disabled
        :fee-type="detail.suitFeeType"
        :gear-time="detail.suitGearTime"
        :gear-amount="detail.suitGearAmount"
      />
    </el-dialog>

  </div>
</template>

<script>
import { closeBill, getBill, rechargeDevice, refreshPayResult } from '@/api/system/recharge'
import Refund from '@/views/ss/refund/index.vue'
import { findLabel } from '@/utils'
import DeviceLink from '@/components/Business/Device/DeviceLink.vue'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import { DeviceServiceMode, SuitFeeType, views } from '@/utils/constants'
import PayBill from '@/views/ss/payBill/index.vue'
import Bonus from '@/views/ss/bonus/index.vue'
import { $recharge } from '@/utils/mixins'
import RefundDialog from '@/views/system/recharge/components/RefundDialog.vue'
import { toDescriptionFromSecond } from '@/utils/date'
import BooleanTag from '@/components/BooleanTag/index.vue'
import SuitTimePrice from '@/views/ss/suit/component/SuitTimePrice.vue'
import BillEleRecord from '@/views/ss/billEleRecord/index.vue'

export default {
  name: 'Recharge/:billId',
  mixins: [$recharge],
  components: { SuitTimePrice, BooleanTag, RefundDialog, Bonus, PayBill, UserLink, DeviceLink, Refund, BillEleRecord },
  dicts: [
    'channel_type',
    'sm_transaction_bill_status',
    'sm_transaction_bill_device_recharge_status',
    'time_unit',
    'suit_fee_mode',
    'suit_fee_type',
    'recharge_close_status',
    'device_service_mode',
    'recharge_mch_show_mobile_status'
  ],
  computed: {
    DeviceServiceMode() {
      return DeviceServiceMode
    },
    views() {
      return views
    },
    SuitFeeType() {
      return SuitFeeType
    },
    // 时长单位
    suitTimeUnit() {
      return (unit) => {
        return findLabel(this.dict.type.time_unit, unit);
      }
    },
  },
  data() {
    return {
      showSuitTimePrice: false,
      loading: false,
      detail: {},
      id: null,
      suitUsingType: ['info', 'warning', 'success', 'danger'],
      suitUsingText: ['未知', '未生效', '使用中', '已结束'],
      showRefund: false,
    }
  },
  created() {
    this.id = this.$route.params.billId;
    this.getDetail();
  },
  methods: {
    toDescriptionFromSecond,
    getDetail() {
      this.loading = true;
      getBill(this.id).then(res => {
        this.detail = res.data;
      }).finally(() => {
        this.loading = false;
      })
    },
    // 结束订单
    handleClose() {
      this.$confirm(`确定结束订单吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        closeBill({billId: this.detail.billId, totalEle: null}).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getDetail();
          }
        })
      })
    },
    // 设备充值
    rechargeDevice() {
      rechargeDevice(this.detail.billId).then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.getDetail();
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    // 刷新支付结果
    refreshPayResult() {
      refreshPayResult([this.detail.billId]).then(res => {
        if (res.code === 200) {
          this.$message.success("刷新成功");
          this.getDetail();
        } else {
          this.$message.error(res.msg);
        }
      })
    },
  }
}
</script>

<style>
.control-item {
  padding: 1em;
  border-radius: 16px;
  text-align: center;
  margin-bottom: 1em;
}
</style>
