<style scoped lang="scss">
.system-container {

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }

  }
}

.page-content {
  margin-bottom: 20px;
}

.page-pager {
  background-color: #fff;
  height: 24px;
}

.copy-icon {
  cursor: pointer;
  margin-left: 4px;
  vertical-align: middle;
  color: #409eff;
}

.copy-icon:hover {
  color: #66b1ff;
}

.copy-text {
  cursor: pointer;
  color: #409eff;
}

.copy-text:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">


      <el-form
          :model="state.formQuery"
          ref="queryRef"
          size="default" label-width="0px" class="mt5 mb5">
        <el-input
            v-model="state.formQuery.mobilePhone"
            placeholder="用户手机号"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>
        <ext-select
            v-model="state.formQuery.stationIds"
            placeholder="站点"
            clearable
            url="station/listStation"
            urlMethod="get"
            data-key=""
            label-key="stationName"
            value-key="stationId"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </ext-select>
        <ext-select
            v-model="state.formQuery.platformName"
            placeholder="互联平台"
            clearable
            url="platform/list"
            urlMethod="get"
            data-key="list"
            label-key="platformName"
            value-key="platformName"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </ext-select>
        <el-input
            v-model="state.formQuery.startChargeSeq"
            placeholder="充电订单号"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>
        <el-input
            v-model="state.formQuery.connectorId"
            placeholder="充电设备接口编码"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>
        <el-date-picker
            v-model="state.formQuery.startDate"
            placeholder="开始时间"
            type="date"
            value-format="YYYY-MM-DD"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </el-date-picker>
        <el-date-picker
            v-model="state.formQuery.endDate"
            placeholder="结束时间"
            type="date"
            value-format="YYYY-MM-DD"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </el-date-picker>
        <ext-d-select
            v-model="state.formQuery.orderStatus"
            type="ChargeOrder.orderStatus"
            placeholder="订单状态"
            clearable
            @on-change="loadData(true)"
            class="wd150 mr10">
        </ext-d-select>
        <ext-d-select
            v-model="state.formQuery.chargeStatus"
            placeholder="充电状态"
            clearable
            type="ChargeOrder.chargeStatus"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </ext-d-select>
        <!--        <ext-d-select-->
        <!--            v-model="state.formQuery.stopReason"-->
        <!--            placeholder="充电停止原因"-->
        <!--            clearable-->
        <!--            type="ChargeOrder.stopReason"-->
        <!--            @blur="loadData(true)"-->
        <!--            class="wd150 mr10">-->
        <!--        </ext-d-select>-->
        <ext-d-select
            v-model="state.formQuery.invoiceStatus"
            placeholder="发票状态"
            clearable
            type="ChargeOrder.invoiceStatus"
            @on-change="loadData(true)"
            class="wd150 mr10">
        </ext-d-select>


        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>
        <el-button class="ml10" plain size="default" type="warning" @click="handleDownloadExcel">
          <SvgIcon name="ele-Download"/>
          导出
        </el-button>
      </el-form>

      <el-card class="w100">
        <div class="order-summary">
          <span>订单笔数:</span>
          <el-tag type="success">{{ state.extraData.totalOrders }} 笔</el-tag>
          <span class="ml5">电量:</span>
          <el-tag type="success">{{ state.extraData.totalPower }} 度</el-tag>
          <span class="ml5">订单金额:</span>
          <el-tag type="success">{{ u.fmt.fmtMoney(state.extraData.totalMoney) }} 元</el-tag>
          <span class="ml5"> 电费:</span>
          <el-tag type="success">{{ u.fmt.fmtMoney(state.extraData.elecMoney) }} 元</el-tag>
          <span class="ml5">服务费:</span>
          <el-tag type="success">{{ u.fmt.fmtMoney(state.extraData.serviceMoney) }} 元</el-tag>
          <span class="ml5">服务费优惠:</span>
          <el-tag type="success">{{ u.fmt.fmtMoney(state.extraData.serviceMoneyDiscount) }} 元</el-tag>
          <span class="ml5">实付服务费:</span>
          <el-tag type="success">{{ u.fmt.fmtMoney(state.extraData.payServiceAmount) }} 元</el-tag>
        </div>

      </el-card>

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          highlight-current-row
          current-row-key="id"
          row-key="id"
          :data="state.tableData.data"
          v-loading="state.tableData.loading"
          @selection-change="handleTableSelectionChange"
          @sort-change="handleTableSortChange">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.tableData.columns"
            :key="field.prop"
            :label="field.label"
            :align="field.align||'left'"
            :column-key="field.prop"
            :width="field.width"
            :min-width="field.minWidth"
            :fixed="field.fixed"
            :sortable="field.sortable"
            :show-overflow-tooltip="!field.fixed&&field.width>150"
        >
          <template #default="{row}">
            <template v-if="field.prop==='expand'">
              <p style="padding-left: 2em;" v-html="row[field.prop]"></p>
            </template>
            <template v-else-if="'totalMoney'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'elecMoney'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'serviceMoney'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'payAmount'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'discountAmount'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'serviceMoneyDiscount'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'payServiceAmount'===field.prop">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="'orderStatus'===field.prop">
              <ext-d-label type="ChargeOrder.orderStatus" v-model="row[field.prop]"/>
            </template>
            <template v-else-if="'chargeStatus'===field.prop">
              <ext-d-label type="ChargeOrder.chargeStatus" v-model="row[field.prop]"/>
            </template>
            <template v-else-if="'stopReason'===field.prop">
              <ext-d-label type="ChargeOrder.stopReason" v-model="row[field.prop]"/>
            </template>
            <template v-else-if="'invoiceStatus'===field.prop">
              <ext-d-label type="ChargeOrder.invoiceStatus" v-model="row[field.prop]"/>
            </template>
            <template v-else-if="'startTime'===field.prop">
              <div title="充电开始时间">
                {{ (row.startTime) }}
              </div>
              <hr>
              <div title="充电结束时间">
                {{ (row.endTime) }}
              </div>
            </template>

            <template v-else-if="'startChargeSeq'===field.prop">
              <span class="copy-text" @click.stop="copyText(row[field.prop])">{{ row[field.prop] }}</span>
            </template>

            <template v-else-if="'stationId'===field.prop">
              <div >
                {{ (row.stationId) }}
              </div>
              <hr v-if="row.stationName">
              <div >
                {{ (row.stationName) }}
              </div>
            </template>

            <template v-else>
              <div>{{ row[field.prop] }}</div>
            </template>

          </template>
        </el-table-column>
      </el-table>

      <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
    </el-card>
  </div>
  <!--  <ChargeOrderDialog ref="chargeOrderDialogRef" @refresh="loadData(true)"/>-->
