<template>
  <div style="padding-top:30px;width:100%;height:100%;overflow:auto;padding:40px 20px; background: rgba(0, 9, 34, 0.6);">
    <el-form ref="form"  size="mini" :model="addForm" :rules="rules"  label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="防火站点名称: " prop="siteName">
            <el-input v-model="addForm.siteName" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="防火站点地址: " prop="siteAddress">
            <el-input v-model="addForm.siteAddress" style="width: calc( 100% - 60px);margin-right:12px;"></el-input> 
            <el-button type="primary" size="mini" icon="el-icon el-icon-location-outline" @click="selectAddressVisible = true;"></el-button>
          </el-form-item>
      </el-col>
      </el-row>
      

      <el-row colum="">
        <el-col :span="12">
          <el-form-item label="站点负责人姓名: " prop="director">
            <el-input v-model="addForm.director" ></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="负责人电话: "  prop="phone">
            <el-input v-model="addForm.phone" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="是否有人值守: " prop="isonduty">
              <el-radio-group v-model="addForm.isonduty" >
                <el-radio :label="true" >是</el-radio>
                <el-radio :label="false" >否</el-radio>
              </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="是否接收进山消息: " prop="isreceive">
                <el-radio-group v-model="addForm.isreceive" >
                  <el-radio :label="true" >是</el-radio>
                  <el-radio :label="false" >否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-col>
      </el-row>
      

      <el-form-item label="消息接收人员: ">
        <p style="color:#fff;">
          （扫码信息消息接收人员）
        <el-link type="primary" style="float:right;" @click="selectUserVisible = true;"> <i class="el-icon el-icon-plus"></i>添加人员</el-link>

        </p>
        <el-table
          :data="addForm.siteUser"
          border
          style="width: 100%">
          
          <el-table-column
            prop="name"
            label="用户姓名"
            align="center"
            >
          </el-table-column>

          <el-table-column
            prop="phone"
            label="联系电话"
            align="center"
            >
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="delUser(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">保存信息</el-button>
        <el-button @click="close()">取消</el-button>
      </el-form-item>
    </el-form>

    <div class="select-address-container" v-if="selectAddressVisible">
      <selectAddress @cancle="selectAddressVisible=false" :currentLngLat="currentLngLat" @confirm="selectAddressSuccess"></selectAddress>
    </div>

    <div class="select-user-container" v-if="selectUserVisible">
      <selectUser @cancle="selectUserVisible=false" @confirm="selectUserSuccess"></selectUser>
    </div>
  </div>
