<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="监测项" prop="meId">
        <el-select v-model="queryParams.meId" placeholder="请选择监测项" clearable filterable @change="handleQuery">
          <el-option v-for="item in pitEls" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="测点" prop="spId">
        <el-select v-model="queryParams.spId" placeholder="请选择测点" clearable filterable>
          <el-option v-for="item in surveyPoints" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon style="margin-right: 5px">
            <Search />
          </el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon style="margin-right: 5px">
            <Refresh />
          </el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="small" @click="handleAdd" v-hasPermi="['device:pitData:add']">
          <el-icon style="margin-right: 5px">
            <Plus />
          </el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="small" :disabled="single" @click="handleUpdate"
          v-hasPermi="['device:pitData:edit']">
          <el-icon style="margin-right: 5px">
            <Edit />
          </el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="small" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['device:pitData:remove']">
          <el-icon style="margin-right: 5px">
            <Delete />
          </el-icon>删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="small" @click="handleExport" v-hasPermi="['device:pitData:export']">
          <el-icon style="margin-right: 5px">
            <Download />
          </el-icon>导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @update:showSearch="showSearch = $event"
        @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pitDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="监测项" align="center" prop="meName" />
      <el-table-column label="测点" align="center" prop="spName" />
      <el-table-column label="X方向位移(mm)" align="center" prop="displace">
        <template v-slot="scope">{{ scope.row.displace.toFixed(3) }}</template>
      </el-table-column>
      <el-table-column label="X方向累计变化量(mm)" align="center" prop="totalize">
        <template v-slot="scope">{{ scope.row.totalize.toFixed(3) }}</template>
      </el-table-column>
      <el-table-column label="X方向单次变化量(mm)" align="center" prop="variation">
        <template v-slot="scope">{{ scope.row.variation.toFixed(3) }}</template>
      </el-table-column>
      <el-table-column label="X方向变化速率(mm/d)" align="center" prop="changeRate">
        <template v-slot="scope">{{
          scope.row.changeRate.toFixed(3)
          }}</template>
      </el-table-column>
      <el-table-column label="Y方向位移(mm)" align="center" prop="displace2">
        <template v-slot="scope">{{ scope.row.displace2.toFixed(3) }}</template>
      </el-table-column>
      <el-table-column label="Y方向累计变化量(mm)" align="center" prop="totalize2">
        <template v-slot="scope">{{ scope.row.totalize2.toFixed(3) }}</template>
      </el-table-column>
      <el-table-column label="Y方向单次变化量(mm)" align="center" prop="variation2">
        <template v-slot="scope">{{
          scope.row.variation2.toFixed(3)
          }}</template>
      </el-table-column>
      <el-table-column label="Y方向变化速率(mm/d)" align="center" prop="changeRate2">
        <template v-slot="scope">{{
          scope.row.changeRate2.toFixed(3)
          }}</template>
      </el-table-column>
      <el-table-column label="采集时间" align="center" prop="collectTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="small" type="primary" text @click="handleUpdate(scope.row)"
            v-hasPermi="['device:pitData:edit']">
            <el-icon style="margin-right: 3px">
              <Edit />
            </el-icon>修改
          </el-button>
          <el-button size="small" type="danger" text @click="handleDelete(scope.row)"
            v-hasPermi="['device:pitData:remove']">
            <el-icon style="margin-right: 3px">
              <Delete />
            </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改测点数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="监测项" prop="meId">
          <el-select v-model="form.meId" placeholder="请选择监测项" clearable filterable>
            <el-option v-for="item in meas" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测点" prop="spId">
          <el-select v-model="form.spId" placeholder="请选择测点" clearable filterable>
            <el-option v-for="item in surveyPoints" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="X方向位移" prop="displace">
          <el-input v-model="form.displace" placeholder="请输入X方向位移" />
        </el-form-item>
        <el-form-item label="X方向累计变化量" prop="totalize">
          <el-input v-model="form.totalize" placeholder="请输入X方向累计变化量" />
        </el-form-item>
        <el-form-item label="X方向单次变化量" prop="variation">
          <el-input v-model="form.variation" placeholder="请输入X方向单次变化量" />
        </el-form-item>
        <el-form-item label="X方向变化速率" prop="changeRate">
          <el-input v-model="form.changeRate" placeholder="请输入X方向变化速率" />
        </el-form-item>
        <el-form-item label="Y方向位移" prop="displace2">
          <el-input v-model="form.displace2" placeholder="请输入Y方向位移" />
        </el-form-item>
        <el-form-item label="Y方向累计变化量" prop="totalize2">
          <el-input v-model="form.totalize2" placeholder="请输入Y方向累计变化量" />
        </el-form-item>
        <el-form-item label="Y方向单次变化量" prop="variation2">
          <el-input v-model="form.variation2" placeholder="请输入Y方向单次变化量" />
        </el-form-item>
        <el-form-item label="Y方向变化速率" prop="changeRate2">
          <el-input v-model="form.changeRate2" placeholder="请输入Y方向变化速率" />
        </el-form-item>
        <el-form-item label="采集时间" prop="collectTime">
          <el-date-picker clearable v-model="form.collectTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择采集时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPitData,
  getPitData,
  delPitData,
  addPitData,
  updatePitData,
} from "@/api/device/pitData";
import { listPitElement } from "@/api/device/pitElement";
import { listPitSurveyPoint } from "@/api/device/pitSurveyPoint";
import { queryUnitList, findMyProjectList } from "@/api/publics";
import Chart from "@/components/Chart";
import useUserStore from "@/store/modules/user";
export default {
  name: "PitData",
  components: {
    Chart,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测点数据表格数据
      pitDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        subDeptId: null,
        meId: null,
        spId: null,
        selDate: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      projectOptions: [],
      depts: [],
      pitEls: [], //监测项
      pitSps: [], //测点
      chartData: null,
      userStore: null,
      selChart1: 0,
      selChart2: 0,
    };
  },
  created() {
    this.userStore = useUserStore();
    this.queryParams.projectId = this.userStore.currentPrjId;
    this.queryParams.subDeptId = this.userStore.currentComId;
    
    this.doQuerySub();
    this.init();
  },
  computed: {
    spId() {
      return this.queryParams.spId;
    },
  },
  watch: {
    spId(n, o) {
      if (n != o) {
        if (n) {
          let postData = {
            spId: this.queryParams.spId,
            pageNum: this.queryParams.pageNum,
            pageSize: 5000,
          };
          listPitData(postData).then((d) => {
            let tmps = d.rows || [];
            this.chartData = tmps.length > 0 ? tmps : null;
            this.selChart1 = 0;
            this.selChart2 = 0;
            this.showChartData(1);
            this.showChartData(2);
          });
        } else {
          this.chartData = null;
        }
        this.getList();
      }
    },
  },
  methods: {
    doQuerySub() {
      this.pitEls = [];
      this.pitSps = [];
      this.queryParams.meId = "";
      this.queryParams.spId = "";
      this.doQueryPitEL();
    },
    doQueryPitEL() {
      listPitElement({
        pageNum: 1,
        pageSize: 100,
        projectId: this.queryParams.projectId
      }).then((d) => {
        this.pitEls = d.rows || [];
        if (this.pitEls.length > 0) {
          this.queryParams.meId = this.pitEls[0].srvId;
        } else {
          this.queryParams.meId = "";
        }
        this.doQueryPitSps();
      });
    },
    doQueryPitSps() {
      if (!this.queryParams.meId) {
        this.pitSps = [];
        this.queryParams.spId = "";
        this.getList();
        return;
      }
      listPitSurveyPoint({
        pageNum: 1,
        pageSize: 100,
        meId: this.queryParams.meId,
      }).then((d) => {
        this.pitSps = d.rows || [];
        if (this.pitSps.length > 0) {
          this.queryParams.spId = this.pitSps[0].spId;
        } else {
          this.queryParams.spId = "";
        }
        this.getList();
      });
    },
    changeOpt(opt, type) {
      opt = {
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: !0x0,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        dataZoom: [
          {
            type: "slider",
            show: true,
          },
          {
            type: "inside",
          },
        ],
        xAxis: {
          type: "time",
        },
        yAxis: {},
        series: [
          {
            data: this.chartData.map((it) => {
              let tmps = [];
              tmps.push(it.collectTime);
              let data = 0;
              if (type == 1) {
                data = (
                  it[
                  "displace,totalize,variation,changeRate".split(",")[
                  this.selChart1
                  ]
                  ] || 0
                ).toFixed(3);
              } else {
                data = (
                  it[
                  "displace2,totalize2,variation2,changeRate2".split(",")[
                  this.selChart2
                  ]
                  ] || 0
                ).toFixed(3);
              }
              tmps.push(data);
              return tmps;
            }),
            sampling: "max",
            showSymbol: false,
            type: "line",
          },
        ],
      };
      return opt;
    },
    showChartData(type) {
      if (type == 1) {
        if (this.$refs.chart1) {
          this.$refs.chart1.initChart();
        } else {
          setTimeout(() => {
            this.showChartData(1);
          }, 400);
        }
      }
      if (type == 2) {
        if (this.$refs.chart2) {
          this.$refs.chart2.initChart();
        } else {
          setTimeout(() => {
            this.showChartData(2);
          }, 400);
        }
      }
    },
    init() {
      if (this.projectOptions && this.projectOptions.length > 0) {
        return;
      }
      findMyProjectList({}).then((response) => {
        this.projectOptions = response.rows;
      });
    },
    /** 查询测点数据列表 */
    getList() {
      if (!this.queryParams.spId) {
        this.pitDataList = [];
        this.total = 0;
        this.loading = false;
        return;
      }
      this.loading = true;
      let postData = {
        spId: this.queryParams.spId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
      };
      let selDate = this.queryParams.selDate;
      if (selDate && selDate.length > 0) {
        postData.createTime = this.$dt(selDate[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        if (selDate.length > 1) {
          postData.updateTime = this.$dt(selDate[1]).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        }
      }
      listPitData(postData).then((response) => {
        this.pitDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cfgId: null,
        dataType: null,
        dataId: null,
        spId: null,
        spName: null,
        collectTime: null,
        changeRate: null,
        changeRate2: null,
        displace: null,
        displace2: null,
        totalize: null,
        totalize2: null,
        variation: null,
        variation2: null,
        state: null,
        remark: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加测点数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPitData(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改测点数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updatePitData(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPitData(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除测点数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPitData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/pitData/export",
        {
          ...this.queryParams,
        },
        `pitData_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
.survey-point-data-index {
  .el-table {
    max-height: 50vh;
    height: unset !important;

    .el-table__body-wrapper {
      height: auto !important;
      max-height: 40vh !important;
    }
  }

  .pagination-container {
    height: 50px !important;
  }

  .div-chart {
    padding-top: 10px;

    .chart1-group {
      .el-radio {
        margin-right: 0px;
      }
    }

    .chart1-group {
      margin-top: 10px;

      .el-radio {
        margin-right: 0px;
      }
    }
  }
}
</style>