</template>

<script setup lang="ts" name="ChargeOrderList">
import {defineAsyncComponent, reactive, onMounted, onBeforeMount, ref, getCurrentInstance, nextTick, onBeforeUnmount} from 'vue';
import {$body, $get} from "/@/utils/request";
import {Msg} from "/@/utils/message";
import u from "/@/utils/u"

import {useRoute} from "vue-router";

const route = useRoute();

import ExtPage from '/@/components/form/ExtPage.vue'

import mittBus from '/@/utils/mitt';
import ExtDatePicker from "/@/components/form/ExtDatePicker.vue";
import ExtDSelect from "/@/components/form/ExtDSelect.vue";
import ExtDLabel from "/@/components/form/ExtDLabel.vue";
import ExtSelect from "/@/components/form/ExtSelect.vue";

// const ChargeOrderDialog = defineAsyncComponent(() => import("/@/views/page/ChargeOrderDialog.vue"));

//定义引用
const queryRef = ref();
const chargeOrderDialogRef = ref();

//定义变量
const state = reactive({
  formQuery: {},
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      {label: '站点ID/名称', prop: 'stationId', width: 130,align:'center', resizable: true, fixed: 'left'},
      {label: '用户手机号', prop: 'mobilePhone', width: 120, resizable: true, fixed: 'left'},
      // {label: '站点ID',  prop: 'stationId',width:100, resizable: true, fixed: 'left'},
      // {label: '站点', prop: 'stationName', width: 150, resizable: true, fixed: 'left'},
      {label: '充电订单号', prop: 'startChargeSeq', width: 170, resizable: true, fixed: 'left'},
      {label: '互联平台', prop: 'platformName', width: 120, resizable: true, fixed: 'left'},
      {label: '设备编号', prop: 'shortId', width: 90, resizable: true},
      {label: '充电设备接口编码', prop: 'connectorId', width: 160, resizable: true},
      {label: '充电开始/结束时间', prop: 'startTime', sortable: 'custom', width: 175, resizable: true},
      // {label: '充电结束时间', prop: 'endTime', sortable: 'custom', width: 160, resizable: true},
      {label: '充电量/度', prop: 'totalPower', width: 95, resizable: true},
      {label: '订单总金额', prop: 'totalMoney', width: 105, resizable: true},
      {label: '服务费优惠', prop: 'serviceMoneyDiscount', width: 105, resizable: true},
      {label: '实付金额', prop: 'payAmount', width: 90, resizable: true},
      {label: '总电费', prop: 'elecMoney', width: 80, resizable: true},
      {label: '总服务费', prop: 'serviceMoney', width: 90, resizable: true},
      {label: '实付服务费', prop: 'payServiceAmount', width: 105, resizable: true},
      // {label: '时段数：0~32', prop: 'sumPeriod', width:150, resizable: true},
      // {label: '充电明细信息', prop: 'chargeDetail', width:150, resizable: true},
      {label: '订单状态', prop: 'orderStatus', width: 90, resizable: true},
      {label: '充电状态', prop: 'chargeStatus', width: 90, resizable: true},
      {label: '充电停止原因', prop: 'stopReason', width: 120, resizable: true},
      {label: '发票状态', prop: 'invoiceStatus', width: 90, resizable: true},
      // {label: '创建时间', prop: 'createTime', sortable: 'custom', width:150, resizable: true},
      // {label: '更新时间', prop: 'updateTime', sortable: 'custom',width:150,  resizable: true},
      // {
      //   label: '操作', prop: 'action', width: 180, align: 'center', fixed: 'right',
      // }
    ],

  },
  extraData: {
    totalOrders: 0,
    totalPower: 0,
    elecMoney: 0,
    serviceMoney: 0,
    totalMoney: 0,
  }
})


