<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;
}

.order-detail {
  margin-left: 20px;
}

.el-table {
  &:deep(.el-table__body-wrapper) {
    width: 100% !important;
    height: calc(100% - 108px) !important; // 表格高度减去表头的高度

    .el-scrollbar__bar.is-horizontal {
      height: 10px;
      left: 2px;
    }
  }


}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <ext-query-form
          class="page-search"
          ref="queryRef"
          v-model="state.formQuery"
          :columns="state.columns"
          :import-config="state.importConfig"
          :export-config="state.exportConfig"
          @on-change="loadData(true)"
          @imported="loadData(true)">
        <!--  <template #extraQuery></template>
          <template #extraLeft></template>
          <template #extraRight></template>-->
      </ext-query-form>

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          highlight-current-row
          current-row-key="id"
          row-key="id"
          @on-row-click="handleRowClick('view',$event)"
          :data="state.tableData.data"
          v-loading="state.tableData.loading">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.columns"
            :key="field.prop"
            :type="field.type"
            :label="field.label"
            :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.type==='expand'">
              <div class="order-detail">
                <el-table
                    border
                    :data="row.detail"
                    stripe="stripe">
                  <el-table-column width="120" label="服务项目" prop="name"></el-table-column>
                  <el-table-column width="120" label="服务时长" prop="seconds"></el-table-column>
                  <el-table-column width="120" label="服务单价" prop="price"></el-table-column>
                  <el-table-column width="120" label="小计金额" prop="amount"></el-table-column>
                </el-table>
              </div>
            </template>
            <template v-else-if="'stationId'===field.prop">
              <div class="flex-align-items-center text-align-center">
                <div>
                  {{ row.stationId }}
                </div>
                <hr/>
                <div>
                  {{ row.stationName }}
                </div>
              </div>
            </template>
            <template v-else-if="field.prop==='discountType'">
              <ext-d-label type="Activity.discountType" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='cardType'">
              <ext-d-label type="OrderCard.type" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='invoiceStatus'">
              <ext-d-label type="Invoice.status" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='openType'">
              <ext-d-label type="Order.openType" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='orderStatus'">
              <ext-d-label type="Order.status" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='payStatus'">
              <ext-d-label type="Order.pay" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='closeType'">
              <ext-d-label type="Order.closeType" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="['prepayMoney','amount','amountReceivable','amountReceived','cardBalance','coinMoney','discountAmount','discountMoney'].includes(field.prop)">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="field.prop==='idleRemainTime'||field.prop==='operationRemainTime'">
              {{ u.fmt.fmtDuration(row[field.prop]) }}
            </template>
            <template v-else-if="field.prop==='createTime'">
              {{ u.fmt.fmtDateTime(row[field.prop]) }}
            </template>
            <template v-else-if="field.prop==='updateTime'">
              {{ u.fmt.fmtDateTime(row[field.prop]) }}
            </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>
</template>

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

const {proxy}: any = getCurrentInstance();

import ExtPage from '/@/components/form/ExtPage.vue'
import ExtQueryForm from "/@/components/form/ExtQueryForm.vue";

import mittBus from '/@/utils/mitt';

import ExtDLabel from "/@/components/form/ExtDLabel.vue";


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

