<!--
 * @Author: wf
 * @Date: 2020-01-13 11:35:41
 * @LastEditors: wf
 * @LastEditTime: 2021-09-16 09:50:23
 * @Description: 安装管理---添加安装计划
 -->
<template>
  <div class="device-info_install addinstall">
		<div class="device_content">
			<div class="left_content">
				<div class="form_head">
					<p>基本信息</p>
				</div>
				<div class="form_content">
          <el-scrollbar class="app-list-scroll" style="height:100%">
					<div class="form_content_disform">
						 <zz-form :cols="detailCols" :data='formdata' :rules="formrules" labelWidth='98' ref='detailform'>
							 <zz-select
									 v-model="formdata.communityId"
									 placeholder="请选择社区名称"
									 :options="communityNameList"
									 slot="communityNameList"
							 />

							 <zz-select
									 v-model="formdata.buildingType"
									 placeholder="请选择楼栋类型"
									 :options="buildingTypeList"
									 slot="buildingTypeList"
							 />

							<el-option
								v-for="(item, index) in communityList"
								:key="index"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
						<div slot="phone">
            <el-input
              v-model="formdata.phone"
              maxlength="11"
              v-number-input
            ></el-input>
          </div>
						 </zz-form>
					</div>
					</el-scrollbar>
				</div>
			</div>
			<div class="right_content">
	      <div class="right_content_head">
				 <span class="head_text">创建单元户</span>
         <span class='close' @click='$emit("close")'>
					  <i class='el-icon-close'></i>
			  	</span>
				</div>
				<div class="right_content_info">
           <!-- <tabcontent :userinfo="userinfo" :params="params" :alias="alias"></tabcontent>						 -->
				  <div class="head_fr">
					<div class="head_content head_add">
							 <div class="checkbox_style">
								 	<el-checkbox @change="checkedUnit" v-model="formdata.checkedUnit"></el-checkbox>
							</div>
							<div class="form_content">
							<zz-form :cols="unitCols" labelposition="left" :rules="unitrules" :data='formdata' labelWidth='50' ref='unitform'>
							  <template slot="floorRule" prop="floorRule" >
									<div class="row_class">
									<el-radio-group  v-model="formdata.rules.floor.type" @change="radioChange('floor',$event)">
										<el-radio label="Number">按数字1-20生成</el-radio>
										<el-radio label="Letter">按字母A-Z生成</el-radio>
								  </el-radio-group>
									<el-select class="w120 wfirst" v-model="formdata.rules.floor.start" placeholder="起始楼栋">
										<el-option
											v-for="item in floorOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									<el-select class="w120 wsecond" v-model="formdata.rules.floor.end" placeholder="楼栋数">
										<el-option
											v-for="item in floorOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									<div class="last_level">
										<label class="label_text">每栋层数</label>
										<el-select class="w120" v-model="formdata.floorlevelNum" placeholder="请选择楼栋层数">
										<el-option
											v-for="item in floorlevelOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									</div>
									</div>
							 </template>
							 <template slot="unitRule" prop="unitRule">
								 <div class="row_class">
									<el-radio-group :disabled="!formdata.checkedUnit" v-model="formdata.rules.unit.type" @change="radioChange('unit',$event)">
										<el-radio label="Number">按数字1-20生成</el-radio>
										<el-radio label="Letter">按字母A-Z生成</el-radio>
								  </el-radio-group>
									<el-select :disabled="!formdata.checkedUnit" class="w120 wfirst" v-model="formdata.rules.unit.start" prop="floorstart" placeholder="起始单元">
										<el-option
											v-for="item in unitOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									<el-select class="w120 wsecond" :disabled="!formdata.checkedUnit" v-model="formdata.rules.unit.end" placeholder="单元数">
										<el-option
											v-for="item in unitOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									<div class="last_level">
										<label class="label_text">每层户数</label>
										<el-select class="w120" v-model="formdata.householdNum" placeholder="请选择每层户数">
										<el-option
											v-for="item in unithouseOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
								  </el-select>
									</div>
								 </div>
							 </template>
						 </zz-form>
						 </div>
						  <div class="btn_unit">
							 <!-- {{doorData.length ? '重新' : ''}} -->
							 <el-button type="primary" class="el-mgRight-md" @click="createDoor">{{doorData.length ? '重新' : ''}}生成单元户</el-button>
						   <el-button @click="clearDoor">清空单元户</el-button>
						 </div>
					</div>
					<div class="title_class">
						<span class="title_txt">楼栋信息</span>
						<el-tooltip v-if="doorData && doorData.length>0" class="item text-wrapper" effect="light" placement="right">
						   <div slot="content">双击可对楼栋、单元名称进行自定义修改<br/>单击选中楼栋、单元、单元户信息根据选中的楼栋、单元进行展示</div>
							 <img src="@/assets/img/menuicon/icon_tishi_zhengchang.png" alt="">
					  </el-tooltip>
					</div>

					</div>
					<div class="floorinfo">
							<div class="door-wrap door_install">
								<div class="top_content">
									<el-scrollbar class="app-list-scroll" style="height:100%">
									<div class="floor_unit" v-if="doorData && doorData.length>0">
									<div class="box clearfix" >
										<div class="label_left">楼栋</div>
										<div class="el-fl-left tags">
											<el-tag
												:key="index1"
												v-for="(build,index1) in doorData"
												closable
												:disable-transitions="false"
												data-code="build"
												@close="handleClose('build', index1, doorData)"
												@click="buildingIndex = index1; unitIndex = 0;"
												:class="{active: buildingIndex === index1}"
												>
												<span class="dbclick_txt" @dblclick="showInput">{{build.name}}</span>
												<el-input
													style="display:none"
													v-model='build.name'
													@keyup.enter.native="inputConfirm($event, doorData)"
													@blur="inputConfirm($event, doorData)"
													data-code="build"
													maxlength="20"
												></el-input>
											</el-tag>
											<el-button class="el-icon-plus button-new-tag" size="small" @click="showInput"></el-button>
											<el-input
												class="input-new-tag"
												style="display:none"
												size="small"
												placeholder="请输入楼栋号"
												v-model="inputValue.build"
												@keyup.enter.native="handleInputConfirm($event, doorData)"
												@blur="handleInputConfirm($event, doorData)"
												data-code="build"
												maxlength="20"
											>
											</el-input>
										</div>
									</div>
									<div class="box clearfix" v-if="formdata.enableUnit&&doorData[buildingIndex] && doorData[buildingIndex].children && doorData[buildingIndex].children.length">
											<div class="label_left">单元</div>
											<div class="el-fl-left tags">
												<el-tag
													:key="index2"
													v-for="(unit, index2) in doorData[buildingIndex].children"
													closable
													:disable-transitions="false"
													data-code="unit"
													@close="handleClose('unit', index2, doorData[buildingIndex].children)"
													@click="unitIndex = index2"
													:class="{active: unitIndex === index2}"
													>
													<span @dblclick="showInput">{{unit.name}}</span>
													<el-input
														style="display:none"
														v-model='unit.name'
														@keyup.enter.native="inputConfirm($event, doorData[buildingIndex].children)"
														@blur="inputConfirm($event, doorData[buildingIndex].children)"
														data-code="unit"
														maxlength="20"
													></el-input>
												</el-tag>
												<el-button class="el-icon-plus button-new-tag" size="small" @click="showInput"></el-button>
												<el-input
													class="input-new-tag"
													style="display:none"
													size="small"
													placeholder="请输入单元号"
													v-model="inputValue.unit"
													@keyup.enter.native="handleInputConfirm($event, doorData[buildingIndex].children)"
													@blur="handleInputConfirm($event, doorData[buildingIndex].children)"
													data-code="unit"
													maxlength="20"
												>
												</el-input>
											</div>
										</div>
									</div>
									<div v-else class="empty_floor">
										<p>暂无相关信息</p>
									</div>
									<div class="title_class border_hr">
										<span class="title_txt">单元户信息</span>
										<el-tooltip v-if="doorData[buildingIndex] && doorData[buildingIndex].children && doorData[buildingIndex].children.length" class="item" effect="light" placement="right" :content="unitMsg">
										  <img  src="@/assets/img/menuicon/icon_tishi_zhengchang.png" alt="">
									  </el-tooltip>
									</div>
									<div class="unit" v-if="doorData[buildingIndex] && doorData[buildingIndex].children && doorData[buildingIndex].children.length">
										<div class="floor" v-if="doorData[buildingIndex].children[unitIndex] && doorData[buildingIndex].children[unitIndex].children && doorData[buildingIndex].children[unitIndex].children.length">
											<!-- <h2>单元户<span>鼠标双击修改名称； 修改楼层名称后，请自行修改单元户的名称</span></h2> -->
											<div
												class="box clearfix"
												:key="index3"
												v-for="(floor, index3) in doorData[buildingIndex].children[unitIndex].children"
												>
												<!-- <span class="el-fl-left label">楼层：</span> -->
												<div class="unit_left">
												<el-tag
														closable
														:disable-transitions="false"
														data-code="floor"
														@close="handleClose('floor', index3, doorData[buildingIndex].children[unitIndex].children)"
														>
														<span @dblclick="showInput">{{floor.name}}</span>
														<el-input
															style="display:none"
															v-model='floor.name'
															@keyup.enter.native="inputConfirm($event, doorData[buildingIndex].children[unitIndex].children)"
															@blur="inputConfirm($event, doorData[buildingIndex].children[unitIndex].children)"
															data-code="floor"
															maxlength="20"
														></el-input>
												</el-tag>
												<span class="unit_text">层</span>
												</div>
												<span class="el-fl-left tags">
													<div class="door" v-if="floor.children && floor.children.length">
														<el-tag
															:key="index4"
															v-for="(door, index4) in floor.children"
															closable
															:disable-transitions="false"
															data-code="door"
															@close="handleClose('door', index4, floor.children)"
															>
															<span @dblclick="showInput">{{door.name}}</span>
															<el-input
																style="display:none"
																v-model='door.name'
																@keyup.enter.native="inputConfirm($event, floor.children)"
																@blur="inputConfirm($event, floor.children)"
																data-code="door"
																maxlength="20"
															></el-input>
														</el-tag>
														<el-button class="el-icon-plus button-new-tag" size="small" @click="showInput"></el-button>
														<el-input
															class="input-new-tag"
															style="display:none"
															size="small"
															placeholder="请输入户号"
															v-model="inputValue.door"
															@keyup.enter.native="handleInputConfirm($event, floor.children)"
															@blur="handleInputConfirm($event, floor.children)"
															data-code="door"
															maxlength="20"
														>
														</el-input>
														</div>
												</span>
											</div>
											<div class="add-floor">
												<el-button class="el-icon-plus button-new-tag " size="small" @click="showInput"></el-button>
												<el-input
													class="input-new-tag"
													style="display:none"
													size="small"
													placeholder="请输入楼层号"
													v-model="inputValue.floor"
													@keyup.enter.native="handleInputConfirm($event, doorData[buildingIndex].children[unitIndex].children)"
													@blur="handleInputConfirm($event, doorData[buildingIndex].children[unitIndex].children)"
													data-code="floor"
													maxlength="20"
												>
												</el-input>
											</div>
										</div>
									</div>
									<div v-else class="unit_empty">
										<div class="center_text">
											<img src="@/assets/img/menuicon/img_wuxiaoxi@2x.png" alt=""/>
									    <span>暂无相关信息</span>
										</div>
									</div>
									</el-scrollbar>
									</div>
									<div class="btns footer_btn">
										<el-button @click="resetForm">重置</el-button>
										<el-button type="primary" @click='submit'>确认</el-button>
									</div>
							</div>
					</div>
				</div>
			</div>
		</div>
  </div>
