<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <!-- 智能张拉——设备管理 -->
      <el-form :inline="true" ref="searchForm" :model="searchForm" size="medium">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.devName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="getList">{{
            $t("message.energyManage.waybill.query")
          }}</el-button>
          <el-button type="warning" plain @click="refresh">{{
            $t("message.deviceManage.refresh")
          }}</el-button>
          <el-button type="primary" size="medium" @click="add">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="List">
        <el-table-column prop="devName" align="center" label="设备名称"></el-table-column>
        <el-table-column prop="devSn" align="center" label="设备编码"></el-table-column>
        <el-table-column prop="installLocation" align="center" label="安装位置"></el-table-column>
        <el-table-column prop="personInChargeName" align="center" label="负责人"></el-table-column>
        <el-table-column prop="phoneNumber" align="center" label="负责人电话"></el-table-column>
        <el-table-column prop="image" align="center" label="设备图片">
          <template slot-scope="scope">
            <div class="devImage">
              <el-image v-if="JSON.parse(scope.row.image)[0]"
                :preview-src-list="JSON.parse(scope.row.image) ? [JSON.parse(scope.row.image)[0].url] : []"
                :src="JSON.parse(scope.row.image)[0] ? JSON.parse(scope.row.image)[0].url : []" alt=""></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" align="center" label="备注"></el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div @click="edit(scope.row)" class="operationText">
                <img src="@/assets/images/icon-edit.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">编辑</span>
              </div>
              <div @click="deleteDev(scope.row)" class="operationText">
                <img src="@/assets/images/icon-delete.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">删除</span>
              </div>
              <div @click="setYu(scope.row)" class="operationText">
                <img src="@/assets/images/yu.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">预警值设置</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagerBox" @size-change="SizeChange" @current-change="CurrentChange"
        :current-page="pagInfo.pageNo" :page-sizes="$store.state.PAGESIZRS" :page-size="pagInfo.pageSize"
        layout="total, sizes, prev, pager, next" :total="Number(pagInfo.total)" background></el-pagination>
    </div>
    <el-dialog :modal-append-to-body="false" @close="close" :title="title" :visible.sync="dialogShow" width="667px">
      <div class="dialog_content">
        <el-form size="medium" ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-width="120px"
          class="dialogFormBox">
          <el-form-item label="设备名称" prop="devName">
            <el-input :disabled="isDetail" v-model="addEditForm.devName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="设备编码" prop="devSn">
            <el-input :disabled="isDetail" v-model="addEditForm.devSn" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="安装位置" prop="installLocation">
            <el-input :disabled="isDetail" v-model="addEditForm.installLocation" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="personInCharge">
            <el-select v-model="addEditForm.personInCharge" placeholder="请选择" :disabled="isDetail"
              @change="dutySelectChange">
              <el-option v-for="(item, index) in dutyList" :key="index" :label="item.realName" :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人电话" prop="phoneNumber">
            <el-input :disabled="isDetail" v-model="addEditForm.phoneNumber" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="上传图片">
            <el-upload :disabled="isDetail" :action="$store.state.UPLOADURL" list-type="picture-card" multiple
              name="files" :limit="1" accept=".png, .jpg, .jpeg" :file-list="fileUplodList"
              :on-exceed="(file, fileList) => handleExceed(file, fileList)"
              :on-success="(res, file) => handleSuccess(res, file)"
              :on-remove="(file, fileList) => handleRemove(file, fileList)">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input :disabled="isDetail" v-model="addEditForm.remark" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="dialog-footer">
            <el-button class="cancleBtn" @click="dialogShow = false" icon="el-icon-circle-close" size="medium">{{
              $t("message.deviceManage.cancel") }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submit" size="medium">{{
              $t("message.deviceManage.save") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog :modal-append-to-body="false" @close="dialogSetShow = false" title="编辑预警值设置" :visible.sync="dialogSetShow"
      width="667px">
      <div class="dialog_content">
        <el-form size="medium" ref="setEditForm" :model="setEditForm" label-width="120px" class="dialogFormBox">
          <el-form-item label="PH值" prop="phValue">
            <el-input v-model="setEditForm.phValue" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="电导率(μS/cm)" prop="conductivity">
            <el-input v-model="setEditForm.conductivity" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="水温(℃)" prop="waterTemperature">
            <el-input v-model="setEditForm.waterTemperature" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="溶解氧(mg/L)" prop="dissolvedOxygen">
            <el-input v-model="setEditForm.dissolvedOxygen" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="浊度值(NTU)" prop="turbidityValue">
            <el-input v-model="setEditForm.turbidityValue" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="流速(m/s)" prop="flowVelocity">
            <el-input v-model="setEditForm.flowVelocity" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="水位(m)" prop="waterLevel">
            <el-input v-model="setEditForm.waterLevel" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="dialog-footer">
            <el-button class="cancleBtn" @click="dialogSetShow = false" icon="el-icon-circle-close" size="medium">{{
              $t("message.deviceManage.cancel") }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submitSet" size="medium">{{
              $t("message.deviceManage.save") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  sewageDevAdd,
  sewageDevDelete,
  sewageDevEdit,
  sewageDevPage,
  getCrewListDataApi,
  sewageThresholdDetail,
  sewageThresholdEdit
} from "@/assets/js/api/sewageMonitor.js";
export default {
  mounted() { },
  created() {
    this.getList();
    this.getDutyPerson();
  },
  data() {
    return {
      isDetail: false, //是否详情
      dutyList: [], // 负责人
      fileUplodList: [],
      title: "",
      dialogSetShow: false,
      dialogShow: false,
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0, //总条数
      },
      List: [],
      setEditForm: {
        phValue: 100,
        conductivity: 100,
        waterTemperature: 100,
        dissolvedOxygen: 100,
        turbidityValue: 100,
        flowVelocity: 100,
        waterLevel: 100
      },
      addEditForm: {
        createTime: "",
        devSn: "",
        installLocation: "",
        devName: "",
        personInChargeName: "",
        personInCharge: "",
        phoneNumber: "",
        personInCharge: "",
        image: "",
        remark: "",
        projectSn: "",
        updateTime: "",
      },
      addEditRules: {
        devName: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
        ],
        devSn: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          {
            message: "请输入正确的手机号码",
            trigger: "blur",
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
          },
        ],
      },
      searchForm: {
        devName: "",
      },
    };
  },
  methods: {
    // 设置阈值
    async setYu(obj) {
      const res = await sewageThresholdDetail({ devSn: obj.devSn })
      let initForm = JSON.parse(JSON.stringify(this.setEditForm))
      this.setEditForm = { ...this.setEditForm, ...res.result }
      for(let i in initForm){
        if(!this.setEditForm[i]){
          this.setEditForm[i] = 100;
        }
      }
      this.dialogSetShow = true;
    },
    //  负责人下拉回调
    dutySelectChange(e) {
      const item = this.dutyList.find(item => item.userId === e);
      this.addEditForm.personInChargeName = item.realName
    },
    //查询负责人下拉
    getDutyPerson() {
      let data = {
        projectSn: this.$store.state.projectSn,
      };
      getCrewListDataApi(data).then((res) => {
        if (res.code == 200) {
          this.dutyList = res.result;
          console.log("获取负责人下拉", this.dutyList);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //查询列表
    getList() {
      sewageDevPage({
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        projectSn: this.$store.state.projectSn,
        devName: this.searchForm.devName,
      }).then((result) => {
        if (result.success) {
          this.List = result.result.records;
          this.pagInfo.total = result.result.total;
        }
      });
    },

    add() {
      this.title = "新增";
      this.dialogShow = true;
      this.fileUplodList = [];
      this.close();
    },

    edit(obj) {
      this.title = "编辑";
      this.dialogShow = true;
      this.addEditForm = JSON.parse(JSON.stringify(obj));
      this.fileUplodList = JSON.parse(obj.image);
    },
    submitSet() {
      let params = JSON.parse(JSON.stringify(this.setEditForm));
      sewageThresholdEdit(params).then((result) => {
        if (result.success) {
          this.$message.success(result.message);
          this.getList();
          this.dialogSetShow = false;
        }
      });
    },
    submit() {
      let params = JSON.parse(JSON.stringify(this.addEditForm));
      params.projectSn = this.$store.state.projectSn;
      params.image = JSON.stringify(this.fileUplodList);
      // if (this.fileUplodList.length > 0) {
      //   this.$message.error('请上传照片')
      //   return false
      // }
      this.$refs.addEditForm.validate((valid) => {
        if (valid) {
          if (this.title == "新增") {
            sewageDevAdd(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          } else if (this.title == "编辑") {
            sewageDevEdit(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          }
          this.dialogShow = false;
        } else {
          return false;
        }
      });
    },
    deleteDev(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          sewageDevDelete({ id: obj.id }).then((res) => {
            if (res.success) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 删除
    handleRemove(file, fileList) {
      this.fileUplodList = fileList;
    },
    handleExceed(file, fileList) {
      console.log("超出限制", file);
      this.$message.warning("只能上传一张图片");
    },
    handleSuccess(res, file, type) {
      if (res.status == "SUCCESS") {
        console.log(res);
        this.fileUplodList.push({
          name: file.name,
          url: this.$store.state.FILEURL + file.response.data[0].imageUrl,
        });
      }
    },
    close() {
      this.isDetail = false;
      this.addEditForm = {};
      this.fileUplodList = [];
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate();
      });
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val;
      this.getList();
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val;
      this.getList();
    },
    refresh() {
      this.searchForm = {};
      this.pagInfo.pageNo = 1; //页数
      this.pagInfo.pageSize = 10; //条数
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.tables2 {
  min-height: auto;
}

.devImage {
  /deep/ .el-image {
    width: 80px;
    height: 50px;
  }
}

.textStyle {
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
