<template>
  <div class="app-container survey-point-data-index">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="queryParams.projectId" filterable placeholder="请选择项目" clearable @change="doQuerySub">
          <el-option v-for="(item, index) in projectOptions" :key="index" :label="item.projectName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总包单位" prop="subDeptId">
        <el-select v-model="queryParams.subDeptId" filterable placeholder="请选择总包单位" clearable @change="doQueryPitEL">
          <el-option v-for="(item, index) in depts" :key="index" :label="item.deptName" :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="监测项" prop="meId">
        <el-select v-model="queryParams.meId" filterable placeholder="请选择监测项" clearable @change="doQueryPitSps">
          <el-option v-for="(item, index) in pitEls" :key="index" :label="item.name" :value="item.srvId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="测点" prop="spId">
        <el-select v-model="queryParams.spId" filterable placeholder="请选择监测项" clearable>
          <el-option v-for="(item, index) in pitSps" :key="index" :label="item.name" :value="item.spId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="查询日期" prop="spId">
        <el-date-picker v-model="queryParams.selDate" type="daterange" align="right" unlink-panels 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" v-if="1 == 2">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['device:pitData:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['device:pitData:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['device:pitData:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['device:pitData:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pitDataList" height="50vh" class="dt-main">
      <el-table-column label="测点" align="center" prop="spName" />
      <template v-if="queryParams.meId == 22">
        <el-table-column label="X方向位移(mm)" align="center" prop="displace">
          <template slot-scope="scope">{{ scope.row.displace.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="X方向累计变化量(mm)" align="center" prop="totalize">
          <template slot-scope="scope">{{ scope.row.totalize.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="X方向单次变化量(mm)" align="center" prop="variation">
          <template slot-scope="scope">{{ scope.row.variation.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="X方向变化速率(mm/d)" align="center" prop="changeRate">
          <template slot-scope="scope">{{ scope.row.changeRate.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="Y方向位移(mm)" align="center" prop="displace2">
          <template slot-scope="scope">{{ scope.row.displace2.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="Y方向累计变化量(mm)" align="center" prop="totalize2">
          <template slot-scope="scope">{{ scope.row.totalize2.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="Y方向单次变化量(mm)" align="center" prop="variation2">
          <template slot-scope="scope">{{ scope.row.variation2.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="Y方向变化速率(mm/d)" align="center" prop="changeRate2">
          <template slot-scope="scope">{{ scope.row.changeRate2.toFixed(3) }}</template>
        </el-table-column>
      </template>
      <template v-if="queryParams.meId == 14">
        <el-table-column label="压力(MPa)" align="center" prop="displace">
          <template slot-scope="scope">{{ scope.row.displace.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="累计变化量(MPa)" align="center" prop="totalize">
          <template slot-scope="scope">{{ scope.row.totalize.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="单次变化量(MPa)" align="center" prop="variation">
          <template slot-scope="scope">{{ scope.row.variation.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="变化速率(MPa/d)" align="center" prop="changeRate">
          <template slot-scope="scope">{{ scope.row.changeRate.toFixed(3) }}</template>
        </el-table-column>
      </template>
      <template v-if="queryParams.meId == 3">
        <el-table-column label="水位(m)" align="center" prop="displace">
          <template slot-scope="scope">{{ scope.row.displace.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="累计变化量(mm)" align="center" prop="totalize">
          <template slot-scope="scope">{{ scope.row.totalize.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="单次变化量(mm)" align="center" prop="variation">
          <template slot-scope="scope">{{ scope.row.variation.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column label="变化速率(mm/d)" align="center" prop="changeRate">
          <template slot-scope="scope">{{ scope.row.changeRate.toFixed(3) }}</template>
        </el-table-column>
      </template>
      <el-table-column label="采集时间" align="center" prop="collectTime" />
    </el-table>

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

    <div v-if="chartData && queryParams.meId==22" class="div-chart">
      <el-radio-group v-model="selChart1" class="chart1-group" @change="showChartData(1)">
        <el-radio :label="0" border>X方向位移(mm)</el-radio>
        <el-radio :label="1" border>X方向累计变化量(mm)</el-radio>
        <el-radio :label="2" border>X方向单次变化量(mm)</el-radio>
        <el-radio :label="3" border>X方向变化速率(mm/d)</el-radio>
      </el-radio-group>
      <Chart ref="chart1" :chgOpt="opt=>changeOpt(opt,1)" :key="'c1-'+spId"/>

      <el-radio-group v-model="selChart2" class="chart2-group" @change="showChartData(2)">
        <el-radio :label="0" border>Y方向位移(mm)</el-radio>
        <el-radio :label="1" border>Y方向累计变化量(mm)</el-radio>
        <el-radio :label="2" border>Y方向单次变化量(mm)</el-radio>
        <el-radio :label="3" border>Y方向变化速率(mm/d)</el-radio>
      </el-radio-group>
      <Chart ref="chart2" :chgOpt="opt=>changeOpt(opt,2)" :key="'c2-'+spId"/>
    </div>
  </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 Chart from '@/components/Chart'
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,
      selChart1:0,
      selChart2:0,
    };
  },
  created() {
    //let dt1 = this.$dt((+new Date()) - 30 * 24 * 3600 * 1000);
    //let dt2 = this.$dt(new Date());
    //this.queryParams.selDate = [dt1, dt2];
    this.getList();
    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() {
      let prjId = this.queryParams.projectId;
      let tmps = this.prjDept2 && this.prjDept2[prjId] ? this.prjDept2[prjId] || [] : [];
      if (tmps.length > 0 || !prjId) {
        this.depts = tmps;
        if (tmps.length >= 1) {
          this.queryParams.subDeptId = tmps[0].deptId;
        } else {
          this.queryParams.subDeptId = '';
          this.pitEls=[];
          this.pitSps=[];
          this.queryParams.meId="";
          this.queryParams.spId="";
        }
        this.doQueryPitEL();
        return;
      }
      this.$api.publics.queryUnitList({
        projectId: prjId,
        unitTypes: "2".split(","),
      }).then((d) => {
        let objs = d.rows || [];
        if (!this.prjDept2) {
          this.prjDept2 = {};
        }
        this.prjDept2[prjId] = objs;
        this.depts = objs;
        if (objs.length >= 1) {
          this.queryParams.subDeptId = objs[0].deptId;
        } else {
          this.queryParams.subDeptId = '';
        }
        this.doQueryPitEL();
      });
    },
    doQueryPitEL() {
      if (!this.queryParams.subDeptId) {
        this.pitEls = [];
        this.queryParams.meId = "";
        this.pitSps=[];
        this.queryParams.spId="";
        this.getList();
        return;
      }
      listPitElement({
        pageNum: 1,
        pageSize: 100,
        projectId: this.queryParams.projectId,
        subDeptId: this.queryParams.subDeptId
      }).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;
      }
      this.$api.publics.getMyProjectList({}).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>