<template>
  <div class="gassVehicle app-container">
    <drawer title="密闭空间和人员密集场所" :inner="true" :width="drawerWidth" :mask="false">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="场所名称" prop="venueFacility">
          <el-input
            v-model="queryParams.venueFacility"
            placeholder="请输入场所/设施名称"
            clearable
            size="small"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="场所分类" prop="venueType">
          <el-select v-model="queryParams.venueType" style="width: 140px" placeholder="请选择场所分类" clearable size="small">
            <el-option label="密闭空间" value="1" />
            <el-option label="人员密集场所" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="警示标识" prop="warningSign">
          <el-select v-model="queryParams.warningSign" style="width: 140px" placeholder="请选择警示标识" clearable size="small">
            <el-option label="已设置" value="1" />
            <el-option label="未设置" value="2" />
          </el-select>
        </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">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>-->

      <el-table v-loading="loading" :data="spaceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column label="企业名称" align="center" prop="enterpriseName" />
        <el-table-column label="场所/设施名称" align="center" prop="venueFacility" />
        <el-table-column label="场所分类" align="center" prop="venueType" :formatter="venueTypeFormat" />
        <el-table-column label="具体位置" align="center" prop="specificLocation" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-map-location"
              @click="getViewLocation(scope.row)"
            >查看位置</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleReport(scope.row)"
            >上报</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <div id="map"></div>

    <!-- 添加或修改密闭空间和人员密集场所对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="所属企业" prop="enterpriseId">
              <el-select v-model="form.enterpriseId" placeholder="请选择所属单位名称" style="width: 100%" @change="qiyechang" >
                <el-option
                  v-for="item in enterprises"
                  :key="item.enterpriseId"
                  :label="item.enterpriseName"
                  :value="item.enterpriseId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="统一社会信用代码" prop="socialCreditCode">
              <el-input v-model="form.socialCreditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="场所设施" prop="venueFacility">
              <el-input v-model="form.venueFacility" placeholder="请输入场所/设施名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="场所分类" prop="venueType">
              <el-select v-model="form.venueType" placeholder="请选择场所分类">
                <el-option label="密闭空间" value="1" />
                <el-option label="人员密集场所" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="具体位置" prop="specificLocation">
              <el-input v-model="form.specificLocation" placeholder="请输入具体位置" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="面积/容积" prop="area">
              <el-input v-model="form.area" placeholder="请输入面积/容积 (平方米或立方米)" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <el-form-item label="经纬度" prop="longitude">
              <el-col :span="9">
                <el-input v-model="form.longitude" placeholder="请输入经度" />
              </el-col>
              <el-col :span="9" style="margin-left: 10px">
                <el-input v-model="form.latitude" placeholder="请输入纬度" />
              </el-col>
              <el-col :span="3" style="margin-left: 30px">
                <el-button type="primary" plain @click="MapdialogFun">选择经纬度</el-button>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="危险因素" prop="riskFactors">
              <el-input v-model="form.riskFactors" placeholder="请输入主要危险因素" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="频次" prop="workFrequency">
              <el-input v-model="form.workFrequency" placeholder="请输入作业/人员频次" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="警示标识" prop="warningSign">
              <el-select v-model="form.warningSign" placeholder="请选择警示标识">
                <el-option label="已设置" value="1" />
                <el-option label="未设置" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="应急器材" prop="emergencyEquipment">
              <el-input v-model="form.emergencyEquipment" placeholder="请输入主要应急器材" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="负责人" prop="siteSupervisor">
              <el-input v-model="form.siteSupervisor" placeholder="请输入现场负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="电话" prop="supervisorPhone">
              <el-input v-model="form.supervisorPhone" placeholder="请输入负责人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="最近检查日期" prop="lastDate">
              <el-date-picker clearable size="small"
                              v-model="form.lastDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择最近检查日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备上报数据弹窗 -->
    <el-dialog title="设备监测数据" :visible.sync="deviceDataVisible" width="900px" append-to-body>
      <el-tabs v-model="activeName" @tab-click="handleDeviceTabClick">
        <el-tab-pane label="压力表" name="1"></el-tab-pane>
        <el-tab-pane label="流量计" name="2"></el-tab-pane>
        <el-tab-pane label="探测器" name="3"></el-tab-pane>
        <el-tab-pane label="温度计" name="4"></el-tab-pane>
      </el-tabs>

      <div v-if="deviceDataVisible">
        <el-table v-loading="deviceDataLoading" :data="deviceDataList" style="width: 100%">
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="设备编号" align="center" prop="deviceNum" />
          <el-table-column label="所属企业" align="center" prop="beyondEnterpriseName" />
          <el-table-column label="压力 (KPa)" align="center" prop="pressure" v-if="activeName === '1'" />
          <el-table-column label="标况流量 (m³)" align="center" prop="standardConditionFlow" v-if="activeName === '2'" />
          <el-table-column label="温度 (℃)" align="center" prop="temperature" v-if="activeName === '4'" />
          <el-table-column label="通讯状态" align="center" prop="communicationStatus" :formatter="communicationStatusFormat" />
          <el-table-column label="上报时间" align="center" prop="createTime" width="180" />
        </el-table>
        <pagination
          v-show="deviceDataTotal>0"
          :total="deviceDataTotal"
          :page.sync="deviceDataQueryParams.pageNum"
          :limit.sync="deviceDataQueryParams.pageSize"
          @pagination="getDeviceDataList"
        />
      </div>
    </el-dialog>

    <GetPos
      :dialogVisible.sync="dialogTableVisibles"
      device=""
      :devicePos="devicePos"
      @close="dialogcancelFun"
      @getPath="getPath"
    />
  </div>
