<template>
  <div class="devicemenu">
    <el-space wrap :size="10">
      <el-button type="primary" @click="handleEdit(state.addFormData)" :disabled="desc.code == ''">新增</el-button>
      <el-input v-model="state.SearchVal" placeholder="筛选" style="width: 180px" size="small" />
      <!-- <el-select v-model="state.selectModel" class="mr10" style="width: 180px"  placeholder="全部" >
     <el-option v-for="item in state.modelList" :key="item" :value="item" :label="item"></el-option>
    </el-select>
    <el-select v-model="state.selectPoint" class="mr10" style="width: 100px"  placeholder="全部" >
      <el-option key="1" label="全部" value=""></el-option>
      <el-option key="2" label="遥测" value="AI"></el-option>
      <el-option key="3" label="遥调" value="MI"></el-option>
      <el-option key="4" label="计算" value="CI"></el-option>
    </el-select> -->
      <el-button type="primary" @click="search">查询</el-button>
      <el-upload class="upload-demo" :disabled="desc.code == ''" action="/sharding/device/input" :show-file-list="false"
        :on-success="handleSuccess" :on-progress="handleProgress" :on-error="handleError">
        <el-button :disabled="desc.code == ''" type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="export2Excel" :disabled="desc.code == ''">导出</el-button>
    </el-space>
  </div>
  <el-table :data="state.pointTableData" stripe style="width: 100%" height="65vh">
    <el-table-column type="index" width="50" />
    <el-table-column prop="metriccode" label="测点编码"></el-table-column>
    <el-table-column label="名称">
      <template #default="scope">
        <el-popover placement="right" :width="260" trigger="click">
          <template #reference>
            <el-button type="text" size="small">{{ scope.row.name }}</el-button>
          </template>
          <el-table :data="scope.row.deviceModelMetrics" max-height="400px">
            <el-table-column property="devicemodel" label="机型" align="center"></el-table-column>
            <el-table-column property="uniformcode" label="统一编码" align="center"></el-table-column>
            <el-table-column property="multiplier" label="倍率" align="center"></el-table-column>
          </el-table>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column prop="unitname" label="单位"></el-table-column>
    <el-table-column prop="categorydata" label="测点类型"></el-table-column>
    <el-table-column prop="categorysci" label="物理类型"></el-table-column>
    <el-table-column prop="categorysci" label="数据类型"></el-table-column>
    <el-table-column prop="description" label="描述"></el-table-column>
    <el-table-column label="操作" width="180" align="center">
      <template #default="scope">
        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="text" icon="el-icon-delete" style="color: red" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination">
    <el-pagination background layout="total, prev, pager, next" hide-on-single-page :current-page="query.page"
      :page-size="query.limit" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
  </div>
  <!-- 传感点编辑弹出框 -->
  <el-dialog v-model="editVisible" width="40%">
    <el-form :model="editFormData" label-width="80px">
      <el-form-item label="编码">
        <el-input v-model="editFormData.metriccode"></el-input>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="名称">
            <el-input v-model="editFormData.name"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="英文名称">
            <el-input v-model="editFormData.enname"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="标准单位">
            <el-input v-model="editFormData.unitname"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="单位名称">
            <el-input v-model="editFormData.unitnamecn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述">
        <el-input v-model="editFormData.description" :rows="3" type="textarea" clearable></el-input>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="数据类型">
            <el-select v-model="editFormData.categorydata" placeholder="Select">
              <el-option v-for="item in state.categorydataoptions" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结构">
            <el-cascader v-model="editFormData.structurecode" :options="cascaderdata"
              :props="{ checkStrictly: true, emitPath: false }" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="物理类型">
            <el-input v-model="editFormData.categorysci"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统分类">
            <el-input v-model="editFormData.categorysys"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="适配机型" class="deviceModelClass">
        <el-select v-model="state.deviceModelSel" style="margin-right: 20px" placeholder="新增机型" size="mini">
          <el-option v-for="item in state.deviceModel" :key="item.code" :label="item.code" :value="item.code">
          </el-option>
        </el-select>
        <el-button v-show="state.deviceModelSel != ''" size="mini" type="primary" @click="deviceModelAdd()">新增机型
        </el-button>
        <el-table :data="editFormData.deviceModelMetrics" style="width: 100%;margin-top: 10px;" max-height="200px">
          <el-table-column prop="devicemodel" label="机型" />
          <el-table-column label="倍率">
            <template #default="scope">
              <el-input v-model="scope.row.multiplier" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="统一编码">
            <template #default="scope">
              <el-input v-model="scope.row.uniformcode" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, inject, reactive, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { point, metrics, delmetrics, device_list,getStationinfo } from "/@/api/api.js";