</template>
<script>
import { postMethodCommon, getMethodCommon } from '../../../../api/common';
import form from '../../../../store/modules/form';
let BASE_IMAGE_URL = process.env.VUE_APP_BASE_IMG_URL;
import selectAddress from './selectAddress.vue';
import selectUser from './SelectRoles.vue';
// let BASE_IMAGE_URL = BASE_IMAGE_API_URL;
export default {
  name:"AddForm",
  components:{
    selectAddress,
    selectUser
  },
  props:["detailInfo"],
  data(){
    return {
      BASE_IMAGE_URL:BASE_IMAGE_URL,
      addForm:{
        siteUser:[
          
        ]
      },
      rules:{
        siteName:[
            { required: true, message: '请输入站点名称', trigger: 'blur' },
        ],
        siteAddress:[
            { required: true, message: '请输入站点地址', trigger: 'blur' },
        ],
        director:[
            { required: true, message: '请输入负责人姓名', trigger: 'blur' },
        ],
        phone:[
            { required: true, message: '请输入负责人电话', trigger: 'blur' },
        ],
      },
      coverImage:null,
      descImages:[],
      bigTypeOptions:[],
      serviceTypeOptions:[],
      limit:999,
      fileList: [],
      serviceType:null,
      tablenameExists:false,
      newServiceId:null,
      filename:"",
      selectAddressVisible:false,
      selectUserVisible:false,
      currentLngLat:null,
    }
  },
  created(){
    this.getSiteDetail();
  },
  methods:{
    getSiteDetail(){
      getMethodCommon("/FireCodeApp/GetSiteInfo",{siteId:this.detailInfo.id}).then(res=>{
        if(res.code == 200){
          this.addForm = res.data;
          this.currentLngLat = [this.addForm.lng,this.addForm.lat]
        }
      })
    },
    handleClose(index) {
        this.addForm.siteUser.splice(index, 1);
      },
    selectAddressSuccess(e){


      let address = e.name;
      // this.addForm.siteAddress = address;
      let coor = e.location.split(",");
      this.currentLngLat = coor;
      this.addForm.lng = coor[0];
      this.addForm.lat = coor[1];

      console.log("selectAddressSuccess",e);
      this.selectAddressVisible = false;
    },
    selectUserSuccess(e){
      e.forEach((item,index)=>{
        let obj = {
          "siteUserId": item.Id,
          "userRole": 0,
          "name": item.Name,
          "phone": item.Account
        }
        this.addForm.siteUser.push(obj);
      })
      this.selectUserVisible = false;
    },  
    delUser(scope){
      this.addForm.siteUser.splice(scope.$index,1);
    },
    addSymbol(){
        if(window.event.keyCode==13){
  // 			 var rawData = $("#"+id).val();
  // 			 $("#"+id).val(rawData+"\n");
          var textarea = document.getElementById("service_description");
          var position = cursorPosition.get(textarea);
          cursorPosition.add(textarea, position, "\n");
          console.log(this.addForm.data_description);
      }
    },
    checkTableName(){
      getMethodCommon("/CimService/IsExistTable",{table:this.addForm.tablename}).then(res=>{
        if(res.code == 200){
          console.log(res);
          this.tablenameExists = res.result;
        }
      })
    },
    delImage(type,path,index){

      postMethodCommon("/CimService/DeleteFileByPath?paths="+path).then(res=>{
        
      })

      if(type == 'coverImage'){
        this.coverImage = null;
      }
      if(type == 'descImage'){
        let arr = [];
        for(let i=0;i<this.descImages.length;i++){
          if(i != index){
            arr.push(this.descImages[i])
          }
        }
        this.descImages = arr;
      }
    },
    handleSuccessAfterImage(response,file,fileList){

    },
    // 上传处理后图片
    handlePictureCardPreviewAfterImage(file) {
			console.log('aaa',file)
		},
    handleExceedAfterImage(files, fileList) {
			this.$message.warning(`只能选择一个文件`);
    },
    // 上传合法 证明材料图片
    UploadCoverImage(param){
			let formData = new FormData()
			formData.append('files', param.file)
			let url = BASE_IMAGE_URL + '/api/Platform/Upload?project=CimPlatform';
			postMethodCommon(url,formData).then(res =>{
        if(res.code == 200){
          this.coverImage = {
            id:res.result[0].id,
            path:res.result[0].filePath
          }
        }
			})
    },
    UploadDescImage(param){
			let formData = new FormData()
			formData.append('files', param.file)
			let url = BASE_IMAGE_URL + '/api/Platform/Upload?project=CimPlatform';
			postMethodCommon(url,formData).then(res =>{
        if(res.code == 200){
          let obj = {
            id:res.result[0].id,
            path:res.result[0].filePath
          }
          this.descImages.push(obj);
        }
			})
    },
    bigTypeValueChange(id){
      let arr = this.bigTypeOptions.filter((item,index)=>{
        return item.id == id;
      })
      this.addForm.big_type_name = arr[0].name;
    },
    serviceTypeValueChange(id){
      let arr = this.serviceTypeOptions.filter((item,index)=>{
        return item.id == id;
      })
      this.addForm.service_type_name = arr[0].name;
    },
    submitForm(formName) {
     

      this.$refs[formName].validate((valid) => {
        if (valid) {
          //  this.createData();
          this.addFormData();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    createData(){
      let _this = this
      if(this.fileList.length>0){
        let formData = new FormData();
        this.fileList.forEach(item => {
          formData.append("files", item.raw);
        });
        if (this.fileList.length === 0) {
          this.$message.warning(`请选择上传文件!!`)
          return;
        }
        let url = '/Files/UploadShpFiles?tablename='+this.addForm.tablename;
        postMethodCommon(url, formData).then(res => {
          if (res.code === 200) {
            let importShpFormData = {
              filepath: res.result,
              tablename: this.addForm.tablename,
              serviceid:this.newServiceId
            }
            this.importShpToDatabase(importShpFormData);
          }
        })
      }else{
        this.addFormData();
      }
    },
    //上传shp
    uploadSheFile(){
      let _this = this
      if(this.fileList.length>0){
        let formData = new FormData();
        this.fileList.forEach(item => {
          formData.append("files", item.raw);
        });
        if (this.fileList.length === 0) {
          this.$message.warning(`请选择上传文件!!`)
          return
        }
        let url = '/Files/UploadShpFiles?tablename='+this.addForm.tablename;
        postMethodCommon(url, formData).then(res => {
          if (res.code === 200) {
            // this.filename = this.fileList
            let importShpFormData = {
              filepath: res.result,
              tablename: this.addForm.tablename,
              serviceid:this.newServiceId,
              srid: 0
            }
            this.importShpToDatabase(importShpFormData);
          }
        })
      }else{
        return;
      }
    },
    // 导入shp到数据库
    importShpToDatabase(formData){
      postMethodCommon("/CimService/ImportShpData",formData).then(res=>{
        if(res.code == 200){
          this.$emit("addSuccess");
          this.$message({
            type:"success",
            message:"添加服务成功"
          })
        }else{
          this.$emit("addSuccess");
          this.$message({
            type:"warning",
            message:"服务基本信息添加成功，导入shp文件失败，请重新导入！"
          })
        }
      }).catch(e=>{
          this.$emit("addSuccess");
          this.$message({
            type:"warning",
            message:"服务基本信息添加成功，导入shp文件失败，请重新导入！"
          })
      })
    },
    // 添加服务
    addFormData(){
      postMethodCommon("/FireCodeApp/EditSiteInfo",this.addForm).then(response=>{
        if(response.code == 200){
            this.$emit("addSuccess");
            this.$message({
              type:"success",
              message:"保存信息成功"
            })
        }
      })
    },
    getDictionary(){

      getMethodCommon('/Categorys/LoadList',{typeid: "CIM_SERVICE_TYPE"}).then(res => {
            this.serviceTypeOptions = res.result
      })

      getMethodCommon('/Categorys/LoadList',{typeid: "CIM_SERVICE_BIGTYPE"}).then(res => {
            this.bigTypeOptions = res.result
      })

    },
      //文件上传时的钩子
    handlePreview(file) {

    },
    // 删除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 文件上传成功
    handleSuccess(res, file, fileList) {
      this.$message.success('文件上传成功')
    },
    // 文件超出个数限制
    handleExceed(files, fileList) {
      this.$message.warning(`只能选择 ${this.limit} 个文件进行上传!!`)
    },
    // 文件状态改变
    handleChange(file, fileList) {
      // this.form.name = file.name.split(".")[0]
      // let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      // let size = file.size / 1024 / 1024;

      // if (extension !== 'shp') {

      //   this.$message.warning('只能上传后缀是.shp的文件')
      //   return false
      // }

      // if (size > 100) {
      //   this.$message.warning('文件大小不得超过100M')
      //   return false
      // }
    
      if (file) {
        this.fileList = fileList
      }

    },
    // 文件上传失败
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      let size = file.size / 1024 / 1024;
      if (extension !== 'shp') {

        this.$message.warning('只能上传后缀是.shp的文件')
        return false
      }
      if (size > 100) {
        this.$message.warning('文件大小不得超过100M')
        return false
      }
      return true
    },
    close(){
      this.$emit("close");
    }
  }
}
</script>
<style scoped>
.service-type-btn{
  width:100%;
  height:180px;
  text-align: center;
  margin-top:100px;
}

.select-address-container{
  width:100%;
  height:100%;
  position:absolute;
  top:0px;
  left:0px;
  z-index:999;
}

.select-user-container{
  width:100%;
  height:100%;
  position:absolute;
  top:0px;
  left:0px;
  z-index:99999;
}

::v-deep .el-form-item__label{
  color:#fff!important;
}

::v-deep .el-radio{
  color:#fff;
}

::v-deep .el-table th.el-table__cell{
  border:0px !important;
  border-bottom:1px!important;
  border-color:#fff!important;
}

::v-deep .el-table{
  border-color: #fff!important;
}

::v-deep .el-table--border .el-table__cell{
  border-color:#fff;
}

::v-deep .el-input__inner{
  border-radius:0px;
}

::v-deep .el-button{
  border-radius:0px;
}
</style>