<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;
}
</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">
        <ext-select
            v-model="state.formQuery.stationId"
            placeholder="站点"
            url="washStation/list"
            url-method="post"
            label-key="stationName"
            value-key="stationId"
            data-key="list"
            clearable
            class="wd200 ml10"/>

        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>
      </el-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>
              </div>
            </template>
            <template v-else-if="field.prop==='stationName'">
              <div class="text-align-center cursor-pointer" @click="handleGotoSplitPage(row)">
                <el-button link type="primary" >{{ row.stationId }}</el-button>
                <hr>
                <el-button link type="primary" >{{ row.stationName }}</el-button>
              </div>
            </template>
            <template v-else-if="field.prop==='type'">
              <ext-d-label type="Object.type" :model-value="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="['availableBalance','withdrawnAmount','withdrawnFrozenAmount'].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="['createTime','updateTime'].includes(field.prop)">
              {{ u.fmt.fmtDateTime(row[field.prop]) }}
            </template>
            <template v-else-if="field.prop=='action'">
             <el-text class="cursor-pointer" type="primary" @click="handleWithdrawApplyClick(row)">提现申请</el-text>
            </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 setup lang="ts" name="adminStationAccount">
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 ExtPage from '/@/components/form/ExtPage.vue'
import {useRouter} from "vue-router";

const router = useRouter();

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

import {ElButton} from 'element-plus'
import ExtSelect from "/@/components/form/ExtSelect.vue";


//定义引用
const queryRef = 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: 'selection', width: 60, align: 'center', fixed: 'left'},
    // {label: '站点ID', width: 100,prop: 'stationId', query: true, type: 'text', resizable: true},
    {label: '站点名称', width: 200, prop: 'stationName', query: true, type: 'text', resizable: true},
    {label: '可提现金额（元）', width: 180, prop: 'availableBalance', query: true, type: '', resizable: true},
    {label: '已提现金额（元）', width: 180, prop: 'withdrawnAmount', query: true, type: '', resizable: true},
    {label: '提现中金额（元）', width: 180, prop: 'withdrawnFrozenAmount', query: true, type: '', resizable: true},
    {label: '创建时间', width: 180, prop: 'createTime', query: true, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDate(val)}},
    {label: '更新时间', width: 180, prop: 'updateTime', query: true, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDate(val)}},
    {
      label: '操作', prop: 'action', type: 'render', width: 180, align: 'center', fixed: 'right',
    }
  ],
})


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

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

})

onMounted(() => {
  loadData();

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

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

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

const handleGotoSplitPage = (row: any) => {
  router.push(`/financeSR?stationId=${row.stationId}`)
}


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

// 打开详情页弹窗
const handleWithdrawApplyClick = ( row: any) => {
  Msg.confirm(`确认执行本操作吗?`,'提现申请').then(()=>{
    Msg.prompt(`请输入提现金额（单位：元）`, '提现申请',
        {
          draggable: true,
          type: 'primary',
        }
    ).then((res: any) => {
      let {value, action} = res;
      console.log(res)
      let v =value;
      if (action === 'confirm') {
        if(!(v != null && v !== '' && !Number.isNaN(Number(v)))){
          Msg.message("请输入有效的提现金额，否则无法发起本操作",'error')
          return
        }
        Msg.showLoading(`请等待`);
        $body(`finance/applyWithdrawn`,{stationId:row.stationId,amount:Number(value)*100}).then(()=>{
          Msg.message("提现已发起")
          Msg.hideLoading()
          loadData(true)
        }).catch(e=>{
          Msg.hideLoading()
        })
      }
    })
  })

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

//endregion


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