<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入统计单元名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="workUnitOptions"
            :props="workUnitProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="日期类型" prop="dateType">
            <el-select v-model="queryParams.dateType" placeholder="请选择日期类型">
              <el-option v-for="item in dateTypeList" :key="item.dateTypeCode" :label="item.dateTypeName" :value="item.dateTypeCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采集日期">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="monitorWorkUnitList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键标识" align="center" prop="objId" v-if="columns[0].visible" />
          <el-table-column label="统计单元编号" align="center" prop="workUnitCode" v-if="columns[1].visible" />
          <el-table-column label="统计单元名称" align="center" prop="workUnitName" v-if="columns[2].visible" />
          <el-table-column label="统计日期" align="center" prop="pointTime" v-if="columns[3].visible" />
          <el-table-column label="分时类型" align="center" prop="priceType" v-if="columns[4].visible" />
          <el-table-column label="耗量(kwh)" align="center" prop="expend" v-if="columns[5].visible" />
          <el-table-column label="价格" align="center" prop="price" v-if="columns[6].visible" />
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { getWorkUnitTrees } from '@/api/ems/base/baseWorkUnit';
import { peaksValleysConsumptionReportList } from '@/api/ems/report/reportPort';
import { parseTime } from '@/utils/ruoyi';

defineOptions({
  name: 'PeaksValleysConsumptionReport'
} as any);

const { proxy } = getCurrentInstance() as any;

const queryForm = ref<any>();
const tree = ref<any>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  parentIds: null,
  parentId: null,
  objId: null,
  monitorCode: null,
  workUnitCode: null,
  monitorStatus: 0,
  monitorType: 1
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  monitorInfoOptions: [],
  workUnitOptions: [],
  workUnitName: undefined,
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 统计计量信息表格数据
  monitorWorkUnitList: [],
  daterangeCollectTime: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    monitorCode: null,
    workUnitCode: null,
    monitorStatus: null,
    monitorType: null,
    dateType: 10
  },
  // 表单参数
  form: createFormData(),
  workUnitProps: {
    children: 'children',
    label: 'label'
  },
  dateTypeList: [
    {
      dateTypeCode: 10,
      dateTypeName: '日'
    },
    {
      dateTypeCode: 7,
      dateTypeName: '月'
    },
    {
      dateTypeCode: 4,
      dateTypeName: '年'
    }
  ],
  columns: [
    {
      key: 0,
      label: `主键标识`,
      visible: false
    },
    {
      key: 1,
      label: `统计单元编号`,
      visible: true
    },
    {
      key: 2,
      label: `统计单元名称`,
      visible: true
    },
    {
      key: 3,
      label: `统计日期`,
      visible: true
    },
    {
      key: 4,
      label: `分时类型`,
      visible: true
    },
    {
      key: 5,
      label: `仪表值(kwh)`,
      visible: true
    },
    {
      key: 6,
      label: `价格`,
      visible: true
    }
  ]
} as any);

const {
  columns,
  dateTypeList,
  daterangeCollectTime,
  form,
  ids,
  loading,
  monitorInfoOptions,
  monitorWorkUnitList,
  multiple,
  open,
  queryParams,
  showSearch,
  single,
  title,
  total,
  workUnitName,
  workUnitOptions,
  workUnitProps
} = toRefs(state);

const workUnitOptionsNormalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id2: node.workUnitCode,
    label2: node.workUnitName,
    children2: node.children
  };
};

const getWorkUnitTrees = () => {
  getWorkUnitTrees().then((response) => {
    workUnitOptions.value = [];
    workUnitOptions.value = JSON.parse(JSON.stringify(response.data).replaceAll('id', 'id2').replaceAll('code', 'id'));
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const handleNodeClick = (data) => {
  queryParams.value.workUnitCode = data.id;
  handleQuery();
};

const getList = () => {
  loading.value = true;
  queryParams.value.beginCollectTime = null;
  queryParams.value.endCollectTime = null;
  if (daterangeCollectTime.value != null && daterangeCollectTime.value !== '') {
    queryParams.value.beginCollectTime = daterangeCollectTime.value[0];
    queryParams.value.endCollectTime = daterangeCollectTime.value[1];
  }
  peaksValleysConsumptionReportList(queryParams.value).then((response) => {
    monitorWorkUnitList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    parentIds: null,
    parentId: null,
    objId: null,
    monitorCode: null,
    workUnitCode: null,
    monitorStatus: 0,
    monitorType: 1
  };
  form.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryForm.value?.resetFields();
  queryParams.value.workUnitCode = null;
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.objId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleExport = () => {
  proxy?.download(
    'ems/report/peaksValleysConsumptionReportList/export',
    {
      ...queryParams.value
    },
    `峰平谷耗量报表_${new Date().getTime()}.xlsx`
  );
};

watch(workUnitName, (val) => {
  tree.value.filter(val);
});

onMounted(() => {
  const nowDate = parseTime(new Date(), '{y}-{m}-{d}');
  daterangeCollectTime.value[0] = nowDate;
  daterangeCollectTime.value[1] = nowDate;
  getList();
  getWorkUnitTrees();
});
</script>
