<template>
  <div class="app-container">
    <el-card class="cardStyle" v-if="orderInfo.orderStatus === '4' || orderInfo.orderStatus === '2'">
      <div style="margin: 10px">
        <span style="color: #bf1c1c">该笔订单为异常状态，请检查充电桩状态！</span>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="dialogVisible = true">手动结算
        </el-button>
      </div>

      <el-dialog title="提示" :visible.sync="dialogVisible" width="35%">
        <span>平台收到充电桩传来的最后一次实时监测数据<br /></span>

        <el-table style="width: 100%" :data="monitorDataList" border>
          <el-table-column prop="dateTime" label="时间" align="center" />
          <el-table-column prop="chargingAmount" label="消费金额" align="center" />
          <el-table-column prop="chargingDegree" label="充电度数" align="center" />
        </el-table>

        <el-divider>下面可以输入自定义消费金额和充电度数</el-divider>

        <div style="display: flex; justify-content: center">
          <el-form :model="manualSettlementParam">
            <el-form-item label="消费金额:" prop="chargingAmount" label-width="80px">
              <el-input-number v-model.number="manualSettlementParam.chargingAmount" :precision="2" :controls="false"
                style="width: 50%" />
            </el-form-item>
            <el-form-item label="充电度数:" prop="chargingDegree" label-width="80px">
              <el-input-number v-model.number="manualSettlementParam.chargingDegree" :precision="2" :controls="false"
                style="width: 50%" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmManualSettlement">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 进度条-->
    <el-card class="cardStyle">
      <div style="margin: 30px">
        <div style="text-align: center; margin-bottom: 30px"
          v-if="orderInfo.orderStatus === '4' || orderInfo.orderStatus === '6'">
          停止理由：
          <span style="color: red">{{ orderInfo.stopReasonMsg }}</span>
        </div>
        <el-steps :active="orderInfo.orderStatus !== '6' ? 2 : 4" align-center finish-status="success">
          <el-step title="客户下单" :description="orderInfo.createTime"></el-step>
          <el-step title="开始充电" :description="orderInfo.orderStatusDescribe"></el-step>
          <el-step title="结束充电" :description="orderInfo.endTime"></el-step>
          <el-step title="完成充电" description="充电时长"></el-step>
        </el-steps>
      </div>
    </el-card>

    <!--  订单信息  -->
    <el-card class="cardStyle">
      <h3>订单信息</h3>
      <el-descriptions direction="vertical" :column="11" border :contentStyle="CS" :label-style="LS">
        <el-descriptions-item label="订单号">{{
          orderInfo.orderCode
        }}
        </el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{
          orderInfo.transactionCode
        }}
        </el-descriptions-item>
        <el-descriptions-item label="卡号">{{
          orderInfo.logicCard
        }}
        </el-descriptions-item>
        <el-descriptions-item label="订单状态描述">{{
          orderInfo.orderStatusDescribe
        }}
        </el-descriptions-item>
        <el-descriptions-item label="充电开始时间">{{
          orderInfo.startTime
        }}
        </el-descriptions-item>
        <el-descriptions-item label="充电结束时间">{{
          orderInfo.endTime
        }}
        </el-descriptions-item>
        <el-descriptions-item label="订单创建时间">{{
          orderInfo.createTime
        }}
        </el-descriptions-item>
        <el-descriptions-item label="订单结算金额">{{
          orderInfo.settleAmount
        }}
        </el-descriptions-item>
        <el-descriptions-item label="订单结算时间">{{
          orderInfo.settlementTime
        }}
        </el-descriptions-item>

        <el-descriptions-item label="起始SOC">{{
          orderInfo.startSOC
        }}
        </el-descriptions-item>
        <el-descriptions-item label="终止SOC">{{
          orderInfo.endSOC
        }}
        </el-descriptions-item>
        <el-descriptions-item label="订单停止原因">{{
          orderInfo.stopReasonMsg
        }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="marginTop"></div>
    </el-card>

    <el-card class="cardStyle">
      <h3>收费明细</h3>
      <el-table :data="tableData" border show-summary :summary-method="getSummaries">
        <el-table-column prop="periodType" label="时段类型" width="180" align="center" />
        <el-table-column prop="electricityPrice" label="电费单价(元/千瓦时)" align="center" />
        <el-table-column prop="servicePrice" label="服务费单价(元/千瓦时)" align="center" />
        <el-table-column prop="usedElectricity" label="用电量(千瓦时)" align="center" />
        <el-table-column prop="electricityAmount" label="电费金额(元)" align="center" />
        <el-table-column prop="serviceAmount" label="服务费金额(元)" align="center" />
      </el-table>
      <div class="marginTop"></div>
    </el-card>

    <!-- 实时订单数据 -->
    <el-card class="cardStyle">
      <h3>订单计费明细</h3>
      <el-descriptions direction="vertical" :column="5" border :contentStyle="CS" :label-style="LS">
        <el-descriptions-item label="时间">{{
          orderRealTimeInfo.time
        }}
        </el-descriptions-item>
        <el-descriptions-item label="消费金额">{{
          orderRealTimeInfo.orderAmount === "0.0000"
          ? "0"
          : orderRealTimeInfo.orderAmount
        }}
        </el-descriptions-item>
        <el-descriptions-item label="充电度数">{{
          orderRealTimeInfo.chargedDegree === "0.0000"
          ? "0"
          : orderRealTimeInfo.chargedDegree
        }}
        </el-descriptions-item>
        <el-descriptions-item label="充电时长">{{
          orderRealTimeInfo.chargingTime
        }}
        </el-descriptions-item>
        <el-descriptions-item label="当前soc">{{
          orderRealTimeInfo.soc
        }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="marginTop"></div>
    </el-card>
    <!-- 支付信息 -->
    <el-card class="cardStyle">
      <h3>支付信息</h3>
      <template v-if="payDetail.length !== 0">
        <el-descriptions direction="vertical" :column="6" border :contentStyle="CS" :label-style="LS"
          v-for="(item, index) in payDetail" :key="index">
          <el-descriptions-item label="支付金额">{{
            item.payAmount
          }}
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{
            item.payModeDesc
          }}
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">{{
            item.payStatus === "1" ? "支付完成" : "待支付"
          }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">{{
            item.payTime
          }}
          </el-descriptions-item>
          <el-descriptions-item label="支付流水号">{{
            item.outTradeNo
          }}
          </el-descriptions-item>
          <el-descriptions-item label="退款金额">{{
            item.refundAmount
          }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <div v-else style="text-align: center">暂无数据</div>
      <div class="marginTop"></div>
    </el-card>
    <!--  退款信息  -->
    <el-card class="cardStyle">
      <div style="margin: 12px 0">
        <span>退款信息</span>
        <el-button icon="el-icon-refresh-right" style="float: right; padding: 3px 0" type="text" @click="retryRefundOrder"
          v-if="retryRefundFlag">
          重试退款
        </el-button>
      </div>
      <el-table style="width: 100%" :data="orderRefundInfoList" border>
        <el-table-column prop="paymentId" label="支付流水号" align="center" />
        <el-table-column prop="reverseId" label="退款流水号" align="center" />
        <el-table-column prop="reverseAmt" label="退款金额" align="center" />
        <el-table-column prop="createdTime" label="退款申请时间" align="center" />
        <el-table-column prop="succeedTime" label="退款成功时间" align="center" />
      </el-table>
      <div class="marginTop"></div>
    </el-card>

    <!--  设备信息  -->
    <el-card class="cardStyle">
      <h3>设备信息</h3>
      <el-table style="width: 100%" :data="pileIn" border>
        <el-table-column prop="merchantName" label="运营商名称" align="center" />
        <el-table-column prop="pileSn" label="设备编号" align="center" />
        <el-table-column prop="ratedCurrent" label="额定电流(A)" align="center" />
        <el-table-column prop="ratedVoltage" label="额定电压(V)" align="center" />
        <el-table-column prop="ratedPower" label="额定功率(KW)" align="center" />
      </el-table>
      <div class="marginTop"></div>
    </el-card>

    <!--  用户信息  -->
    <el-card class="cardStyle">
      <h3>用户信息</h3>
      <el-table style="width: 100%" :data="userInfo" border>
        <el-table-column prop="nickName" label="用户昵称" align="center">
          <template slot-scope="scope">
            <router-link :to="'/member/detail/index/' + scope.row.memberId" class="link-type">
              <span>{{ scope.row.nickName }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="memberId" label="会员ID" align="center" />
        <el-table-column prop="mobileNumber" label="用户手机号" align="center" />
        <el-table-column prop="principalBalance" label="本金金额" align="center" />
        <!--        <el-table-column prop="giftBalance" label="赠送金额" align="center"/>-->
        <el-table-column prop="totalAccountAmount" label="总金额" align="center" />
      </el-table>
      <div class="marginTop"></div>
    </el-card>
    <!--    时间 描述-->
    <el-card class="cardStyle"
      v-if="orderInfo.orderStatus === '1' || orderInfo.orderStatus === '6' && obj.realTimeMonitorDataList !== null">
      <div class="marginTop"></div>
      <order-echarts :obj="obj"></order-echarts>
    </el-card>
  </div>
</template>
<script>
import {
  getOrder,
  manualSettlementOrder,
  retryRefundOrder,
} from "@/api/order/order";
import OrderEcharts from "@/views/order/order/orderEcharts";

export default {
  name: "",
  components: { OrderEcharts },
  data() {
    return {
      CS: {
        "text-align": "center",
        "word-break": "break-all",
      },
      LS: {
        height: "40px",
        color: "#515A6E",
        "text-align": "center",
        "word-break": "break-all",
        "font-weight": "bolder",
      },
      orderCode: this.$route.params.orderCode,
      orderInfo: {},
      payDetail: [],
      // 订单退款列表
      orderRefundInfoList: [],
      // 重试退款按钮
      // retryRefundFlag: false,
      userInfo: [],
      obj: {},
      orderDetail: [],
      pileIn: [],
      orderRealTimeInfo: {
        orderAmount: null,
        chargedDegree: null,
        chargingTime: null,
        soc: null,
      },
      // 手动结算对话框Visible
      dialogVisible: false,
      // 最后一次实时监测数据
      lastMonitorData: {},
      // monitorDataList: [this.lastMonitorData],
      // 手动结算参数
      manualSettlementParam: {
        orderCode: null,
        chargingAmount: null,
        chargingDegree: null,
      },
      tableData: [],
      isRequesting: false, // 手动结算请求状态
    };
  },
  created() {
    this.getOrderDetail();
  },
  methods: {
    getSummaries(param) {
      console.log(param, '添加调试输出');
      const { columns, data } = param;
      // console.log(data, 'data');
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "usedElectricity" ||
          column.property === "electricityAmount" ||
          column.property === "serviceAmount"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              let result = prev + curr;
              result = Math.round(result * 100) / 100;
              return result;
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    clickManualSettlement() {
      this.dialogVisible = true;
    },

    // 重试退款方法
    retryRefundOrder() {
      const param = {
        orderCode: this.orderCode,
      };
      retryRefundOrder(param).then((response) => {
        this.getOrderDetail();
      });
    },
    confirmManualSettlement() {
      if (this.isRequesting) {
        this.$message({
          showClose: true,
          message: '手动结算订单已经提交，请勿重复操作',
          type: 'warning'
        });
        return; // 如果正在请求中，则不再继续发送请求
      }
      this.isRequesting = true;
      console.log('点击了手动结算按钮');
      if (this.manualSettlementParam.chargingAmount == null) {
        return false;
      }
      if (this.manualSettlementParam.chargingDegree == null) {
        return false;
      }
      this.manualSettlementParam.orderCode = this.orderInfo.orderCode;
      console.log("确认手动结算订单param:", this.manualSettlementParam);
      manualSettlementOrder(this.manualSettlementParam).then((response) => {
        this.dialogVisible = false;
        this.getOrderDetail();
      });
    },
    async getOrderDetail() {
      const { data } = await getOrder(this.orderCode);
      console.log("getOrder", data);
      this.obj = data;
      console.log('统计图是否有数据', this.obj.realTimeMonitorDataList);
      this.orderInfo = data.orderInfo;
      this.payDetail = data.payRecordList; // 数组
      this.orderRefundInfoList = data.orderRefundInfoList; // 数组
      this.userInfo = [data.memberInfo];
      // console.log("this.userInfo", this.userInfo);
      this.pileIn = [data.pileInfo];
      // console.log("this.pileIn", this.pileIn);
      if (data.orderRealTimeInfo !== null) {
        this.orderRealTimeInfo = data.orderRealTimeInfo;
      }
      this.orderDetail = [data.billingDetails];
      this.tableData = data.chargeDetails; // array
      this.lastMonitorData = data.lastMonitorData;
      console.log("orderInfo.orderStatus", this.orderInfo.orderStatus);
      // 是否显示重试退款按钮
      // if (data.orderInfo.orderStatus === '6' && data.payRecordList[0].payMode === '4' && data.orderRefundInfoList.length === 0) {
      //   this.retryRefundFlag = true;
      // }
    },
  },
  computed: {
    // 一个计算属性的 getter
    monitorDataList() {
      return [this.lastMonitorData];
    },
    retryRefundFlag() {
      // if (this.orderInfo == null || this.orderInfo.orderStatus !== "6") {
      //   return false;
      // }
      // if (this.payDetail[0] == null || this.payDetail[0].payMode !== "4") {
      //   return false;
      // }
      // if (
      //   this.payDetail[0].refundAmount == null ||
      //   this.payDetail[0].refundAmount <= 0.0
      // ) {
      //   return false;
      // }
      // if (this.orderRefundInfoList.length === 0) {
      //   return false;
      // }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.cardStyle {
  margin-bottom: 10px;
}

.marginTop {
  margin-top: 10px;
}
</style>
