<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <!-- 新增 -->
      <el-button type="primary" @click="addFn" size="medium">{{
        $t('message.highModulus.add')
      }}</el-button>
    </div>
    <div class="table_wrap whiteBlock">
      <!-- 测量点名称 -->
      <el-table :data="tableData" class="tables">
        <el-table-column
          prop="measurePointName"
          :label="$t('message.highModulus.pointName')"
        >
        </el-table-column>
        <!-- 测量点编号 -->
        <el-table-column
          prop="measurePointNumber"
          :label="$t('message.highModulus.pointNo')"
        >
        </el-table-column>
        <!-- 采集仪编号 -->
        <el-table-column
          prop="acquisitionInstrumentNumber"
          :label="$t('message.highModulus.devNo')"
        >
        </el-table-column>
        <el-table-column prop="enterpriseName" label="分包单位" align="center">
          <template slot-scope="scope">{{ scope.row.enterpriseName || '-' }}</template>
        </el-table-column>
        <!-- 报警状态 -->
        <el-table-column
          prop="alarmState"
          :label="$t('message.highModulus.alarmStatus')"
          :formatter="formatAlarmState"
        >
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          :label="$t('message.highModulus.actions')"
          align="center"
          width="450"
        >
          <template slot-scope="scope">
            <div class="tableBtns">
              <div @click="showDevManage(scope.row)" class="operationText">
                <!-- <img src="@/assets/images/icon-edit.png" width="15px" height="15px"/> -->
                <span>
                  <!-- 设备管理 -->
                  {{ $t('message.highModulus.devManage') }}
                </span>
              </div>
              <div @click="showRealTime(scope.row)" class="operationText">
                <!-- <img src="@/assets/images/icon-edit.png" width="15px" height="15px"/> -->
                <span>
                  <!-- 实时数据 -->
                  {{ $t('message.highModulus.realData') }}
                </span>
              </div>
              <div @click="editFn(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-edit.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t('message.alarmValueSet.edit') }}</span>
              </div>
              <div @click="deleteFn(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-delete.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t('message.alarmValueSet.delete') }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(pageTotal)"
        background
      ></el-pagination>
    </div>
    <!-- '新增':'编辑' -->
    <el-dialog
      :title="
        isAdd ? $t('message.highModulus.add') : $t('message.highModulus.edit')
      "
      :visible.sync="dialogVisible"
      width="667px"
      :modal-append-to-body="false"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          :model="ruleForm"
          :rules="$t('message.highModulus.rules')"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 测量点名称 -->
          <el-form-item
            :label="$t('message.highModulus.pointName')"
            prop="measurePointName"
          >
            <el-input
              v-model="ruleForm.measurePointName"
              :placeholder="$t('message.highModulus.placeholderText')"
            ></el-input>
          </el-form-item>
          <!-- 测量点编号 -->
          <el-form-item
            :label="$t('message.highModulus.pointNo')"
            prop="measurePointNumber"
          >
            <el-input
              type="number"
              v-model="ruleForm.measurePointNumber"
              :placeholder="$t('message.highModulus.placeholderText')"
              :disabled="!isAdd"
            ></el-input>
          </el-form-item>
          <!-- 采集仪编号 -->
          <el-form-item
            :label="$t('message.highModulus.devNo')"
            prop="acquisitionInstrumentNumber"
          >
            <el-input
              v-model="ruleForm.acquisitionInstrumentNumber"
              :placeholder="$t('message.highModulus.placeholderText')"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分包单位"
            prop="enterpriseIds"
          >
          <el-select v-model="ruleForm.enterpriseIds" multiple filterable placeholder="请选择企业">
            <el-option :label="item.enterpriseName" :value="item.id"
              v-for="(item, index) in enterpriseList" :key="index">
            </el-option>
          </el-select>
          </el-form-item>
          <!-- 预警设置 -->
          <el-form-item
            :label="$t('message.highModulus.warningConfig')"
            prop="test"
          >
          </el-form-item>
          <el-table
            style="min-height: auto"
            :data="ruleForm.thresholdList"
            class="tables"
          >
            <!-- 对象 -->
            <el-table-column
              prop="type"
              :label="$t('message.highModulus.obj')"
              :formatter="formatType"
            >
            </el-table-column>
            <!-- 预警值 -->
            <el-table-column
              prop="warningValue"
              :label="$t('message.highModulus.warningNum')"
              width="180"
            >
              <template slot-scope="scope">
                <el-input
                  size="medium"
                  v-model="scope.row.warningValue"
                  onkeyup="value=value.match(/\d+\.?\d{0,2}/)"
                  onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
                  maxlength="9"
                ></el-input>
              </template>
            </el-table-column>
            <!-- 报警值 -->
            <el-table-column
              prop="alarmValue"
              :label="$t('message.highModulus.alarmNum')"
            >
              <template slot-scope="scope">
                <el-input
                  onkeyup="value=value.match(/\d+\.?\d{0,2}/)"
                  onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
                  maxlength="9"
                  size="medium"
                  v-model="scope.row.alarmValue"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- 取 消 -->
        <el-button size="medium" @click="dialogVisible = false">{{
          $t('message.highModulus.cancel')
        }}</el-button>
        <!-- 确 定 -->
        <el-button
          size="medium"
          type="primary"
          @click="submitForm('ruleForm')"
          >{{ $t('message.highModulus.confirm') }}</el-button
        >
      </span>
    </el-dialog>
    <!-- 实时数据 -->
    <el-dialog
      :title="
        ruleForm.measurePointName + ' - ' + $t('message.highModulus.realData')
      "
      :visible.sync="dialogRealTime"
      width="867px"
      :modal-append-to-body="false"
    >
      <div class="dialog_content">
        <div class="filterBox">
          <!-- <el-select
            size="medium"
            :placeholder="$t('message.highModulus.realData')"
            v-model="filterForm.alarmState"
          >
            <el-option
              v-for="(item, index) in $t(
                'message.highModulus.placeholderText2'
              )"
              :key="index"
              :value="index + 1"
              :label="item"
            ></el-option>
          </el-select> -->
          <el-date-picker
            size="medium"
            v-model="daterange"
            type="daterange"
            :range-separator="$t('message.highModulus.to')"
            :start-placeholder="$t('message.highModulus.startTime')"
            :end-placeholder="$t('message.highModulus.endTime')"
            value-format="yyyy-MM-dd"
            @change="changeDate"
            style="width: 240px; margin: 0 15px"
          >
          </el-date-picker>
          <!-- 查询 -->
          <el-button type="primary" size="medium" @click="loadRealTimeData">{{
            $t('message.highModulus.search')
          }}</el-button>
          <!-- 刷新 -->
          <el-button type="warning" size="medium" @click="refreshRealTimeFn">{{
            $t('message.highModulus.refresh')
          }}</el-button>
        </div>
        <el-table :data="realTimeList" class="tables">
          <!-- 立杆轴力 -->
          <el-table-column
            prop="poleAxialForce"
            label="立杆轴力(N)"
          >
          </el-table-column>
          <!-- 水平位移 -->
          <el-table-column
            prop="horizontalDisplacement"
            label="水平位移(mm)"
          >
          </el-table-column>
          <!-- 模板沉降 -->
          <el-table-column
            prop="formworkSettlement"
            label="模板沉降(mm)"
          >
          </el-table-column>
          <!-- 立杆倾斜 -->
          <el-table-column
            prop="poleTilt"
            label="立杆倾斜(°)"
          >
          </el-table-column>
          <!-- 地基沉降 -->
          <el-table-column
            prop="foundationSettlement"
            label="地基沉降(mm)"
          >
          </el-table-column>
          <!-- 测量时间 -->
          <el-table-column
            prop="collectTime"
            :label="$t('message.highModulus.measureTime')"
            width="200"
          >
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagerBox"
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="filterForm.pageNo"
          :page-sizes="$store.state.PAGESIZRS"
          :page-size="filterForm.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="Number(pageTotal2)"
          background
        ></el-pagination>
      </div>
    </el-dialog>
    <!-- 设备管理 -->
    <el-dialog
      :title="
        ruleForm.measurePointName + ' - ' + $t('message.highModulus.devManage')
      "
      :visible.sync="dialogDev"
      width="867px"
      :modal-append-to-body="false"
    >
      <div class="dialog_content">
        <div class="filterBox">
          <!-- 新增设备 -->
          <el-button type="primary" size="medium" @click="addDevFn">{{
            $t('message.highModulus.addDev')
          }}</el-button>
        </div>
        <el-table :data="devList" class="tables">
          <!-- 设备名称 -->
          <el-table-column
            prop="deviceName"
            align="center"
            :label="$t('message.highModulus.devName')"
          >
            <template slot-scope="scope">
              <el-input
                size="medium"
                v-if="scope.row.devOpType == 1 || scope.row.devOpType == 2"
                placeholder="请输入"
                v-model="scope.row.deviceName"
              ></el-input>
              <span v-else>{{ scope.row.deviceName }}</span>
            </template>
          </el-table-column>
          <!-- 采集仪编号 -->
          <el-table-column
            prop="deviceSn"
            align="center"
            :label="$t('message.highModulus.devNo')"
          >
            <template slot-scope="scope">
              <el-input
                size="medium"
                v-if="scope.row.devOpType == 1 || scope.row.devOpType == 2"
                placeholder="请输入"
                v-model="scope.row.deviceSn"
                @input="handleInput"
              ></el-input>
              <span v-else>{{ scope.row.deviceSn }}</span>
            </template>
          </el-table-column>
          <!-- 传感器类型 -->
          <el-table-column
            prop="deviceType"
            align="center"
            :label="$t('message.highModulus.deviceType')"
          >
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.devOpType == 1 || scope.row.devOpType == 2"
                size="medium"
                placeholder="请选择类型"
                v-model="scope.row.deviceType"
              >
                <el-option
                  v-for="(item, index) in $t(
                    'message.highModulus.monitorTypeArr'
                  )"
                  :key="index"
                  :value="index + 1"
                  :label="item"
                ></el-option>
              </el-select>
              <span v-else>{{
                $t('message.highModulus.monitorTypeArr')[
                  scope.row.deviceType - 1
                ]
              }}</span>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column
            prop="pressure"
            align="center"
            :label="$t('message.highModulus.actions')"
          >
            <template slot-scope="scope">
              <div
                class="tableBtns"
                v-if="scope.row.devOpType == 1 || scope.row.devOpType == 2"
              >
                <!-- <div class="operationText" @click="saveDevInfo(scope.row)">保存</div> -->
                <!-- 保存 -->
                <el-button
                  size="medium"
                  type="text"
                  @click="saveDevInfo(scope.row)"
                  >{{ $t('message.highModulus.save') }}</el-button
                >
                <el-button
                  size="medium"
                  type="text"
                  @click="canselDevInfo(scope.row, scope.$index)"
                  >取消</el-button
                >
              </div>
              <div class="tableBtns" v-else>
                <div
                  @click="editDevFn(scope.row, scope.$index)"
                  class="operationText"
                >
                  <img
                    src="@/assets/images/icon-edit.png"
                    width="15px"
                    height="15px"
                  />
                  <span>{{ $t('message.alarmValueSet.edit') }}</span>
                </div>
                <div @click="deleteDevFn(scope.row)" class="operationText">
                  <img
                    src="@/assets/images/icon-delete.png"
                    width="15px"
                    height="15px"
                  />
                  <span>{{ $t('message.alarmValueSet.delete') }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  highFormworkMeasurePointAddApi,
  highFormworkMeasurePointEditApi,
  highFormworkMeasurePointDeleteApi,
  highFormworkMeasurePointListApi,
  highFormworkMeasurePointDetailApi,
  highFormworkMeasureCurrentDataApi,
  highFormworkMeasureDeviceAddApi,
  highFormworkMeasureDeviceEditApi,
  highFormworkMeasureDeviceDeleteApi,
  highFormworkMeasureDeviceListApi
} from '@/assets/js/api/highModulus.js'
import { getEnterpriseInfoListApi } from "@/assets/js/api/specialWork";
export default {
  data() {
    return {
      enterpriseList: [],
      tableData: [],
      pageTotal: 0,
      pageNo: 1,
      pageSize: 10,
      pageTotal2: 0,
      dialogVisible: false,
      ruleForm: {
        enterpriseIds: [],
        acquisitionInstrumentNumber: '',
        measurePointName: '',
        measurePointNumber: '',
        projectSn: '',
        thresholdList: [
          {
            alarmValue: '',
            type: 1,
            warningValue: ''
          },
          {
            alarmValue: '',
            type: 2,
            warningValue: ''
          },
          {
            alarmValue: '',
            type: 3,
            warningValue: ''
          },
          {
            alarmValue: '',
            type: 4,
            warningValue: ''
          },
          {
            alarmValue: '',
            type: 5,
            warningValue: ''
          }
        ]
      },
      rules: {
        measurePointName: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        measurePointNumber: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        acquisitionInstrumentNumber: [
          { required: true, message: '必填', trigger: 'blur' }
        ]
      },
      isAdd: true,
      alarmType: [
        '电量（%）',
        'X轴（°）',
        ' Y轴（°）',
        '压力（kN）',
        '沉降（mm）'
      ],
      dialogRealTime: false,
      realTimeList: [],
      filterForm: {
        pageNo: 1,
        pageSize: 10,
        startTime: '',
        endTime: '',
        alarmState: 1
      },
      alarmStateArr: ['正常', '预警', '报警'],
      daterange: [],
      dialogDev: false,
      devList: [],
      devOpType: 1, //1：添加  2：编辑  3：详细
      deviceTypeArr: ['倾角', '压力', '沉降2'],
      cancelList: [] // 取消的数据数组
    }
  },
  mounted() {
    this.getEnterpriseList();
    this.loadData()
  },
  methods: {
    /** 查询企业列表 */
    getEnterpriseList() {
      const params = {
        projectSn: this.$store.state.projectSn,
        enterpriseName: undefined,
        userEnterpriseId: this.$store.state.userInfo.userEnterpriseId,
        enterpriseTypeId: undefined,
      };
      getEnterpriseInfoListApi(params).then(res => {
        console.log('查询企业列表: ', res);
        this.enterpriseList = res.result;
      })
    },
    handleInput() {
      this.devList.forEach(item => {
        if (item.deviceSn != '') {
          item.deviceSn = item.deviceSn.replace(/[\u4e00-\u9fa5]/g, '');
        }
      })
    },
    changeDate() {
      if (this.daterange) {
        this.filterForm.startTime = this.daterange[0]
        this.filterForm.endTime = this.daterange[1]
      } else {
        this.filterForm.startTime = ''
        this.filterForm.endTime = ''
      }
    },
    formatAlarmState(row) {
      if (row.alarmState == 1) {
        // '正常'
        return this.$t('message.highModulus.normal')
      } else if (row.alarmState == 2) {
        // '预警'
        return this.$t('message.highModulus.warning')
      } else if (row.alarmState == 3) {
        // '报警'
        return this.$t('message.highModulus.alarm')
      }
    },
    loadData() {
      highFormworkMeasurePointListApi({
        projectSn: this.$store.state.projectSn,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }).then((res) => {
        this.tableData = res.result.records
        this.pageTotal = res.result.total
      })
    },
    formatType(row) {
      return this.$t('message.highModulus.monitorTypeArr')[row.type - 1]
    },
    addFn() {
      this.isAdd = true
      this.dialogVisible = true
      this.resetForm()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.ruleForm));
          params.enterpriseIds = params.enterpriseIds.join(',')
          if (this.isAdd) {
            params.projectSn = this.$store.state.projectSn
            highFormworkMeasurePointAddApi(params).then((res) => {
              // '添加成功'
              this.$message.success(
                this.$t('message.highModulus.addSuccessMsg')
              )
              this.loadData()
              this.dialogVisible = false
            })
          } else {
            highFormworkMeasurePointEditApi(params).then((res) => {
              // '编辑成功'
              this.$message.success(
                this.$t('message.highModulus.editSuccessMsg')
              )
              this.loadData()
              this.dialogVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$nextTick(() => {
        this.ruleForm = {
          enterpriseIds: [],
          acquisitionInstrumentNumber: '',
          measurePointName: '',
          measurePointNumber: '',
          projectSn: '',
          thresholdList: [
            {
              alarmValue: '',
              type: 1,
              warningValue: ''
            },
            {
              alarmValue: '',
              type: 2,
              warningValue: ''
            },
            {
              alarmValue: '',
              type: 3,
              warningValue: ''
            },
            {
              alarmValue: '',
              type: 4,
              warningValue: ''
            },
            {
              alarmValue: '',
              type: 5,
              warningValue: ''
            }
          ]
        }
      })
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.loadData()
    },
    handleCurrentChange(value) {
      this.pageNo = value
      this.loadData()
    },
    handleSizeChange2(value) {
      this.filterForm.pageSize = value
      this.loadRealTimeData()
    },
    handleCurrentChange2(value) {
      this.filterForm.pageNo = value
      this.loadRealTimeData()
    },
    refreshRealTimeFn() {
      this.filterForm.startTime = ''
      this.filterForm.endTime = ''
      this.daterange = []
      this.filterForm.alarmState = ''
      this.loadRealTimeData()
    },
    showRealTime(item) {
      this.ruleForm = item
      this.dialogRealTime = true
      this.refreshRealTimeFn()
    },
    loadRealTimeData() {
      let json = Object.assign(
        this.filterForm,
        { measurePointNumber: this.ruleForm.measurePointNumber },
        { projectSn: this.$store.state.projectSn }
      )
      highFormworkMeasureCurrentDataApi(json).then((res) => {
        this.realTimeList = res.result.records
        this.pageTotal2 = res.result.total
      })
    },
    editFn(item) {
      highFormworkMeasurePointDetailApi({ id: item.id }).then((res) => {
        this.isAdd = false
        this.ruleForm = res.result
        this.ruleForm.enterpriseIds = res.result.enterpriseIds ? res.result.enterpriseIds.split(',') :[];
        this.dialogVisible = true
      })
    },
    deleteFn(item) {
      // '此操作将永久删除该点位, 是否继续?', '提示'
      this.$confirm(
        this.$t('message.highModulus.hintText'),
        this.$t('message.highModulus.hint'),
        {
          confirmButtonText: this.$t('message.highModulus.confirm'),
          cancelButtonText: this.$t('message.highModulus.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          highFormworkMeasurePointDeleteApi({ id: item.id }).then((res) => {
            // '删除成功!'
            this.$message({
              type: 'success',
              message: this.$t('message.highModulus.removeSuccessMsg')
            })
            this.loadData()
          })
        })
        .catch(() => {
          // '已取消删除'
          this.$message({
            type: 'info',
            message: this.$t('message.highModulus.cancelRemove')
          })
        })
    },
    deleteDevFn(item) {
      // this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      // }).then(() => {
      highFormworkMeasureDeviceDeleteApi({ id: item.id }).then((res) => {
        // '删除成功!'
        this.$message({
          type: 'success',
          message: this.$t('message.highModulus.removeSuccessMsg')
        })
        this.loadDevList()
      })
      // }).catch(() => {
      //     this.$message({
      //         type: 'info',
      //         message: '已取消删除'
      //     });
      // });
    },
    addDevFn() {
      this.dialogDev = true
      this.devList.push({
        deviceName: '',
        deviceSn: '',
        deviceType: 1,
        measurePointId: this.ruleForm.id,
        projectSn: this.$store.state.projectSn,
        devOpType: 1
      })
    },
    showDevManage(item) {
      this.ruleForm = item
      this.dialogDev = true
      this.loadDevList()
    },
    editDevFn(item, index) {
      console.log(index)
      item.devOpType = 2
      // this.devList[index].devOpType=2
      this.$set(this.devList, index, item)
    },
    loadDevList() {
      highFormworkMeasureDeviceListApi({
        measurePointId: this.ruleForm.id,
        projectSn: this.$store.state.projectSn
      }).then((res) => {
        this.devList = res.result
      })
    },
    saveDevInfo(item) {
      if (item.devOpType == 1) {
        highFormworkMeasureDeviceAddApi(item).then((res) => {
          // '添加成功'
          this.$message.success(this.$t('message.highModulus.addSuccessMsg'))
          this.loadDevList()
        })
      } else if (item.devOpType == 2) {
        highFormworkMeasureDeviceEditApi(item).then((res) => {
          // '编辑成功'
          this.$message.success(this.$t('message.highModulus.editSuccessMsg'))
          this.loadDevList()
        })
      }
    },
    // 取消
    canselDevInfo(val, index) {
      const originalItem = this.devList[index];
      console.log('取消的类型---', originalItem.devOpType);
      if (originalItem.devOpType === 1) {
        // 如果是新增的设备，直接从列表中移除
        this.devList.splice(index, 1);
      } else if (originalItem.devOpType === 2) {
        // 如果是编辑的设备，将原始数据还原到列表中
        this.$set(this.devList, index, originalItem);
        this.dialogDev = true
        this.loadDevList()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.filterBox {
  margin-bottom: 20px;
}
</style>