<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		      :loading="exportLoading"
          @click="downloadSuccessDataMethod"
        >导出</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport">导入</el-button>
      </el-col> 
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名称" align="center" prop="nickName" >
        <span slot-scope="scope" v-if="scope.row.nickName">{{scope.row.nickName}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="用户类型" align="center" prop="userType" >
        <span slot-scope="scope" v-if="scope.row.userType">{{scope.row.userType}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" >
        <span slot-scope="scope" v-if="scope.row.address">{{scope.row.address}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="所属企业" align="center" prop="beyondEnterpriseName" >
        <span slot-scope="scope" v-if="scope.row.beyondEnterpriseName">{{scope.row.beyondEnterpriseName}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="居住区(村、庄)" width="120" align="center" prop="villageName" >
        <span slot-scope="scope" v-if="scope.row.villageName">{{scope.row.villageName}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="经度" align="center" prop="longitude" >
        <span slot-scope="scope" v-if="scope.row.longitude">{{scope.row.longitude}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="纬度" align="center" prop="latitude" >
        <span slot-scope="scope" v-if="scope.row.latitude">{{scope.row.latitude}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="linkman" >
        <span slot-scope="scope" v-if="scope.row.linkman">{{scope.row.linkman}}</span>
        <span v-else>-</span>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phone" >
        <span slot-scope="scope" v-if="scope.row.phone">{{scope.row.phone}}</span>
        <span v-else>-</span>
      </el-table-column>
      <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-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(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"
    />

    <!-- 添加或修改燃气用户对话框 -->
    <el-dialog :title="title" :visible.sync="open"width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-row>
          <el-col :span="11">
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户账号" />
        </el-form-item>
          </el-col>

          <el-col :span="11">
          <el-form-item label="用户名称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户名称" />
          </el-form-item>
          </el-col>
        </el-row>

        <el-row> 
          <el-col :span="11">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择用户类型">
                <el-option v-for="dict in userTypeOpers" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          

          <el-col :span="11" v-if="form.userType === '1'">
            <el-form-item label="居住区(村、庄)" prop="villageId">
              <el-select v-model="form.villageId"  placeholder="请在下拉框中选择名称" maxlength="255" :disabled="false" clearable style="width: 100%;">
                <el-option v-for="item in villageList" :key="item.fVillageId" :label="item.fVillageName" :value="item.fVillageId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> 

        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="所属企业" prop="beyondEnterpriseId">
              <el-select v-model="form.beyondEnterpriseId"  placeholder="请在下拉框中选择名称" maxlength="255" :disabled="false" clearable style="width: 100%;">
                <el-option v-for="item in test" :key="item.enterpriseId" :label="item.enterpriseName" :value="item.enterpriseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row> 
        
        <el-row>
          <el-col :span="21">
            <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: 15px">
                <el-input v-model="form.latitude" placeholder="请输入纬度"/>
              </el-col>
              <el-col :span="3" style="margin-left: 33px">
                <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="linkman">
              <el-input v-model="form.linkman" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="电话" prop="phone">
              <el-input onkeyup="this.value=this.value.replace(/\D/g,'')" v-model="form.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
        </el-row> 

        <el-row>
          <el-col :span="22">
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div class="tableTitle">
        <img :src="relationImg" style="width: 24px; height: 25px;position: relative; left: -355px; top: -12px; bottom: 8px;"/>
        <span class="midText">安全装置</span>
        
        
      <el-row :gutter="10" class="mb9">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="dialogFormVisible = true"
          >新增</el-button>
        </el-col> 
      </el-row>
      </div>
      
      <el-table v-loading="loadings" ref="multipleTable" :data="detailInfoList" tooltip-effect="dark" style="width: 100%" max-height="250">
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备型号" align="center" prop="deviceModel" />
        <el-table-column label="设备类型" align="center" prop="relationDeviceType" />
        <el-table-column label="物联网编号" width="85" align="center" prop="fIotNo" />
        <el-table-column label="探测介质" align="center" prop="detectionMedium" />
        <el-table-column label="设备安装时间" width="100" align="center" prop="deviceInstallTime" />
        <el-table-column label="安装位置" align="center" prop="deviceInstallPosition" />
        <el-table-column label="负责人" align="center" prop="head" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <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-delete"
              @click="deleteDataListilInfo(scope.row,scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <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="dialogFormVisible">
      <el-form ref="formDetailInfo" :model="formDetailInfo" :rules="formDetailInfoRules" label-width="100px">

        <el-row>
        <el-col :span="11">
          <el-form-item label="设备名称" prop="fDeviceName">
            <el-input v-model="formDetailInfo.fDeviceName" placeholder="请输入设备名称" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="11">
        <el-form-item label="设备型号" prop="fDeviceModel">
           <el-input v-model="formDetailInfo.fDeviceModel" placeholder="请输入设备型号" />
         </el-form-item>
        </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
          <el-form-item label="设备类型"  prop="fRelationDeviceType">
              <el-input v-model="formDetailInfo.fRelationDeviceType" placeholder="请输入设备类型"> 
              </el-input>
          </el-form-item>
          </el-col>

          <el-col :span="11">
          <el-form-item label="物联网编号" prop="fIotNo" >
              <el-input v-model="formDetailInfo.fIotNo" placeholder="请输入物联网编号" />
            </el-form-item>
          </el-col>
        </el-row>   

        <el-row>
          <el-col :span="11">
            <el-form-item label="设备安装时间"  prop="fDeviceInstallTime"> 
              <el-date-picker clearable size="small"
                v-model="formDetailInfo.fDeviceInstallTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择安装时间">
              </el-date-picker> 
            </el-form-item>
          </el-col>

          <el-col :span="11">
          <el-form-item label="安装位置" prop="fDeviceInstallPosition" >
                  <el-input v-model="formDetailInfo.fDeviceInstallPosition" placeholder="请输入安装位置" />
            </el-form-item>
          </el-col>
        </el-row>  
 
        <el-row>
          <el-col :span="11">
          <el-form-item label="负责人"  prop="fHead">
              <el-input v-model="formDetailInfo.fHead" placeholder="请输入负责人"> 
              </el-input>
          </el-form-item>
          </el-col>

          <el-col :span="11">
          <el-form-item label="联系电话" prop="fPhone" >
                  <el-input v-model="formDetailInfo.fPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>  

        <el-row> 
          <el-col :span="22">
            <el-form-item label="探测介质" prop="fDetectionMedium" >
              <el-input v-model="formDetailInfo.fDetectionMedium" placeholder="请输入探测介质" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertListDetailInfo">提 交</el-button>
        
        <el-button @click="dialogFormVisible=false">取 消</el-button>
      </div>
    </el-dialog>

    <GetPos
      :dialogVisible.sync="dialogTableVisibles"
      device=""
      :devicePos="devicePos"
      @close="dialogcancelFun"
      @getPath="getPath"
    />
    
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>

          <br> 

        <el-divider v-if="this.importError > 0 " content-position="left">错误数据导出分隔</el-divider>

        <br>
        
        <el-button
            type="danger" 
            icon="el-icon-download"
            size="small" 
            @click="handleImportError"
            v-if="this.importError > 0 "
          >
           下载导入时错误数据 
          </el-button>
        <el-badge v-if="this.importError > 0 " :value="importError" class="item">
          
        </el-badge> 
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

          <!-- 燃气用户错误数据弹出框 -->
    <el-dialog :title="importErrorShowTitle"  :visible.sync="importErrorShow" width="400px" append-to-body> 
        <el-form>
        <el-form-item>
          <div style="width: 100%; text-align: center;">
            <el-button type="primary" @click="downloadImportError">下载</el-button>
            <el-button type="danger" @click="clearImportErrorMethod">清除错误数据</el-button> 
          </div>
        </el-form-item>
        </el-form> 
      </el-dialog>

  </div>
</template>

<script>
// import { listUser, getUser, delUser,newExportUser,
//   getNoSelectSafetyDetailInfo,addSafetyDetailInfo,deleteSafetyDeviceInfo,
//   deleteSafetyDeviceListInfo,queryDeviceInfoByUserId,
//   addUserAndSafetyDevice,updateUserAndSafetyDevice,downloadTemplate,
//   countImportError,clearImportError,exportErrorData,exportSuccessData} from "@/api/lpgRegulation/user";
import { listUser, getUser, delUser,newExportUser,
getNoSelectSafetyDetailInfo,addSafetyDetailInfo,deleteSafetyDeviceInfo,
deleteSafetyDeviceListInfo,selectSafetyDeviceDetailInfo,
addUserAndSafetyDevice,updateUserAndSafetyDevice,downloadTemplate,downloadLiquefiedGasTemplate,
countImportError,clearImportError,exportErrorData,exportSuccessData} from "@/api/regulation/user";

import { selectTEnterprise} from "@/api/regulation/supervise";
import { noPageListVillage} from "@/api/regulation/userManagement/village";
import GetPos from '@/components/GetPos';
import { getToken } from "@/utils/auth";
export default {
  name: "User",
  components: {
    GetPos
  },
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/supervise/user/moreSheetImportExcelLpg" // todo
      },  

      importError: null,
      importErrorShow: false,
      importErrorShowTitle: "选择下载错误数据或者是清除错误数据",

      relationImg: require('@/assets/project/relation.png'),
      //下拉框数据
      test:{},
      dialogTableVisible: false,
      //存储已被选中的下级数据id
      DetailInfoListId :[],
      //存储已经选中的下级关联数据
      detailInfoList:[],
      /*添加关联设备*/
      formDetailInfo:{
        gasUserSafetyDeviceId:'',
        relationDeviceType: '',
        deviceName:'',
        deviceModel:'',
        fIotNo:'',
        detectionMedium:'',
        deviceInstallTime:null,
        deviceInstallPosition:'',
        head:'',
        phone:''
      },
      dialogFormVisible: false,
      /**--------------地图使用数据---------------*/
      dialogTableVisibles: false,
      devicePos: [],
      //下级设备数据数组
      tableData: [],
      /**--------------地图使用数据---------------*/
      // 居住区数据集合
      villageList:[],
      // 遮罩层
      loading: true,
      //下级数据的遮罩层
      loadings:false,
      //下级数据的遮罩层
      safetyDeviceManageLoadings:true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 燃气用户表格数据
      userList: [],
      // 燃气类型
      userTypeOpers: [],
      // 燃气类型
      gasTypeOpers: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gasType:"1",
        username: null,
        nickName: null,
      },
      // 查询参数
      dateQueryParams: {
        deviceName: null,
        deviceModel: null,
        fIotNo: null,
      },
      // 表单参数
      form: {
        userId: null,
        username: null,
        nickName: null,
        userType: null,
        gasType: "1",
        address: null,
        longitude: null,
        latitude: null,
        linkman: null,
        phone: null,
        email: null,
        isDel: null,
        remarks: null
      },
      // 表单校验
      rules: {
        /*username: [
          { required: true, message: "请输入用户账号", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],*/
        nickName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          // { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          // { min: 0, max: 30, message: "长度30位", trigger: "blur" },
        ],
        gasType: [
          { required: true, message: "请选择燃气类型", trigger: "blur" },
          // { min: 0, max: 30, message: "长度30位", trigger: "blur" },
        ],
      },
      
      //关联设备下级数据 表单校验
      formDetailInfoRules:{
        deviceName:[
          { required: true, message: "请输入设备名称", trigger: "blur" },
          { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        deviceModel:[
          { required: true, message: "请输入设备型号", trigger: "blur" },
          { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
        relationDeviceType:[
          { required: true, message: "请选择设备类型", trigger: "blur" },
        ],
        fIotNo:[
          { required: true, message: "请输入联网编号", trigger: "blur" },
          { min: 0, max: 20, message: "长度20位", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("yehuaqi_user_type").then(response => {
      this.userTypeOpers = response.data;
    });
    this.getDicts("gas_type").then(response => {
      this.gasTypeOpers = response.data;
    });
    this.getNoPageListVillage();
    
    this.countImportError();
  },
  methods: { 

    // 下载燃气用户错误 按钮
    handleImportError() {
      if(this.importError === 0) {
        this.$alert('暂无错误数据', '下载', {
          confirmButtonText: '确定',
        });
        return
      } else {
        this.importErrorShow = true;
      }
    },

    
  //自定义-模版下载-正确数据导出-燃气用户
    downloadSuccessDataMethod() {
      this.$showLoading.show()

      exportSuccessData(this.queryParams).then((res) =>{

        let blob = new Blob([res], {type: 'data:application/vnd.ms-excel;base64;charset=utf-8'});

        let downloadElement = document.createElement('a');

        let href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '液化气用户数据'+'.xlsx'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象
        
        this.$showLoading.hide()

        return true 
      })
    },

    // 下载燃气用户错误 按钮
    downloadImportError() {  
      exportErrorData("1").then((res) =>{ 

          let blob = new Blob([res], {type: 'data:application/vnd.ms-excel;base64;charset=utf-8'});

          let downloadElement = document.createElement('a');

          let href = window.URL.createObjectURL(blob); //创建下载的链接

          downloadElement.href = href;

          downloadElement.download = '液化气用户导入错误数据'+'.xlsx'; //下载后文件名

          document.body.appendChild(downloadElement);

          downloadElement.click(); //点击下载

          document.body.removeChild(downloadElement); //下载完成移除元素

          window.URL.revokeObjectURL(href); //释放掉blob对象

          return true 
      }) 


      this.importErrorShow = false;
    },

    // 清除 燃气用户错误 数据
    clearImportErrorMethod() {

      this.$confirm('是否确认删除导入的燃气用户错误数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return clearImportError();
        }).then(() => {
          this.importErrorShow = false;
          this.msgSuccess("删除成功");
          this.importError = 0
        }).catch(() => {});
    },

    //查询 导入错误数据
    countImportError() {
      countImportError("1").then(response => {
          this.importError = response.data;
      })
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit(); 
    },

    handleImport(){
      this.upload.title = "液化气用户导入"; // todo
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      downloadLiquefiedGasTemplate().then((res) =>{ 

        let blob = new Blob([res], {type: 'data:application/vnd.ms-excel;base64;charset=utf-8'});

        let downloadElement = document.createElement('a');

        let href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '液化气用户导入模版'+'.xlsx'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        return true 
      }) 
    }, 

    // 文件上传处理中
    handleFileUploadProgress(event,file,fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // this.getDataList(); 
      
      countImportError("1").then(response => {
          this.importError = response.data;
          if(this.importError === 0) {
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
          } else {
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + '有错误数据，请点击导入界面查看详情' + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
          }
      })

      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total; 
      });
    },

    /**关联设备已经选中数据删除方法*/
    deleteDataListilInfo(row,index){
      const deviceIds = row.fSafetyDeviceId;
      //判断form表单是否有id来验证是修改的删除还是添加的删除
      if (this.form.userId != null) {
        deleteSafetyDeviceInfo(deviceIds).then(response => {
          this.msgSuccess("删除成功");
          this.detailInfoList.splice(index,1);
        });
      }else {
        this.detailInfoList.splice(index,1);
        this.msgSuccess("删除成功");
      }

    },
    
    /**关联设备单条删除方法*/
    deleteDetailInfo(row){
      const deviceIds = row.gasUserSafetyDeviceId;
      this.$confirm('是否确认删除安全装置编号为"' + deviceIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteSafetyDeviceInfo(deviceIds);
      }).then(() => {
        // this.tableData.splice(index,1);
        this.getDataList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**关联设备单条删除方法*/
    deleteSafetyDeviceInfo(row){
      const deviceIds = row.gasUserSafetyDeviceId;
      this.$confirm('是否确认删除设备信息编号为"' + deviceIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteSafetyDeviceInfo(deviceIds);
      }).then(() => {
        // this.tableData.splice(index,1);
        this.getDataList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /**
     * 批量删除关联设备方法
     * @param row
     */
     deleteListDetailInfo(row){
      const deviceIds = this.ids;
      this.$confirm('是否确认删除安全装置为"' + deviceIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteSafetyDeviceListInfo(deviceIds);
      }).then(() => {
        this.getDataList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**添加关联设备与设备绑定的数据  （存储到数组中）*/
    insertListDetailInfo(){
      console.log("this.detailInfoList" + this);
      this.detailInfoList.push(this.formDetailInfo);
      
      //数据表单重置
      this.formDetailInfo={
        relationDeviceType: null,
        deviceName:null,
        deviceModel:null,
        fIotNo:null,
        detectionMedium:null,
        deviceInstallTime:null,
        deviceInstallPosition:null,
        head:null,
        phone:null
      };

      this.dialogFormVisible = false;
    }, 
    
    /**关联设备添加方法*/
    addSafetyDeviceInfo(){
      this.$refs["formDetailInfo"].validate(valid => {
        if (valid) {
          addSafetyDetailInfo(this.formDetailInfo).then(response => {
            // this.tableData.push(this.formDetailInfo)
            //关闭弹出层
            this.dialogFormVisible = false;
            //数据表单重置
            this.formDetailInfo={
              relationDeviceType: null,
              deviceName:null,
              deviceModel:null,
              fIotNo:null,
              detectionMedium:null,
              deviceInstallTime:null,
              deviceInstallPosition:null,
              head:null,
              phone:null
            };
            this.getDataList();
            this.msgSuccess("新增成功");
          });
        }

      });
    },

    /** 下级数据搜索*/
    handleQueryData(){
      this.getDataList();
    },

    /**查询下级数据列表方法*/
    getDataList(){
      this.safetyDeviceManageLoadings = true;
      // console.log(this.dateQueryParams)
      //查询下级设备数据
      getNoSelectSafetyDetailInfo(this.dateQueryParams).then(response => {
        //下级设备数据 到时候换成下级数据
        this.tableData = response.rows;
        this.detailTotal = response.total;
        this.safetyDeviceManageLoadings = false;
      });
    },
    
    /** 下级数据重置按钮操作  搜索框重置*/
    resetQueryDate(){
      this.dateQueryParams={
        deviceName: null,
          deviceModel: null,
          fIotNo: null,
      }
      this.getDataList();
    },
    /**
     * 选择关联设备查询方法
     */
     selectDataListInfo(){
      //查询下级设备数据
      getNoSelectSafetyDetailInfo(this.dateQueryParams).then(response => {
        //下级设备数据 到时候换成下级数据
        this.tableData = response.rows;
        this.detailTotal = response.total;
        this.safetyDeviceManageLoadings = false;
        //打开选择关联设备弹出框
        this.dialogTableVisible = true
      });
    },

    //获取居住区集合
    getNoPageListVillage(){
      noPageListVillage(this.queryForm).then(response => {
        this.villageList = response;
      });
    },
    /** 查询燃气用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        username: null,
        nickName: null,
        userType: null,
        gasType: "1",
        address: null,
        longitude: null,
        latitude: null,
        linkman: null,
        phone: null,
        email: null,
        isDel: null,
        remarks: null,
        fVillageId: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.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      //查询企业名称下拉框数据
      selectTEnterprise().then(response => {
        this.test = response.data;
      });
      this.reset();
      this.devicePos = [];
      //清空关联设备数据
      this.detailInfoList=[]
      this.open = true;
      this.title = "添加燃气用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
      this.loadings = true;
      //查询企业名称下拉框数据
      selectTEnterprise().then(response => {
        this.test = response.data;
      });
      this.reset();
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改燃气用户";
        if (response.data.longitude == null || response.data.latitude == null) {
          this.devicePos = [];
        } else {
          this.devicePos = [response.data.longitude, response.data.latitude];
        } 
      }); 

      //查询关联设备信息数据
      selectSafetyDeviceDetailInfo(userId).then(response => {
        this.detailInfoList = response.data;
        this.loadings = false;
      }); 
    },
    /** 提交按钮 */
    submitForm() {

      if (this.form.userType === '1' && this.form.villageId == null ) {
        
        alert("当用户类型是 ‘居民用户’ 时，居住区(村、庄) 必选");

        return 
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            
            var tDeviceInfon={
              detectorUser:this.form,
              gasuserSafetyDeviceInfoList:this.detailInfoList
            }
            updateUserAndSafetyDevice(JSON.stringify(tDeviceInfon)).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });  
          } else {
            
            var tDeviceInfon={
              detectorUser:this.form,
              gasuserSafetyDeviceInfoList:this.detailInfoList
            }

            addUserAndSafetyDevice(JSON.stringify(tDeviceInfon)).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除燃气用户编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有燃气用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return newExportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /**
     * 经纬度坐标方法
     */
    MapdialogFun() {
      this.dialogTableVisibles = true;
    },
    /**
     * 地图关闭方法
     */
    dialogcancelFun() {
      this.dialogTableVisibles = false;
    },
    /**
     * 经纬度 选择
     * @param res
     */
    getPath(res){
      //确认选择经纬度
      this.form.longitude = res[0];
      this.form.latitude = res[1];
    }
  }
};
</script>
<style scoped>

  .tableTitle {
    position: relative;
    margin: 24px  auto;
    width: 600px;
    height: 2px;
    background-color: #d4d4d4;
    text-align: center;
    font-size: 16px;
    color: rgba(101, 101, 101, 1);
  }
  
  .midText {
    position: absolute;
    left: 3%;
    background-color: #ffffff;
    padding: 0 15px;
    transform: translateX(-50%) translateY(-50%);
  }
 
.mb9 {
  left: -60px;
  bottom: 8px;
}
 
  </style>