<template>
  <div style="width:100%;height:100%;overflow:auto;padding:0px 23px;">
    <!-- <div class="service-type-btn" v-if="serviceType==null">
      <el-button type="primary" style="width:200px;height:120px;" @click="serviceType = 'data'" >在线服务</el-button>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="primary" style="width:200px;height:120px;"  @click="serviceType = 'shp'">数据服务</el-button>
    </div> -->
    <el-form ref="form"  size="mini" :model="addForm" :rules="rules"  label-width="140px">
      <el-form-item label="站点名称: " prop="name">
        <el-input v-model="addForm.name" ></el-input>
      </el-form-item>

      <el-form-item label="负责人: " prop="url">
        <el-input v-model="addForm.url" ></el-input>
      </el-form-item>

      <el-form-item label="负责人电话: ">
        <el-input v-model="addForm.data_service_url" ></el-input>
      </el-form-item>

      <el-form-item label="站点地址: ">
        <el-input v-model="addForm.data_source_name" ></el-input>
      </el-form-item>

      <el-form-item label="是否有人值守: " prop="">
        	<el-radio-group v-model="addForm.isshow" >
            <el-radio :label="true" >是</el-radio>
            <el-radio :label="false" >否</el-radio>
          </el-radio-group>
      </el-form-item>

      <el-form-item label="是否接收进山消息: " prop="data_type">
        	<el-radio-group v-model="addForm.data_type" >
            <el-radio :label="'二维'" >是</el-radio>
            <el-radio :label="'三维'" >否</el-radio>
          </el-radio-group>
      </el-form-item>

      <el-form-item label="消息接收人员: ">
        <el-input v-model="addForm.srid" ></el-input>
      </el-form-item>


      <el-form-item label="防火提示语: ">
        <el-input type="textarea" style="white-space:pre-line;" :autosize="{minRows:10,maxRows:1000}"  v-model="addForm.data_description" ></el-input>
      </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>
</template>
<script>
import { postMethodCommon, getMethodCommon } from '../../../../api/common';
import form from '../../../../store/modules/form';
let BASE_IMAGE_URL = process.env.BASE_IMAGE_URL;
export default {
  name:"AddForm",
  data(){
    return {
      BASE_IMAGE_URL:BASE_IMAGE_URL,
      addForm:{},
      rules:{
        name:[
            { required: true, message: '请输入服务名称', trigger: 'blur' },
        ],
        url:[
            { required: true, message: '请输入服务地址', trigger: 'blur' },
        ],
        service_type_id:[
            { required: true, message: '请输入服务类型', trigger: 'blur' },
        ],
        data_type:[
            { required: true, message: '请输入服务类型', trigger: 'blur' },
        ],
      },
      coverImage:null,
      descImages:[],
      bigTypeOptions:[],
      serviceTypeOptions:[],
      limit:999,
      fileList: [],
      serviceType:null,
      tablenameExists:false,
      newServiceId:null,
      filename:"",
    }
  },
  created(){
    this.getDictionary();
  },
  methods:{
    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.fileList.forEach((item,index)=>{
        if(index<this.fileList.length-1){
          this.filename+=item.name+",";
        }else{
          this.filename+=item.name
        }
      })

      this.addForm.filename = this.filename;

      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){
          // let updateform = {
          //   id:this.newServiceId,
          //   filename:this.filename,
          // }
          // postMethodCommon("/CimService/AddOrUpdate",updateform).then(response=>{})

          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(){
      let _this = this;
      _this.addForm.coverImage = this.coverImage;
      _this.addForm.descImages = this.descImages;
      postMethodCommon("/CimService/AddOrUpdate",this.addForm).then(response=>{
        if(response.code == 200){
          this.newServiceId = response.serviceid;
          _this.addForm.id = response.serviceid;
          // 上传shp
          if(this.fileList.length>0){
            this.uploadSheFile();
          }else{
            this.$emit("addSuccess");
            this.$message({
              type:"success",
              message:"添加服务成功"
            })
          }
          // 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;
}
</style>