import { outExportExcel } from "/@/utils/exportExcel"; //引入文件
onMounted(() => {
  getPoint(desc.value);
  getDeviceModel();
  getequipmentmodel_list()
});
let editFormData = ref({});
let editVisible = ref(false); //传感点
let desc = inject("desc");
let treeId = inject("treeId");
let cascaderdata = inject("cascaderdata");
watch(
  () => treeId,
  (newV, old) => {
    state.addFormData.structurecode = desc.value.code;
    getPoint(desc.value);
  },
  {
    deep: true,
  }
);
let state = reactive({
  pointTableData: "",
  SearchVal: "",
  selectPoint: "",
  selectModel: "",
  modelList: [],
  categorydataoptions: ['AI', 'DI', 'CI'],
  addFormData: {
    categorydata: "AI",
    categoryres1: null,
    categoryres2: null,
    categoryres3: null,
    categoryres4: null,
    categoryres5: null,
    categorysci: null,
    categorysys: null,
    description: null,
    deviceid: "windturbine",
    enname: null,
    id: null,
    metriccode: "",
    name: "",
    structurecode: "101010205",
    unitname: null,
    unitnamecn: null,
    deviceModelMetrics: [],
  },
});
const query = reactive({
  page: 1,
  limit: 10,
});
let pageTotal = ref(0);
const search = async () => {
  getPoint(desc.value)
}
// getPoint
const getPoint = async (node) => {
  const res = await point(node.code, query.page, query.limit, state.selectPoint, state.SearchVal, 'windturbine', state.selectModel);
  console.warn(res);
  pageTotal.value = res.total;
  state.pointTableData = res.records?.sort((a, b) => {
    return a.id - b.id;
  });
};
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await getStationinfo('');
    let arr = []
    data.forEach(e => {
      arr.push(...e.modelList)
    });
    state.modelList = [...new Set(arr)]
};
// 测点 编辑
const handleEdit = (row) => {
  console.warn(row);
  if (!row.deviceModelMetrics) {
    row.deviceModelMetrics = [];
  }
  editFormData.value = row;
  editVisible.value = true;
};
//测点 add
const postmetrics = async () => {
  console.warn(editFormData.value);
  const res = await metrics(editFormData.value);
  console.warn(res);
  if (res.status == 20000) {
    ElMessage.success(`操作成功!`);
    editVisible.value = false;
  } else {
    ElMessage.success(res.msg);
  }
  getPoint(desc.value);
};
// 保存编辑
const saveEdit = async () => {
  postmetrics();
};
// 测点 删除
const handleDelete = (row) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      console.warn(row);
      const res = await delmetrics(row.id);
      console.warn(res);
      if (res == 1) {
        ElMessage.success(`删除成功!`);
      } else {
        ElMessage.success("删除失败");
      }
      getPoint(desc.value);
    })
    .catch(() => { });
};

//deviceModelAdd 新增机型
const deviceModelAdd = async () => {
  if (state.deviceModelSel == "") return;
  console.warn();
  let obj = {
    deviceid: editFormData.value.deviceid,
    devicemodel: state.deviceModelSel,
    id: null,
    metriccode: editFormData.value.metriccode,
    multiplier: 0,
    uniformcode: "",
  };
  editFormData.value.deviceModelMetrics.push(obj);
};
//getDeviceModel
const getDeviceModel = async () => {
  const res = await device_list();
  state.deviceModel = res;
  console.warn(res);
};

// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getPoint(desc.value);
};

// 批量导入
const handleSuccess = (response, file, fileList) => {
  console.warn(response, file, fileList);
  ElMessage.success("导入成功!");
  getPoint(desc.value);
};
const handleProgress = (response, file, fileList) => { };
const handleError = (response, file, fileList) => {
  ElMessage.success("导入失败!");
};

// 批量导出
const export2Excel = async () => {
  const tableData = await point(desc.value.code, 1, 99999999, state.selectPoint, state.SearchVal, 'windturbine', state.selectModel);
  ElMessage.success(`导出成功!`);
  const tableHeader = [
    "上级结构编码",
    "测点编码",
    "名称",
    "英文名称",
    "单位",
    "测点类型",
    "物理类型",
    "描述",
  ];
  const tableKey = [
    "structurecode",
    "metriccode",
    "name",
    "enname",
    "unitname",
    "categorydata",
    "categorysci",
    "description",
  ];
  outExportExcel(tableHeader, tableKey, tableData.records, "测点导出excel");
};
</script>
<style lang="scss" scoped>
.devicemenu {
  margin-bottom: 10px;
}
</style>