//定义变量
const state = reactive({
  formQuery: {},
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false
  },
  importConfig: {},
  exportConfig: {},
  columns: [
    {type: 'expand', width: 60, align: 'center', fixed: 'left'},
    {label: '站点', prop: 'stationId', width: 140,query: true, type: 'select', resizable: true,conf:{url:'washStation/list',labelKey:'stationName',valueKey:'stationId',dataKey:'list'}},
    {width: 220, label: '订单号', prop: 'orderId', query: true, type: 'text', resizable: true, fixed: 'left'},
    {width: 120, label: '用户手机号', prop: 'mobilePhone', query: true, type: 'text', fixed: 'left'},
    {width: 100, label: '设备编号', prop: 'shortId', query: false, type: 'text', resizable: true},
    {width: 160, label: '开始时间', prop: 'startTime', query: false, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDate(val)}},
    {width: 160, label: '结束时间', prop: 'endTime', query: false, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDateTime(val)}},
    {width: 100, label: '消费总额', prop: 'amount', query: false, resizable: true},
    {width: 100, label: '应收金额', prop: 'amountReceivable', query: false, type: '', resizable: true},
    {width: 100, label: '实收金额', prop: 'amountReceived', query: false, type: 'text', resizable: true},
    // {width: 160, label: '卡内余额', prop: 'cardBalance', query: false, type: 'text', resizable: true},
    // {
    //   width: 160, label: '卡过期时间',
    //   prop: 'cardExpired',
    //   query: false,
    //   sortable: 'custom',
    //   type: 'datetime',
    //   resizable: true,
    //   conf: {format: (val: any) => u.fmt.fmtDateTime(val)}
    // },
    // {width: 160, label: '卡内码', prop: 'cardId', query: false, type: 'text', resizable: true},
    // {width: 160, label: '卡串号', prop: 'cardSn', query: false, type: 'text', resizable: true},
    // {width: 160, label: '卡类型', prop: 'cardType', query: false, type: '', resizable: true},
    {
      width: 120, label: '关机方式',
      prop: 'closeType',
      query: false,
      type: 'dict',
      conf: {dict: 'Order.closeType'},
      resizable: true
    },
    // {width: 160, label: '投币的累计金额', prop: 'coinMoney', query: false, type: 'text', resizable: true},
    // {width: 160, label: '投币的次数', prop: 'coinNum', query: false, type: 'text', resizable: true},
    // {width: 160, label: '开单时间', prop: 'createTime', query: false, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDateTime(val)}},
    // {
    //   width:160,label: '费用明细',
    //   prop: 'detail',
    //   query: true,
    //   type: 'text',
    //   resizable: true
    // },

    // {width: 160, label: '优惠金额', prop: 'discountAmount', query: false, type: '', resizable: true},
    // {width: 160, label: '优惠方式', prop: 'discountType', query: false, type: 'dict', conf: {dict: 'Activity.discountType'}, resizable: true},
    // {
    //   width: 160, label: '设备空闲关机倒计时剩余时间',
    //   prop: 'idleRemainTime',
    //   query: true,
    //   type: 'text',
    //   resizable: true
    // },
    // {width: 160, label: '会员折扣比例', prop: 'memberDiscount', query: false, type: 'text', resizable: true},
    // {width: 160, label: '开机方式', prop: 'openType', query: false, type: 'dict', conf: {dict: 'Order.openType'}, resizable: true},
    // {width: 160, label: '订单操作剩余操作时间(单位秒)', prop: 'operationRemainTime', query: false, type: 'text', resizable: true},
    // {width: 160, label: '本机订单号', prop: 'orderIdLocal', query: false, type: 'text', resizable: true},
    {width: 100, label: '订单状态', prop: 'orderStatus', query: false, type: 'dict', conf: {dict: 'Order.status'}, resizable: true},
    {width: 100, label: '支付状态', prop: 'payStatus', query: true, type: 'dict', conf: {dict: 'Order.pay'}, resizable: true},
    {width: 100, label: '发票状态', prop: 'invoiceStatus', query: false, type: 'dict', conf: {dict: 'Invoice.status'}, resizable: true},
    // {width: 160, label: '本次开机的预付金额', prop: 'prepayMoney', query: true, type: '', resizable: true},
    // {width: 160, label: '产品key', prop: 'productKey', query: false, type: 'text', resizable: true},
    // {width: 160, label: '站点ID', prop: 'stationId', query: true, type: 'text', resizable: true},
    // {label: '停机原因', prop: 'stopReason', query: false, type: 'text', resizable: true},
    {
      width: 160,
      label: '更新时间',
      fixed: 'right',
      prop: 'updateTime',
      query: false,
      sortable: 'custom',
      type: 'datetime',
      resizable: true,
      conf: {format: (val: any) => u.fmt.fmtDate(val)}
    },
  ],
})


// 监听双向绑定 modelValue 的变化
// watch(
//         () => state.pageNum,
//         () => {
// //：' +
// 'name 名称 price 单价(单位分) ' +
// 'seconds 时长(单位秒) ' +
// 'amount 费用(单位分)' +
// ' space⻋位或场地，' +
// 'water清水，' +
// 'foam泡沫，' +
// 'leaner吸尘，' +
// 'tap水龙头，' +
// 'user_ext用户扩展，消毒或吹干等功能，' +
// 'coat镀膜，' +
// 'blow吹气
//         }
// );

//生命周期钩子
onBeforeMount(() => {
  let token = Session.get("token")
  let encodeToken = encodeURIComponent(token)
  let exportUrl = `poi/export?type=washOrder&X-Token=${encodeToken}`
  //导入导出参数配置
  state.importConfig = {
    auths: ['washOrder.add'],
    url: `poi/import?type=washOrder&X-Token=${encodeToken}`,
    template: `${exportUrl}&isTemplate=true`
  }

  state.exportConfig = {url: exportUrl,}

})

onMounted(() => {
  console.log("ordering mounted")
  loadData();

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

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

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


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

    list.forEach((item: any) => {
      if (item.detail) {
        // let parse = JSON.parse(item.detail);
        item.detail = item.detail.filter((k: any) => k.amount > 0 || k.seconds > 0).map((s: any) => {
          return {
            name: u.fmt.fmtDict(s.name, 'Order.feeType'),
            seconds: u.fmt.fmtDuration(s.seconds * 1000),
            price: u.fmt.fmtMoney(s.price),
            amount: u.fmt.fmtMoney(s.amount),
          }
        })
      } else {
        item.detail = {}
      }
    })

    state.tableData.data = list;
    state.pageQuery.total = total;
    state.tableData.loading = false;
  }).catch(e => {
    //console.error(e)
    state.tableData.loading = false;
  })
};

// 打开详情页弹窗
const handleRowClick = (type: string, row: any) => {
  washOrderDialogRef.value.open(type, row);
};
// 删除点击
const handleRowDelete = (row: any) => {
  Msg.confirm(`此操作将永久删除：『${row.name}』，是否继续?`).then(() => {
    $get(`/washOrder/delete/${row.id}`).then(() => {
      Msg.message("删除成功", 'success')
    }).catch(() => {
      Msg.message("删除失败", 'error')
    })
  });
};

//endregion


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