// 监听双向绑定 modelValue 的变化
// watch(
//         () => state.pageIndex,
//         () => {
//
//         }
// );

//生命周期钩子
onBeforeMount(() => {
})

onMounted(() => {
  var query = route.query;
  console.log(route.params, route.query)
  if (query.connectorId) {
    state.formQuery.connectorId = query.connectorId;
  }

  if (query.mobilePhone) {
    state.formQuery.mobilePhone = query.mobilePhone;
  }

  loadData();

  nextTick(() => {
    let bodyHeight = document.body.clientHeight;
    let queryHeight = queryRef.value.$el.clientHeight;
    state.tableData.height = bodyHeight - queryHeight - 320
    // state.tableData.height =300
  })

  mittBus.on("chargeOrder.refresh", () => {
    loadData();
  })
});

onBeforeUnmount(() => {
  mittBus.off("chargeOrder.refresh")
})


//region 方法区
// 初始化表格数据
const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $get(`/custom/listChargeOrders`, {...state.formQuery, ...state.pageQuery}).then((res: any) => {
    let {list, total, extraData} = res;
    state.extraData = extraData;
    state.tableData.data = list;
    state.pageQuery.total = total;
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

// 打开修改用户弹窗
const onRowClick = (type: string, row: any) => {
  chargeOrderDialogRef.value.open(type, row);
};

// 删除用户
const onRowDel = (row: any) => {
  Msg.confirm(`此操作将永久删除：『${row.name}』，是否继续?`).then(() => {
    $get(`/chargeOrder/delete/${row.id}`).then(() => {
      Msg.message("删除成功", 'success')
    }).catch(() => {
      Msg.message("删除失败", 'error')
    })
  });
};

const handleTableSelectionChange = (selection: any) => {
  console.log("handleTableSelectionChange>>", selection)
  // emit("on-check-change", selection)
}

const handleTableSortChange = (column, prop, order) => {
  console.log("handleTableSortChange>>", column, prop, order)
  // emit("on-sort-change", column)
}

const copyText = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    Msg.message("已复制", 'success')
  })
}

const handleDownloadExcel = () => {
  let url = import.meta.env.VITE_API_URL;
  if (!url) {
    url = `${location.origin}/admin/`;
  }
  let params = Object.keys(state.formQuery).map(key => `${key}=${state.formQuery[key]}`).join("&")
  window.open(`${url}/custom/exportChargeOrders?t=${new Date().getTime()}&${params}`, "_blank")
}


//endregion


// 暴露变量
// defineExpose({
//     loadData,
// });
</script>