</template>

<script>
import list from "@/utils/list";
import mapgis from "@views/system/popups/mapmarkgis"
import CoordConver from '@/utils/CoordConver.js';
import {initDoor, calcDoor} from './basedata';
const createContinueData=(type,num)=>{
  //type--类型，num生成的个数
	let objArr=[]
	if(type=='Number'){
    [...new Array(num).keys()].map((idx) => {
			let obj={label:Number(idx)+1, value:Number(idx)+1}
			objArr.push(obj);
		});
	}
	else{
		for (let i = 0; i < num; i++) {
        let letter=String.fromCharCode((65 + i));
				let obj={label:letter, value:letter}
		  	objArr.push(obj);
    }
	}
	// console.log(JSON.stringify(objArr));
	return objArr;
}
const txtI18n = {
	build: '楼栋',
	unit: '单元',
	floor: '楼层',
	door: '单元户',
}
export default {
  mixins: [list,CoordConver],
  props:['userinfo'],
	components: {
		mapgis
	},
  data() {
		const _self = this;
    return {
			 addressparams:{},
			 floorMsg:`双击可对楼栋、单元名称进行自定义修改\n单击选中楼栋、单元、单元户信息根据选中的楼栋、单元进行展示`,
			 unitMsg:'双击可对楼层、单元户名称进行更改',
		// 	 imgList: [
      //   '@/assets/img/menuicon/btn_caijiqi.png'
      // ],
			defaultProps: {
						value: 'id', // 唯一标识
						label: 'orgName', // 标签显示
						children: 'orgs' // 子级
			},
			formdata:{
				communityName:'',
			},
			unitCols:[[
				{ label: '楼栋', slot: 'floorRule',prop:'floorRule' },
		    { label: '单元', slot: 'unitRule',prop:'unitRule' },
			]],
			detailCols: [[
			 {
					label: '所属社区',
					prop: 'communityNameList',
				    slot: 'communityNameList',
			   	    placeholder: '请选择公司',
					// input: 'true'
			 },{
				label: '楼栋名称',
				prop: 'buildingName',
					input: 'true'
			 },{
				label: '楼栋编号',
				prop: 'buildingNumber',
					input: 'true'
			 },{
				label: "楼栋类型",
				prop: "buildingTypeList",
				slot: "buildingTypeList",
			},{
				label: '楼栋用途',
				prop: 'buildingPurpose',
				input: 'true'
			},{
				label: '建筑结构',
					prop: 'buildingStructure',
					slot: 'buildingStructure',
					placeholder: '请选择部门',
			},{
				label: '建成日期',
				prop: 'builtDate',
				// slot:'communityId',
				// placeholder: '请选择小区',
					date:"true",
			},{
				label: '验收日期',
				prop: 'acceptanceDate',
					date:"true",
			},{
					label: '建筑面积',
					prop: 'buildingArea',
					input: 'true'
				},{
					label: '使用面积',
					prop: 'useArea',
					input: 'true'
				},{
					label: '备注信息',
					prop: 'remarks',
					input: 'true'
				}]
			],
      detail:{},
			getWkidVal:'',
			mapInputFilter: '',
			inputlongitude:'',
      inputlatitude:'',
			getCityName:'',
			amap: null,
			lnglat: [],
			// address: '',
			code: '',
			search: '',
			copyformdata:{},
			copyrules:{},
			formdata: {
        productId : "", //
		// communityNameList:'',
        deptOrgId: "",
        communityId: "",
				acceptanceDate:'',
        planName: "",
        unit: "", // 施工单位
        phone:"",
        // address: "",
				principal:'',
				checkedUnit:false,
				enableUnit: 1,  	//勾选了复选框
				floorlevelNum:'1',//每栋层数
				householdNum:'1',//每层户数
        buildingNumber:'1',//楼栋数
				unitNumber:'2',//单元数
				preInstallNumber:'',//总单元户数
				lat:'',
				lng:'',
				rules: {
					floor: {
						type: 'Number', //  Number Letter
						start: '1', // 1 A //楼栋的起始楼栋
					  end:'1'
					},
					unit: {
						type: 'Number', //  Number letter
						start: '1', // 1 A单元的起始单元
					  end:'1'
					}
				},
      },
			floorOptions:createContinueData('Number',20),
			floorlevelOptions:createContinueData('Number',50),
			unitOptions:createContinueData('Number',20),
			unithouseOptions:createContinueData('Number',10),
			buildingIndex: 0,
			unitIndex: 0,
			doorData: [],
		  formrules:{
			  // communityNameList:[
				//   this.$valid.inputRequired('社区名称'),
				//   this.$valid.pattern(/^[\u4e00-\u9fa5A-Za-z0-9_]{2,30}$/)
				// ],
				productId: this.$valid.init(["null"]),
				communityId: this.$valid.init(["null"]),
				// phone:this.$valid.init(['phone'])
			},
			unitrules:{

			},
			inputValue: {
				build: '',
				unit: '',
				floor: '',
				door: '',
			},
		    communityNameList:[],
		    buildingTypeList:[{
				label:'高层',
				id:1
			},{
				label:'底层',
				id:2
			}]
		};
  },
  computed: {
    organListCompany() {
      let list = this.$store.getters['fileDevice/getallcompanyList'];
			return list;
    },
    organListdepartment() {
      	let list = this.$store.getters['fileDevice/getalldeptList'];
		  	return list||[];
    },
    // communityList(){
    //   let list= this.$store.getters["fileDevice/getCommunityList"];
    //   return list;
	// 		// return [{id: '', name: '全部'}].concat(list)
    // },
		// deviceModelList(){
		// 	let list= this.$store.getters["getdeviceModelList"];
      // // if(list.length>0){
		// // 		list.map(item=>{
		// // 			item.label=`${item.manufacturerName}/${item.productName}/${item.productModel}`;
		// // 		  return item;
		// // 		})
		// // 	}
      // return list;
		// },
		collapse() {
				return this.$store.getters['getCollapse'];
		},
  },
  watch: {
    params() {
      this.initParams()
    }
  },
  methods: {
		radioChange(type,val){
      let length=val=='Number'?'20':'26';
			if(val=='Letter')
			{
        if(type=='floor') {
					this.floorOptions=createContinueData(val,length);
					this.formdata.rules.floor.type='Letter'
					this.formdata.rules.floor.start='A'
					this.formdata.rules.floor.end='A'
				}else{
					this.unitOptions=createContinueData(val,length);
					this.formdata.rules.unit.type='Letter'
					this.formdata.rules.unit.start='A'
					this.formdata.rules.unit.end='A'
				}
			} else {
				if(type=='floor'){
					this.formdata.rules.floor=this.copyrules.floor;
          this.floorOptions=createContinueData(val,length);
				}
				else{
					this.formdata.rules.unit=this.copyrules.unit;
					this.unitOptions=createContinueData(val,length);
				}
			}
		},
		//深拷贝
		deepClone(obj) {
				if (typeof obj !== 'object') return;
				let newObj = obj instanceof Array ? [] : {};
				for (let key in obj) {
						if (obj.hasOwnProperty(key)) {
								newObj[key] = typeof obj[key] === 'object' ? this.deepClone(obj[key]) : obj[key];
						}
				}
				return newObj;
		},
		resetForm(){
        this.formdata={};
				this.formdata=this.copyformdata;
				this.doorData=[]
				this.$refs.detailform.validateField('productId');
				this.$refs.detailform.validateField('communityId');
		},
		showInput(e) {
			e.target.nextElementSibling.style.display = 'inline-block';
			e.target.style.display = 'none';
			e.target.nextElementSibling.firstElementChild.focus();
		},
		inputConfirm(e, arr) {
			const {value, dataset} = e.target;
			const querySame = () => _.filter(arr, (v) => v.name == value)
			if(e.target.value.length == 0) {
				this.$message.error(`${txtI18n[dataset.code]}名称不能为空，请重新命名`);
				e.target.focus();
				return;
			} else if(querySame().length > 1) {
				this.$message.error(`${txtI18n[dataset.code]}名称重复，请修改`);
				e.target.focus();
				return
			}
			e.target.parentElement.style.display = 'none';
			e.target.parentElement.previousElementSibling.style.display = 'inline-block';
		},
		handleInputConfirm(e, arr) {
			const {value, dataset} = e.target;
			if (value && dataset) {
				const {code} = dataset;
				const querySame = () => _.isEmpty(_.filter(arr, (v) => v.name == value))
				const generate = {
					build: initDoor(this.formdata).generateUnit,
					unit: initDoor(this.formdata).generateFloor,
					floor: initDoor(this.formdata).generateDoor(value)
				}
				if(querySame()) {
					arr.push({
						name: value,
						code: 'build',
						children: code != 'door' ? generate[code] : undefined
					});
					this.inputValue[code] = '';
				} else {
					this.$message.error(`${txtI18n[code]}名称重复，请重新添加`);
				}
			}
			e.target.parentElement.style.display = 'none';
			e.target.parentElement.previousElementSibling.style.display = 'inline-block';
			e.target.value = '';
    },
	 clearDoor() {
			if(!this.doorData.length)return;
			this.__confirm('是否确认清空单元户？', '清空单元户').then(v => {
				this.doorData = [];
			}).catch(() => {})
		},
		handleClose(code, index, arr) {
			this.__confirm(`是否删除该${txtI18n[code]}？`, `删除${txtI18n[code]}`).then(v => {
				switch(code) {
					case 'build':
						if(this.buildingIndex == index) {
							this.buildingIndex = 0;
							this.unitIndex = 0;
						}
						break;
					case 'unit':
						if(arr.length == 1) {
							this.$message.error('请直接删除该楼栋');
							return;
						}
						if(this.unitIndex == index) {
							this.unitIndex = 0;
						}
						break;
					case 'floor':
						if(arr.length == 1) {
							this.$message.error('请直接删除该单元');
							return;
						}
						break;
					case 'door':
						if(arr.length == 1) {
							this.$message.error('请直接删除该楼层');
							return;
						}
						break;
				}
				arr.splice(index, 1);
			}).catch(() => {})
		},
		checkedUnit(val){
      	if(val) {
					this.formdata.enableUnit = 1;
				}else {
					this.formdata.unitNumber = 1;
					this.formdata.enableUnit = 0;
				}
		},
		createDoor() {
			new Promise(resolve => {
        this.$refs.unitform.validate(resolve)
			}).then(v => {
				if(this.formdata.checkedUnit) {
					this.formdata.enableUnit = 1;
				}else {
					this.formdata.unitNumber = 1;
					this.formdata.enableUnit = 0;
				}
				let isNumberFlag=this.formdata.rules.floor.type=='Number'?true:false;
				let isNumberUnitFlag=this.formdata.rules.unit.type=='Number'?true:false;
				let checkFloor=this.formdata.rules.floor.start<=this.formdata.rules.floor.end?true:false;
				let checkUnit=this.formdata.rules.unit.start<=this.formdata.rules.unit.end?true:false;
				if(checkFloor&&isNumberFlag)
				{
				  this.formdata.buildingNumber=this.formdata.rules.floor.end-this.formdata.rules.floor.start+1;
				}
				else if(!isNumberFlag&&checkFloor){
           this.formdata.buildingNumber=this.formdata.rules.floor.end.charCodeAt()-this.formdata.rules.floor.start.charCodeAt()+1;
				}
				else{
					this.formdata.buildingNumber=1;
					this.$message.error('楼栋起始和结束设置出错');
					return;
				}
				if(this.formdata.checkedUnit)
				{
					if(checkUnit&&isNumberUnitFlag)
					{
						this.formdata.unitNumber=this.formdata.rules.unit.end-this.formdata.rules.unit.start+1;
					}
					else if(!isNumberUnitFlag&&checkUnit){
						this.formdata.unitNumber=this.formdata.rules.unit.end.charCodeAt()-this.formdata.rules.unit.start.charCodeAt()+1;
					}
					else{
						this.formdata.unitNumber=1;
						this.$message.error('单元起始和结束设置出错');
						return;
					}
				}
				this.doorData = initDoor(this.formdata).initDoor;
			})
		},
		handleInputConfirm(e, arr) {
			const {value, dataset} = e.target;
			if (value && dataset) {
				const {code} = dataset;
				const querySame = () => _.isEmpty(_.filter(arr, (v) => v.name == value))
				const generate = {
					build: initDoor(this.formdata).generateUnit,
					unit: initDoor(this.formdata).generateFloor,
					floor: initDoor(this.formdata).generateDoor(value)
				}
				if(querySame()) {
					arr.push({
						name: value,
						code: 'build',
						children: code != 'door' ? generate[code] : undefined
					});
					this.inputValue[code] = '';
				} else {
					this.$message.error(`${txtI18n[code]}名称重复，请重新添加`);
				}
			}
			e.target.parentElement.style.display = 'none';
			e.target.parentElement.previousElementSibling.style.display = 'inline-block';
			e.target.value = '';
    },
		// 获取子级传的值
		getCityNameval(val) {
				this.getCityName = val;
		},
		getwkid(val){
					this.getWkidVal = val;
		},
		querySearchAsyncBtn() {
			if(this.mapInputFilter){
					this.$refs.querySearchAsyncInput.handleFocus();
			}else{
					this.$http.post('/operation-manager/track/TaskTrack/convertXY', {
									"moveXY": this.getmoveXYVal,
									"wkid": this.getWkidVal,
									"xy": [`${this.inputlongitude},${this.inputlatitude}`]
									})
							.then(({ status, data, msg }) => {
									this.handleSelect({
											'XY':data.convertXY[0].split(','),
											'text':''
									})
							})
			}
    },
		querySearchAsync(queryString, cb) {
            if (!queryString) return;
            if(this.getWkidVal===2360){
                this.$refs.mapInit.fuzzyQueryLocation(queryString,(res)=>{
                    let newarr = []
                    res.map(item=>{
                        var itemobj = {
                            XY:[item.feature.geometry.x,item.feature.geometry.y],
                            address:item.feature.attributes.TEXTSTRING,
                            id:item.feature.attributes.OBJECTID,
                            text:item.value
                        }
                        newarr.push(itemobj)
                    })
                    cb(newarr);
                });
            }else if(this.getWkidVal===3857){
                this.AmapSearch(
                    1,
                    queryString,
                    (result) => {
                        cb(result.list);
                    },
                    false
                );
            }
    },
		 /**
         * 调用高德地图执行模糊查询
         * @param {Number} page  当前页
         * @param {String} inputval  关键字
         * @param {Function} cb 回调函数
         * @param {Boolean} isMark 是否在地图上标记点
         */
        AmapSearch(page, inputval, cb, isMark) {
            var keywords = inputval;
            AMap.plugin('AMap.PlaceSearch', () => {
                var autoOptions = {
                    city: this.getCityName,
                    citylimit: true,
                    pageIndex: page
                };
                var placeSearch = new AMap.PlaceSearch(autoOptions);
                placeSearch.search(keywords, (status, result) => {
                    if (status != 'complete') {
                        return;
                    }
                    var datas = result.poiList;
                    let count = datas.count;
                    let crupage = datas.pageIndex;
                    let arr = datas.pois;
                    var pointData = [];
                    var returnObjectList = [];
                    for (let i = 0; i < arr.length; i++) {
                        const element = arr[i];
                        var xy = [];
                        var x = element.location.lng; //经度
                        var y = element.location.lat; // 纬度
                        x = this.handle_x(x);
                        y = this.handle_y(y);
                        xy.push(x);
                        xy.push(y);

                        var returnObject = new Object();
                        returnObject.id = element.id;
                        returnObject.text = element.name;
                        returnObject.address = element.address;
                        returnObject.XY = xy;
                        var marksData = {
                            json: xy
                        };
                        pointData = pointData.concat(marksData);
                        returnObjectList.push(returnObject);
                    }
                    // var symbol = new PictureMarkSymbolArgs();
                    // symbol.url = 'images/amap_l_gray.png';
                    // symbol.height = 36;
                    // symbol.width = 36;
                    // symbol.yoffset = 15;
                    // symbol.xoffset = 3;
                    // if (isMark) {
                    //     createMarkLayer(pointData, 'vagueQueryLyr', symbol);
                    // }
                    var resDatasObj = {
                        keywords: keywords,
                        page: crupage,
                        count: count,
                        list: returnObjectList
                    };
                    cb(resDatasObj);
                });
            });
    },
		// GCJ-02 => 墨卡托
		//经度转墨卡托
		handle_x(x) {
					return (x / 180.0) * 20037508.34;
			},
		//纬度转墨卡托
		handle_y(y) {
					if (y > 85.05112) {
							y = 85.05112;
					}
					if (y < -85.05112) {
							y = -85.05112;
					}
					y = (Math.PI / 180.0) * y;
					var tmp = Math.PI / 4.0 + y / 2.0;
					return (20037508.34 * Math.log(Math.tan(tmp))) / Math.PI;
		},
		oninput(value,tip) {
				if(!value){return}
				if(tip==='x'){
						if(value>180||value<-180){
								this.$message.warning('请输入正确的经度')
								return value.substring(0,value.length-1);
						}
				}else{
							if(value>90||value<-90){
								this.$message.warning('请输入正确的纬度')
								return value.substring(0,value.length-1);
						}
				}
				let str = value;
				let len1 = str.substr(0, 1);
				let len2 = str.substr(1, 1);
				//如果第一位是0，第二位不是点，就用数字把点替换掉
				if (str.length > 1 && len1 == 0 && len2 != ".") {
						str = str.substr(1, 1);
				}
				//第一位不能是.
				if (len1 == ".") {
						str = "";
				}
				if (len1 == "+") {
						str = "";
				}
				if (len1 == "-") {
						str = "";
				}

				//限制只能输入一个小数点
				if (str.indexOf(".") != -1) {
						let str_ = str.substr(str.indexOf(".") + 1);
						if (str_.indexOf(".") != -1) {
						str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
						}
				}
				//正则替换
				str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
				str = str.replace(/^\D*([0-9]\d*\.?\d{0,11})?.*$/, "$1"); // 小数点后只能输 11 位
				return str;
		},
    submit() {
			new Promise(resolve => {
        this.$refs.detailform.validate(resolve)
			}).then(v => {
				const {buildNumber, unitNumber, floorNumber, doorNumber} = calcDoor(this.doorData,this.formdata.checkedUnit);
				const txt = `请检查信息是否填写完整（包含重复名称，名称为空现象）<br>确认提交单元户信息：<br>总楼栋数：${buildNumber}${this.formdata.enableUnit ? `<br>总单元数：${unitNumber}` : ''}<br>总楼层数：${floorNumber}<br>总单元户数：${doorNumber}`
				this.__confirm(txt, '提交').then(v => {
					this.formdata.installPlanDataList = this.doorData;
					// this.formdata.deviceTypeIds = Array.of(this.data.deviceTypeIds);
					// console.log('this.data.deviceTypeIds',typeof(this.data.deviceTypeIds.join('')))
					this.formdata.preInstallNumber = doorNumber;
					// this.data.deviceTypeIds
					const url = '/sc-community-web/assets/building/add';
					console.log(this.formdata,'++++++++++++++++++++++++++++++++c')
					this.$http.post(url, this.formdata).then(({ msg, status }) => {
						this.$message({
							type: status === 0 ? 'success' : 'error',
							message: msg
						})
						if(status === 0) {
							this.$emit('close')
							this.$emit('refresh')
						}
					}).catch(() => {})

					let buildingAddEditData=JSON.parse(sessionStorage.getItem('buildingAddEdit'));
					if(buildingAddEditData.todo=="edit"){

					}else{

					}
				}).catch(() => {})
			})
		},
		getDeviceStatusName(val) {
      switch (val) {
        case 1:
          return "正常";
        case 2:
          return "离线";
        case 3:
          return "报警";
        case 4:
          return "未启用";
        default:
          return val;
      }
    },
		querySearchAsync(addressName, callback) {
			if(addressName) {
				// let self = this;
				AMap.plugin('AMap.Autocomplete', function(){
					// 实例化Autocomplete
					var autoOptions = {
						//city 限定城市，默认全国
						city: '全国'
					}
					var autoComplete= new AMap.Autocomplete(autoOptions);
					autoComplete.search(addressName, (status, result) => {
						// 搜索成功时，result即是对应的匹配数据
						if(status === 'complete' && result.info === 'OK') {
							_.each(result.tips, (v) => {
								if(!v.location) return;
								v.value = v.district + v.name;
								v.locationArray = [v.location.lng, v.location.lat];
							})
							const list = result.tips || [{}];
							callback(list);
						} else{
							// self.$message.error('地名查询失败')
							callback([])
						}
					})
				})
			} else {
				callback([])
			}
		},
		handleSelect(obj) {
			this.amap.clearMap();
			this.amap.setCenter(obj.locationArray)
			this.lnglat = obj.locationArray;
			this.address = obj.value;
			this.code = obj.adcode;
			new AMap.Marker({
				map: this.amap,
				position: obj.locationArray,
				content: `
					<div class='map_mark_icon'></div>
				`,
				offset: new AMap.Pixel(-(10 * this.scale), -(28 * this.scale))
			})
			let infoWindow = new AMap.InfoWindow({
				isCustom: true,  //使用自定义窗体
				content: `
					<div class='map_mark_content'>`+obj.district+obj.address+`</div>
				`,
				offset: new AMap.Pixel(0, -(36 * this.scale))
			});
			this.amap.clearInfoWindow()
			infoWindow.open(this.amap, obj.locationArray);
			this.amap.setFitView()
		},
		getDetailMap(){
			let deviceid=this.params.data.id
      this.$api.device.getDetail(deviceid).then(({ status, msg, data }) => {
          if (status === 0) {
            this.detail = data;
            new Promise((resolve) => {
              if (data.lng && data.lat) {
                resolve([data.lng, data.lat]);
              } else {
                AMap.plugin("AMap.Geocoder", () => {
                  const geocoder = new AMap.Geocoder({
                    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                    city: "全国"
                  });
                  const address =
                    data.address ||
                    data.provinceName
                      .concat(data.cityName)
                      .concat(data.regionName)
                      .concat(data.communityName);
                  if (address) {
                    geocoder.getLocation(address, (s, result) => {
                      if (s === "complete" && result.info === "OK") {
                        const { lng, lat } = result.geocodes[0].location;
                        resolve([lng, lat]);
                      } else {
                        resolve();
                      }
                    });
                  }
                });
              }
            }).then((pos) => {
              if (pos&&pos.length) {
                /* eslint-disable */
                new AMap.Marker({
                  map: this.amap,
                  position: pos,
                  content: '<span class="map_mark_icon"></span>',
                  offset: new AMap.Pixel(-23, -23)
                });
                this.amap.setZoomAndCenter(15, pos);
              } else {
                this.amap.setZoomAndCenter(7, [116.379927, 39.971675]);
              }
            });
            if (!data.lng || !data.lat) return;
          } else {
            this.$message.error(msg);
          }
        });
		},
		initMap(){
      this.$nextTick(() => {
        this.amap = new AMap.Map("detailMap", {
          resizeEnable: true,
          pitch: 0, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: "3D", // 地图模式
          zooms: [4, 19]
        });
      });
		},
		gobackMap(){
       this.islistShow = false;
			 this.$emit("showMap");
		},
		gobackLastLevel(){
			  this.islistShow = true;
        // this.$emit("show-map");
		},
    // 搜索条件重置
    resetSearch() {
      this.productCategoryId = [0];
      this.selectedTreeId = '';
      this.expandedTreeKeys = [];
      this.mixins_query.deviceStatus = 0;
      this.mixins_query.productCategoryId = 0;
      this.$refs.times.reset()
    },
    exportFile(type) {
      if (type == 'template') {
        this.$exportExcel('/device/device/manage/downTemplate');
      } else {
        this.$commonExportExcel('/device/device/manage/pageList', '/device/device/manage/getDeviceListExcel', this.mixins_query, '设备')
      }
    },
    productChange(arr) {
      const len = arr.length;
      if (len === 1) {
        this.mixins_query.productCategoryId = arr[0]
      } else if (len === 2) {
        this.mixins_query.productCategoryId = arr[0]
        this.mixins_query.manufacturerId = arr[1]
      } else {
        this.mixins_query.productCategoryId = arr[0]
        this.mixins_query.manufacturerId = arr[1]
        this.mixins_query.productId = arr[2]
      }
      this.$refs.cascader && this.$refs.cascader.toggleDropDownVisible(false)
    },
    // 新增
    add() {
      // this.$store.dispatch("openModal", {
      //   url: "/devices/DeviceInfo/add",
      //   title: "设备注册",
      //   height: '680px'
      // });
    },
    // 编辑
    editRow(row) {
      // this.$store.dispatch("openModal", {
      //   url: "/devices/DeviceInfo/add",
      //   title: `编辑-${row.deviceNo}`,
      //   height: '70%',
      //   params: { ...row }
      // });
    },
    // 更新日期
    updateDate(key, value) {
      let val
      if (key === 'startDate') {
        val = value ? `${value}000000` : val
      } else {
        val = value ? `${value}235959` : val
      }
      this.mixins_query[key] = val;
    },
    // 跳转至详情
    goDetail({ id, deviceNo, productId, productCategoryName = '' }) {
      this.openNewPage("/devices/DeviceInfo/detail", `${deviceNo}`, { id, deviceNo, productId, productCategoryName, isCollapse: true, backTabId: this.params.id })
    },
    // 删除设备
    deleteRow({ productCategoryName, deviceNo, productName, id }) {
      this.$msgBox(`是否删除设备“${productCategoryName}/${productName}-${deviceNo}”`).then(() => {
        const params = { id }
        const $loading = this.$loading()
        this.$http.delete('/device/device/manage/delete', { params }).then(({ status, msg }) => {
          $loading.close()
          this.$message({
            type: status === 0 ? 'success' : 'error',
            message: msg
          })
          if (status === 0) {
            this.mixins_search('del')
          }
        })
      }).catch(() => {})
    },
    beforeImport(file) {
      const size = __CONFIG.excelLimitSize;
      const isExcel =
        file.name.lastIndexOf(".xls") !== -1 ||
        file.name.lastIndexOf(".xlsx") !== -1 ||
        file.name.lastIndexOf(".xlsm") !== -1;
      const isLtSize = file.size / 1024 / 1024 < size;
      if (!isExcel) {
        this.$message.error("导入文件只支持.xls、.xlsx或.xlsm格式的Excel!");
      } else if (!isLtSize) {
        this.$message.error(`上传Excel表格大小不能超过${size}Mb!`);
      }
      document.querySelector('#inputHidden').focus()
      return isExcel && isLtSize;
    },
    batchImport(content) {
      const formData = new FormData();
      formData.append("file", content.file);
      const loading = this.$loading();
      this.$http.post("/zoniot-rmcp-web/device/device/manage/importExcel", formData).then(({ status, msg }) => {
        loading.close();
        if (status === 0) {
          this.$message.success("上传成功，请稍后在导入/导出历史查看上传结果");
          setTimeout(() => {
            this.$store.dispatch("getMessageCount");
            this.callback && this.callback();
          }, 1500);
        } else {
          this.$message.error(msg);
        }
      }).catch(() => {
        loading.close();
      });
    },
    areaChange(arr) {
      const { dimensionCode = "", id = "", key = '' } = _.last(arr) || {};
      const keys = [
        "provinceId",
        "cityId",
        "regionId",
        "communityId",
        "buildingId"
      ];
      keys.forEach((key1) => {
        if (key1.indexOf(dimensionCode) != -1) {
          this.mixins_query[key1] = id;
        } else {
          this.mixins_query[key1] = "";
        }
      });
      this.selectedTreeId = key;
      this.expandedTreeKeys = _.reduce(
        arr,
        (result, v) => {
          if (v.key != key) {
            result.push(v.key);
          }
          return result;
        },
        []
      );
      this.mixins_search();
    },
	  communityList(){
		  this.communityNameList=[];
		  let onOption='';
		  this.$http.get('/assets/community/list', {}).then((res) => {
			  res.data.map(res=>{
				  onOption={
					  label:res.communityName,
					  id:res.id
				  }
				  this.communityNameList.push(onOption)
			  })
		  });
	  },

	  //加载楼栋详情展示
	  buildingAddEdit(){
		  let buildingAddEditData=JSON.parse(sessionStorage.getItem('buildingAddEdit'));
		  if(buildingAddEditData.todo=="edit"){
			  this.$http.get('/sc-community-web/assets/building/house/find', {id:buildingAddEditData.id}).then((res) => {
				  console.log(res)
				  // formdata.communityName
				  if(res.status==0){
				  	this.formdata.communityName=res.data.communityId;
					this.formdata.buildingName=res.data.buildingName;
					  this.formdata.buildingType=res.data.buildingType;
					  this.formdata.buildingNumber=res.data.buildingNumber;
					  this.formdata.buildingPurpose=res.data.buildingPurpose;
					  this.formdata.buildingArea=res.data.buildingArea;
					  this.formdata.builtDate=res.data.builtDate;
					  this.formdata.useArea=res.data.useArea;
					  this.formdata.remarks=res.data.remarks;
				  }else{
					  this.formdata.communityName='';
					  this.formdata.buildingName='';
					  this.formdata.buildingType='';
					  this.formdata.buildingNumber='';
					  this.formdata.buildingPurpose='';
					  this.formdata.buildingArea='';
					  this.formdata.builtDate='';
					  this.formdata.useArea='';
					  this.formdata.remarks='';
				  }
			  });
		  }else{

		  }
	  }
  },
  mounted() {
    // this.initMap();
  },
  created() {
	  this.buildingAddEdit();

  	this.communityList();
		this.copyformdata=this.deepClone(this.formdata);



		this.copyrules=JSON.parse(JSON.stringify(this.formdata.rules))

  }
};
</script>
<style lang="scss">
@import './popup.scss';
.device-info.addinstall{
  padding:0;
}
</style>
