<template>
  <div class="p-2">
    <el-row :gutter="28">
      <el-col :span="4.3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入计量设备名称"
            clearable

            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="monitorInfoOptions"
            :props="monitorProps"
            :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="queryFormRef" :inline="true" v-show="showSearch"
                 label-width="100px"
        >
          <!--          <el-form-item label="计量设备编号" prop="monitorCode">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.monitorCode"-->
          <!--              placeholder="请输入计量设备编号"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="采集时间">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 340px"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="记录时间">
            <el-date-picker
              v-model="daterangeRecordTime"
              style="width: 340px"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="采集方式" prop="collectType">
            <el-select v-model="queryParams.collectType" placeholder="请选择采集方式" clearable>
              <el-option
                v-for="dict in collect_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

<!--        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"

              @click="handleAdd"
              v-hasPermi="['ems:record:recordDnbInstant:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"

              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['ems:record:recordDnbInstant:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"

              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['ems:record:recordDnbInstant:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"

              @click="handleExport"
              v-hasPermi="['ems:record:recordDnbInstant:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>-->

        <el-table v-loading="loading" :data="recordDnbInstantList" @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="monitorCode" v-if="columns[1].visible" width="100"/>
          <el-table-column label="计量设备名称" align="center" prop="monitorName" v-if="columns[15].visible" width="120"/>
          <el-table-column label="采集时间" align="center" prop="collectTime" width="180" v-if="columns[2].visible">
            <template #default="scope">
              <span>{{ parseTime(scope.row.collectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="A项电压" align="center" prop="va" v-if="columns[3].visible"/>
          <el-table-column label="B项电压" align="center" prop="vb" v-if="columns[4].visible"/>
          <el-table-column label="C项电压" align="center" prop="vc" v-if="columns[5].visible"/>
          <el-table-column label="A项电流" align="center" prop="ia" v-if="columns[6].visible"/>
          <el-table-column label="B项电流" align="center" prop="ib" v-if="columns[7].visible"/>
          <el-table-column label="C项电流" align="center" prop="ic" v-if="columns[8].visible"/>
          <el-table-column label="功率因数" align="center" prop="glys" v-if="columns[10].visible"/>
          <el-table-column label="正向有功" align="center" prop="zxyg" v-if="columns[11].visible"/>
          <el-table-column label="有功功率" align="center" prop="activePower" v-if="columns[12].visible"/>
          <el-table-column label="无功功率" align="center" prop="reactivePower" v-if="columns[13].visible"/>
          <el-table-column label="记录时间" align="center" prop="recordTime" width="180" v-if="columns[9].visible">
            <template #default="scope">
              <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采集方式" align="center" prop="collectType" v-if="columns[14].visible">
            <template #default="scope">
              <dict-tag :options="collect_type" :value="scope.row.collectType"/>
            </template>
          </el-table-column>
          <!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
          <!--            <template #default="scope">-->
          <!--              <el-button-->
          <!--               -->
          <!--                type="text"-->
          <!--                icon="Edit"-->
          <!--                @click="handleUpdate(scope.row)"-->
          <!--                v-hasPermi="['ems:record:recordDnbInstant:edit']"-->
          <!--              >修改-->
          <!--              </el-button>-->
          <!--              <el-button-->
          <!--               -->
          <!--                type="text"-->
          <!--                icon="Delete"-->
          <!--                @click="handleDelete(scope.row)"-->
          <!--                v-hasPermi="['ems:record:recordDnbInstant:remove']"-->
          <!--              >删除-->
          <!--              </el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </el-col>
    </el-row>


    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电实时数据对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogOpen" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="计量设备名称" prop="monitorCode">
          <treeselect v-model="form.monitorCode" :options="baseMonitorInfoOptions" :normalizer="normalizer"
                      placeholder="请选择计量设备名称"
          />
        </el-form-item>
        <el-form-item label="采集时间" prop="collectTime">
          <el-date-picker clearable
                          v-model="form.collectTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择采集时间"
          >
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="A项电压" prop="va">-->
        <!--          <el-input v-model="form.va" placeholder="请输入A项电压"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="B项电压" prop="vb">-->
        <!--          <el-input v-model="form.vb" placeholder="请输入B项电压"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="C项电压" prop="vc">-->
        <!--          <el-input v-model="form.vc" placeholder="请输入C项电压"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="A项电流" prop="ia">-->
        <!--          <el-input v-model="form.ia" placeholder="请输入A项电流"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="B项电流" prop="ib">-->
        <!--          <el-input v-model="form.ib" placeholder="请输入B项电流"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="C项电流" prop="ic">-->
        <!--          <el-input v-model="form.ic" placeholder="请输入C项电流"/>-->
        <!--        </el-item>-->
        <!--        <el-form-item label="记录时间" prop="recordTime">-->
        <!--          <el-date-picker clearable-->
        <!--                          v-model="form.recordTime"-->
        <!--                          type="datetime"-->
        <!--                          value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--                          placeholder="请选择记录时间"-->
        <!--          >-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="功率因数" prop="glys">-->
        <!--          <el-input v-model="form.glys" placeholder="请输入功率因数"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="正向有功" prop="zxyg">
          <el-input-number v-model="form.zxyg" placeholder="请输入正向有功"/>
        </el-form-item>
        <!--        <el-form-item label="有功功率" prop="activePower">-->
        <!--          <el-input v-model="form.activePower" placeholder="请输入有功功率"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="无功功率" prop="reactivePower">-->
        <!--          <el-input v-model="form.reactivePower" placeholder="请输入无功功率"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="采集方式" prop="collectType">
          <el-radio-group v-model="form.collectType" disabled>
            <el-radio
              v-for="dict in collect_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance, onMounted, watch } from 'vue';
import type { ElFormInstance, FormRules } from 'element-plus';
import { listRecordDnbInstant, getRecordDnbInstant, delRecordDnbInstant, addRecordDnbInstant, updateRecordDnbInstant } from '@/api/ems/record/recordDnbInstant';
import { getMonitorInfoTree, listBaseMonitorInfo } from '@/api/ems/base/baseMonitorInfo';
import type { RecordDnbInstantVO, RecordDnbInstantForm } from '@/api/ems/record/types';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { collect_type } = toRefs<any>(proxy?.useDict('collect_type'));

const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const tree = ref();

const baseMonitorInfoOptions = ref<any[]>([]);
const monitorInfoOptions = ref<any[]>([]);
const workUnitName = ref<string | undefined>(undefined);

const daterangeCollectTime = ref<string[] | null>([] as any);
const daterangeRecordTime = ref<string[] | null>([] as any);

const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const recordDnbInstantList = ref<RecordDnbInstantVO[]>([]);
const dialogTitle = ref('');
const dialogOpen = ref(false);

const monitorProps = { children: 'children', label: 'label' };

const columns = ref([
  { key: 0, label: `主键标识`, visible: false },
  { key: 1, label: `计量设备编号`, visible: true },
  { key: 2, label: `采集时间`, visible: true },
  { key: 3, label: `A项电压`, visible: true },
  { key: 4, label: `B项电压`, visible: true },
  { key: 5, label: `C项电压`, visible: true },
  { key: 6, label: `A项电流`, visible: true },
  { key: 7, label: `B项电流`, visible: true },
  { key: 8, label: `C项电流`, visible: true },
  { key: 9, label: `记录时间`, visible: true },
  { key: 10, label: `功率因数`, visible: true },
  { key: 11, label: `正向有功`, visible: true },
  { key: 12, label: `有功功率`, visible: false },
  { key: 13, label: `无功功率`, visible: false },
  { key: 14, label: `采集方式`, visible: true },
  { key: 15, label: `计量设备名称`, visible: true }
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    monitorCode: null,
    collectTime: null,
    va: null, vb: null, vc: null,
    ia: null, ib: null, ic: null,
    recordTime: null,
    glys: null, zxyg: null,
    activePower: null, reactivePower: null,
    collectType: null
  } as any,
  form: {
    objId: null,
    monitorCode: null,
    collectTime: null,
    va: null, vb: null, vc: null,
    ia: null, ib: null, ic: null,
    recordTime: null,
    glys: null, zxyg: null,
    activePower: null, reactivePower: null,
    collectType: 1
  } as RecordDnbInstantForm
});

const { queryParams, form } = toRefs(data);

const rules = reactive<FormRules>({
  objId: [{ required: true, message: '编号不能为空', trigger: 'blur' }]
});

const normalizer = (node: any) => {
  if (node.children && !node.children.length) delete node.children;
  return { id: node.monitorCode, label: node.monitorName, children: node.children };
};

const getTreeMonitorInfo = () => {
  listBaseMonitorInfo({ monitorType: 2 }).then((response: any) => {
    baseMonitorInfoOptions.value = [];
    const dataRoot: any = { objId: 0, monitorName: '顶级节点', children: [] };
    dataRoot.children = proxy?.handleTree(response.data, 'objId', 'parentId');
    baseMonitorInfoOptions.value.push(dataRoot);
  });
};

const getTreeselect = () => {
  getMonitorInfoTree({ monitorType: 2 }).then((response: any) => {
    monitorInfoOptions.value = response.data;
  });
};

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

const handleNodeClick = (dataNode: any) => {
  (data.queryParams as any).monitorCode = dataNode.code;
  handleQuery();
};

const getList = () => {
  loading.value = true;
  (data.queryParams as any).params = {};
  if (daterangeCollectTime.value?.length) {
    (data.queryParams as any).params['beginCollectTime'] = daterangeCollectTime.value[0];
    (data.queryParams as any).params['endCollectTime'] = daterangeCollectTime.value[1];
  }
  if (daterangeRecordTime.value?.length) {
    (data.queryParams as any).params['beginRecordTime'] = daterangeRecordTime.value[0];
    (data.queryParams as any).params['endRecordTime'] = daterangeRecordTime.value[1];
  }
  listRecordDnbInstant(data.queryParams).then((response: any) => {
    recordDnbInstantList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

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

const reset = () => {
  data.form = {
    objId: null,
    monitorCode: null,
    collectTime: null,
    va: null, vb: null, vc: null,
    ia: null, ib: null, ic: null,
    recordTime: null,
    glys: null, zxyg: null,
    activePower: null, reactivePower: null,
    collectType: 1
  } as any;
  formRef.value?.resetFields();
};

const handleQuery = () => { (data.queryParams as any).pageNum = 1; getList(); };

const resetQuery = () => {
  (data.queryParams as any).monitorCode = null;
  queryFormRef.value?.resetFields();
  handleQuery();
};

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

const handleAdd = () => { reset(); dialogOpen.value = true; dialogTitle.value = '添加电实时数据'; };

const handleUpdate = (row?: any) => {
  reset();
  const objId = row?.objId ?? ids.value;
  getRecordDnbInstant(objId).then((response: any) => {
    data.form = response.data;
    dialogOpen.value = true;
    dialogTitle.value = '修改电实时数据';
  });
};

const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    if ((data.form as any).objId != null) {
      updateRecordDnbInstant(data.form).then(() => {
        proxy?.$modal.msgSuccess('修改成功');
        dialogOpen.value = false;
        getList();
      });
    } else {
      addRecordDnbInstant(data.form).then(() => {
        proxy?.$modal.msgSuccess('新增成功');
        dialogOpen.value = false;
        getList();
      });
    }
  });
};

const handleDelete = (row?: any) => {
  const objIds = row?.objId ?? ids.value;
  proxy?.$modal.confirm('是否确认删除电实时数据编号为\"' + objIds + '\"的数据项？')
    .then(() => delRecordDnbInstant(objIds))
    .then(() => { getList(); proxy?.$modal.msgSuccess('删除成功'); })
    .catch(() => {});
};

const handleExport = () => {
  proxy?.download('ems/record/recordDnbInstant/export', { ...data.queryParams }, `recordDnbInstant_${new Date().getTime()}.xlsx`);
};

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

onMounted(() => {
  const nowDate = parseTime(new Date(), '{y}-{m}-{d}');
  (daterangeCollectTime.value as any)[0] = nowDate + ' 00:00:00';
  (daterangeCollectTime.value as any)[1] = nowDate + ' 23:59:59';
  getTreeselect();
  getTreeMonitorInfo();
  getList();
});
</script>
