<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)"/>
  <DeviceRemoteDialog ref="device_remote_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, ElMessageBox} from 'element-plus'

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


//定义引用
const queryRef = ref();
const device_dialog_ref = ref();
const device_config_dialog_ref = ref();
const device_remote_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: 'sequence', width: 90, query: false, type: 'text', resizable: true},
    {
      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: 'deviceConfigName', width: 120, query: true, type: 'text', resizable: true, fixed: 'left'},
    {label: 'ProductKey', prop: 'productKey', width: 180, query: true, type: 'text', resizable: true},
    {label: 'DeviceName', prop: 'deviceName', 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: 120, 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: 120, query: true, type: 'dict', conf: {range: [{label: '有', value: '1'}, {label: '无', value: '0'}], dataRange: [{label: '有', value: '1'}, {label: '无', value: '0'}]}, resizable: true},
    {label: '是否有水', prop: 'hasWater', width: 120, query: true, type: 'dict', conf: {range: [{label: '有', value: '1'}, {label: '无', value: '0'}], dataRange: [{label: '有', value: '1'}, {label: '无', value: '0'}]}, resizable: true},
    {label: '是否支持PA', prop: 'hasPa', width: 120, query: true, type: 'dict', conf: {range: [{label: '是', value: '1'}, {label: '否', value: '0'}], dataRange: [{label: '是', value: '1'}, {label: '否', value: '0'}]}, 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: 260, align: 'center', fixed: 'right',
      render: (h: any, row: any,rowData:any) => {
        const canRemote = !['sleep', 'maintenance', 'fault'].includes(rowData.state);
        return (
            h('div', null, [
              proxy.$auth('washDevice.modify') ?
                  h(ElButton, {
                    type: 'warning',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      handleRowClick('edit', rowData)
                    }
                  }, () => '编辑') : '',
              proxy.$auth('washDevice.list') ?
                  h(ElButton, {
                    type: 'success',
                    text: true,
                    size: 'small',
                    disabled: !canRemote,
                    onClick: () => {
                      handleRemoteClick(rowData)
                    }
                  }, () => '远程控制') : '',
              proxy.$auth('washDevice.modify') ?
                  h(ElButton, {
                    type: 'primary',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      ElMessageBox.confirm(`确定要对设备「${rowData.shortId}」进行强制结算吗？此操作将强制结束该设备当前未完结的订单。`, '提示', {
                        confirmButtonText: '确定结算',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                        $body(`/washDevice/stopDevice/${rowData.shortId}`).then(() => {
                          Msg.message('结算成功', 'success')
                          loadData(true)
                        })
                      }).catch(() => {})
                    }
                  }, () => '结算') : '',
              proxy.$auth('washDevice.remove') ?
                  h(ElButton, {
                    type: 'danger',
                    text: true,
                    size: 'small',
                    onClick: () => {
                      handleRowDelete(rowData)
                    }
                  }, () => '删除') : '',
            ])
        )
      }
    }
  ],
})


// 监听双向绑定 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")
})


// 将 dict 返回的字符串 "0"/"1" 转为 boolean，避免后端 Boolean 字段反序列化失败
const BOOL_QUERY_FIELDS = ['hasFoam', 'hasWater', 'hasPa']

const normalizeQueryBooleans = (query: Record<string, any>) => {
  BOOL_QUERY_FIELDS.forEach((key) => {
    const v = query[key]
    if (v === undefined || v === null || v === '' || v === -1 || v === '-1') {
      delete query[key]
    } else if (v === '1' || v === 1) {
      query[key] = true
    } else if (v === '0' || v === 0) {
      query[key] = false
    }
  })
  return query
}

//region 方法区
// 初始化表格数据
const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  const query = normalizeQueryBooleans({...state.formQuery, ...state.pageQuery})
  $body(`/washDevice/list`, query).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) => {
  debugger
  device_dialog_ref.value.open(type, row);
};
// 删除点击
const handleRowDelete = (row: any) => {
  Msg.confirm(`此操作将永久删除：『${row.deviceName}』，是否继续?`).then(() => {
    $get(`/washDevice/remove/${row.id}`).then(() => {
      Msg.message("删除成功", 'success')
    }).catch(() => {
      Msg.message("删除失败", 'error')
    })
  });
};

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

const handleRemoteClick = (row: any) => {
  device_remote_dialog_ref.value.open(row);
};

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

}

//endregion


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