</template>

<script>
import { listSpace, getSpace, delSpace, addSpace, updateSpace, selectDetailInfoList } from "@/api/risk/space";
import {enterpriseLists} from "@/api/regulation/info";
import {spaceListData} from "@/api/operationMonitor/data";
import drawer from  "./component/drawer";
import GetPos from '@/components/GetPos';
import { mapBound } from "@/utils/mapClass/boundaryMap";
import {entReportConGasProInfo, reportConGasProInfo} from "@/api/thirdbuild/project";

export default {
  name: "VisualManagement",
  components: {
    GetPos,
    drawer
  },
  data() {
    return {
      map: null,
      recordMarkers: [],
      drawerWidth: '800px',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 密闭空间和人员密集场所表格数据
      spaceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      enterprises: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enterpriseId: null,
        venueFacility: null,
        venueType: null,
        warningSign: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseId: [
          { required: true, message: "所属企业不能为空", trigger: "blur" }
        ],
        venueFacility: [
          { required: true, message: "场所/设施名称不能为空", trigger: "blur" }
        ],
        venueType: [
          { required: true, message: "场所分类不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "blur" }
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "blur" }
        ],
      },
      /**--------------地图使用数据---------------*/
      dialogTableVisibles: false,
      devicePos: [],
      /**--------------设备上报数据---------------*/
      deviceDataVisible: false,
      deviceDataLoading: false,
      deviceDataList: [],
      deviceDataTotal: 0,
      activeName: '1',
      currentSpaceId: null,
      deviceDataQueryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceType: '1'
      }
    };
  },
  created() {
    this.getList();
    this.getEnterpriseLists();
  },
  mounted(){
    // 延迟初始化确保 DOM 已经渲染
    this.$nextTick(() => {
      this.map = new AMap.Map("map", {
        center: [117.08, 39.98],
        zoom: 14,
      });
      mapBound('三河市', this.map, false);
    });
  },
  methods: {
    qiyechang(value){
      let obj = {};
      obj = this.enterprises.find((item)=>{
        return item.enterpriseId === value;
      });
      this.form.enterpriseName = obj.enterpriseName;
      this.form.enterpriseId = value;
    },
    getEnterpriseLists(){
      const param = {};
      enterpriseLists(param).then(response => {
        if (response.rows.length>1){
          this.enterprises = response.rows;
        }else {
          this.form.enterpriseId=response.rows[0].enterpriseId
          this.enterprises = response.rows;
        }
      });
    },
    /** 查询密闭空间和人员密集场所列表 */
    getList() {
      this.loading = true;
      listSpace(this.queryParams).then(response => {
        this.spaceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 场所分类字典翻译
    venueTypeFormat(row, column) {
      if (row.venueType === '1') {
        return '密闭空间';
      } else if (row.venueType === '2') {
        return '人员密集场所';
      }
      return '';
    },
    // 通讯状态字典翻译
    communicationStatusFormat(row, column) {
      if (row.communicationStatus === '0') {
        return '在线';
      } else if (row.communicationStatus === '1') {
        return '离线';
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        enterpriseId: null,
        enterpriseName: null,
        socialCreditCode: null,
        venueFacility: null,
        venueType: null,
        specificLocation: null,
        area: null,
        riskFactors: null,
        workFrequency: null,
        warningSign: null,
        emergencyEquipment: null,
        siteSupervisor: null,
        supervisorPhone: null,
        lastDate: null,
        createTime: null,
        longitude: null,
        latitude: 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
      getSpace(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改密闭空间和人员密集场所";
        this.devicePos = [response.data.longitude, response.data.latitude];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpace(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpace(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除密闭空间和人员密集场所编号为"' + ids + '"的数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delSpace(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**获取场所位置并展示设备数据*/
    getViewLocation(row){
      this.currentSpaceId = row.id;
      this.map.remove(this.recordMarkers);

      if (row.longitude!=="" && row.latitude!="" && row.longitude!==undefined && row.latitude!==undefined){
        let marker = new AMap.Marker({
          icon: require("@/assets/firstimage/yjzy.png"),
          position: [row.longitude,row.latitude],
          offset: new AMap.Pixel(-13, -30),
          clickable: true
        });

        marker.on('click', () => {
          this.showDeviceData(row);
        });

        this.map.add(marker);
        this.map.setCenter([row.longitude,row.latitude]);
        this.map.setZoom(16);
        this.recordMarkers.push(marker);

        // 不再自动打开设备数据弹窗，只有点击地图标记才打开
        // this.showDeviceData(row);
      }else{
        this.$message({
          message: '当前场所未配置位置信息！',
          type: 'warning'
        });
      }
    },
    /**展示设备上报数据*/
    showDeviceData(row) {
      this.deviceDataVisible = true;
      this.activeName = '1';
      this.deviceDataQueryParams.deviceType = '1';
      this.deviceDataQueryParams.relationDeviceId = row.id;
      this.getDeviceDataList();
    },
    /**切换设备类型标签*/
    handleDeviceTabClick(tab) {
      this.activeName = tab.name;
      this.deviceDataQueryParams.deviceType = tab.name;
      this.getDeviceDataList();
    },
    /**获取设备数据列表*/
    getDeviceDataList() {
      this.deviceDataLoading = true;
      spaceListData(this.deviceDataQueryParams).then(response => {
        this.deviceDataList = response.rows;
        this.deviceDataTotal = response.total;
        this.deviceDataLoading = false;
      });
    },
    /**
     * 经纬度坐标方法
     */
    MapdialogFun() {
      this.dialogTableVisibles = true;
    },
    /**
     * 地图关闭方法
     */
    dialogcancelFun() {
      this.dialogTableVisibles = false;
    },
    /**
     * 经纬度 选择
     * @param res
     */
    getPath(res){
      this.form.longitude = res[0];
      this.form.latitude = res[1];
    },
    /** 上报按钮操作 */
    handleReport(row) {
      this.$confirm('是否确认上报监测异常?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {

      }).then(() => {
        this.getList();
        //this.msgSuccess("上报成功");
        this.msgError("上级接口调用失败");
      }).catch(() => {});
    },
  }
};
</script>
<style lang="scss" scoped>
.gassVehicle{
  position:relative;
  height:calc(100vh - 84px);
  padding:0;
  display: flex;
}

#map{
  height: 100%;
  flex: 1;
  min-width: 500px;
}

.el-table{
  background-color: #fff !important;
}

::v-deep .drawer-container {
  height: 100%;
  overflow-y: auto;
}
</style>
