<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">
      <ext-query-form
          class="page-search"
          ref="queryRef"
          v-model="state.formQuery"
          :columns="state.columns"
          @on-change="loadData(true)"
          @imported="loadData(true)">
        <template #extQuery>
          <el-button v-auth="'washDevice.add'" size="default" plain type="success" class="ml10" @click="handleRowClick('add',null)">
            <SvgIcon name="ele-FolderAdd"/>
            新增
          </el-button>

          <el-button v-auth="'washDevice.modify'" size="default"
                     plain type="success" class="ml10"

                     @click="handleBatchDeviceConfig">
            <SvgIcon name="ele-Setting"/>
            配置
          </el-button>
        </template>
        <!--  <template #extraQuery></template>
          <template #extraLeft></template>
          <template #extraRight></template>-->
      </ext-query-form>

      <ext-table
          selectable
          @on-check-change="handleChooseDeviceChange"
          class="page-content"
          :height="state.tableData.height"
          :data-list="state.tableData.data"
          :columns="state.columns"
          :border="true"
          :loading="state.tableData.loading">
      </ext-table>

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

<script setup lang="ts" name="adminStationDevice">
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 ExtTable from "/@/components/form/ExtTable.vue";

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

import {ElButton} from 'element-plus'

import DeviceDialog from '/@/views/admin/station/device/dialog.vue'
import DeviceConfigDialog from '/@/views/admin/station/device/config.vue'


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

//定义变量
const state = reactive({
  chooseDeviceList: [],
  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: '站点',
      prop: 'stationId',
      width: 80,
      query: true,
      type: 'select',
      hide: true,
      resizable: true,
      conf: {url: 'washStation/list', labelKey: 'stationName', valueKey: 'stationId', dataKey: 'list'}
    },
    {label: '设备编号', prop: 'shortId', width: 100, query: true, type: 'text', resizable: true, fixed: 'left'},
    {
      label: '站点名称', prop: 'stationName', width: 180, query: false, type: 'render', resizable: true,
      render: (h: any, row: any, rowData: any) => {
        return (
            h('div', {
              class: 'flex-align-items-center text-align-center'
            }, [
              h("div", {}, rowData.stationId),
              h("hr"),
              h("div", {}, rowData.stationName)
            ])
        )
      }
    },
    // {label: '设备名称', prop: 'deviceName', width: 180, query: true, type: 'text', resizable: true, fixed: 'left'},
    // {label: '产品key', prop: 'productKey', width: 180, query: true, type: 'text', resizable: true},
    {label: '状态', prop: 'state', width: 90, query: true, type: 'dict', conf: {dict: 'WashDevice.status'}, resizable: true},
    // {label: '设备状态', prop: 'fsmState', width: 90, query: true, type: 'text', resizable: true},
    {
      label: '运行时长', prop: 'uptimeMs', width: 100, query: false, type: 'render', resizable: true,
      render: (h: any, row: any) => {
        return (
            h('div', null, u.fmt.fmtDuration(row))
        )
      }
    },
    {label: '功能', prop: 'functions', width: 180, query: true, type: 'text', resizable: true},
    {label: '是否有泡沫', prop: 'hasFoam', width: 180, query: true, type: 'dict', conf: {dict: 'WashDevice.foam'}, resizable: true},
    {label: '是否有水', prop: 'hasWater', width: 180, query: true, type: 'dict', conf: {dict: 'WashDevice.water'}, resizable: true},
    // {label: '当前温度', prop: 'temperatureChip', width: 180, query: false, type: 'text', resizable: true},
    {label: '创建时间', prop: 'createTime', query: false, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDateTime(val)}},
    {label: '更新时间', prop: 'updateTime', query: false, sortable: 'custom', type: 'datetime', resizable: true, conf: {format: (val: any) => u.fmt.fmtDateTime(val)}},
    {
      label: '操作', prop: 'action', type: 'render', width: 180, align: 'center', fixed: 'right',
      render: (h: any, row: any) => {
        return (
            h('div', null, [
              proxy.$auth('washDevice.modify') ?
                  h(ElButton, {
                    type: 'warning',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      handleRowClick('edit', row)
                    }
                  }, () => '编辑') : '',
              proxy.$auth('washDevice.modify') ?
                  h(ElButton, {
                    type: 'primary',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      // handleRowClick('edit', row)
                    }
                  }, () => '结算') : '',
              proxy.$auth('washDevice.remove') ?
                  h(ElButton, {
                    type: 'danger',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      handleRowDelete(row)
                    }
                  }, () => '删除') : '',
            ])
        )
      }
    }
  ],
})


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

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

  state.exportConfig = {url: exportUrl,}

})

onMounted(() => {
  loadData();

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

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

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


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

// 配置详情页
const handleRowConfigClick = (type: string, row: any) => {
  device_config_dialog_ref.value.open(type, row);
}

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

const handleBatchDeviceConfig = () => {
  device_config_dialog_ref.value.open(state.chooseDeviceList);
}

const handleChooseDeviceChange = (deviceList) => {
  console.log(deviceList)
  state.chooseDeviceList = deviceList.map(k=>k.id);

}

//endregion


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