<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: var(--el-color-white);
  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="'userStationId'===field.prop">
              <div class="flex-align-items-center text-align-center">
                <div>
                  {{ row.userStationId }}
                </div>
                <hr/>
                <div>
                  {{ row.userStationName }}
                </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-column label="操作" width="100" fixed="right">
          <template #default="{row}">
            <el-button
              v-if="row.orderStatus === 0"
              type="danger"
              text
              size="small"
              @click="handleForceSettle(row)"
            >
              强制结算
            </el-button>
          </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 {reactive, onMounted, onBeforeMount, ref, 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";
import {useRoute} from "vue-router";
import {ElButton} from 'element-plus';

const route = useRoute();


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: {
    mobilePhone:null
  },
  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', valueKey: 'stationId', labelKey: 'stationName'}},
    {label: '归属站点', prop: 'userStationId', width: 140, query: true, type: 'select', resizable: true, conf: {url: 'washStation/list', valueKey: 'stationId', labelKey: 'stationName'}},
    {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: 120, label: '关机方式',
      prop: 'closeType',
      query: false,
      type: 'dict',
      conf: {dict: 'Order.closeType'},
      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: '更新时间',
      fixed: 'right',
      prop: 'updateTime',
      query: false,
      sortable: 'custom',
      type: 'datetime',
      resizable: true,
      conf: {format: (val: any) => u.fmt.fmtDate(val)}
    },
  ],
})



//生命周期钩子
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,}
  let query = route.query;
  console.log(route.params, route.query)
  if (query.mobilePhone) {
    state.formQuery.mobilePhone = query.mobilePhone;
  }
})

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')
    })
  });
};
// 强制结算
const handleForceSettle = (row: any) => {
  Msg.confirm(`确定要对订单「${row.orderId}」进行强制结算吗？此操作将强制结束该订单并释放设备。`).then(() => {
    $body(`/washOrder/forceSettle/${row.orderId}`).then(() => {
      Msg.message("强制结算成功", 'success')
      loadData(true)
    }).catch(() => {
      Msg.message("强制结算失败", 'error')
    })
  });
};

//endregion


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