<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="数据集名称: ">
        <el-input v-model="addForm.data_set_name" ></el-input>
      </el-form-item>

      <el-form-item label="所属分类: ">
        <el-select v-model="addForm.big_type_id" placeholder="请选择服务类型" @change="bigTypeValueChange">
          <el-option v-for="(item,index) in bigTypeOptions" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="表名: " >
        <el-input v-model="addForm.tablename" ></el-input>
      </el-form-item>

       <el-form-item label="矢量数据: ">
        <el-input v-model="addForm.demension" ></el-input>
      </el-form-item>

       <el-form-item label="服务类型: " prop="service_type_id">
        <el-select v-model="addForm.service_type_id" placeholder="请选择服务类型" @change="serviceTypeValueChange">
         <el-option v-for="(item,index) in serviceTypeOptions" :key="index" :label="item.name" :value="item.id" ></el-option>
        </el-select>
      </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="上传shp文件" size="mini">
        <el-upload
        size="mini"
            class="upload-demo"
            action="#"
            drag
            :limit="limit"
            :on-preview="handlePreview"
            :file-list="fileList"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-error="handleError"
        >
          <i class="el-icon-upload" style="font-size:60px;line-height:0px;"></i>
          <div class="el-upload__text">将Shp文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
      <el-form-item label="封面图片: " >
        <div class="image-container" style="position:relative;width:150px;float:left;margin-right:12px;" v-if="coverImage!=null">
          <div @click="delImage('coverImage',coverImage.path,0)" class="del-btn" style="height:40px;width:40px;text-align:center;line-height:40px;position:absolute;right:8px;top:8px;border-radius:50%;background:rgba(255,255,255,0.4)">
            <span><i class="el-icon-delete"></i></span>
          </div>
          <img  :src="BASE_IMAGE_URL+'/'+coverImage.path" alt="" width="150px" height="150px">
        </div>
        <el-upload
          ref="upload"
          action="string"
          accept=".png,.jpg,.docx,.xlsx,.xls"
          list-type="picture-card"
          :show-file-list="false"
          :on-preview="handlePictureCardPreviewAfterImage"
          :on-success="handleSuccessAfterImage"
          :on-exceed="handleExceedAfterImage"
          :http-request="UploadCoverImage">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="功能描述图片: " >
        <div class="image-container" style="position:relative;width:150px;float:left;margin-right:12px;" v-for="(item,index) in descImages" :key="index" >
          <div @click="delImage('descImage',item.path,index)" class="del-btn" style="height:40px;width:40px;text-align:center;line-height:40px;position:absolute;right:8px;top:8px;border-radius:50%;background:rgba(255,255,255,0.4)">
            <span><i class="el-icon-delete"></i></span>
          </div>
          <img  :src="BASE_IMAGE_URL+'/'+item.path" alt="" width="150px" height="150px">
        </div>
        <el-upload
          ref="upload"
          action="string"
          accept=".png,.jpg,.docx,.xlsx,.xls"
          list-type="picture-card"
          :show-file-list="false"
          :on-preview="handlePictureCardPreviewAfterImage"
          :on-success="handleSuccessAfterImage"
          :on-exceed="handleExceedAfterImage"
          :http-request="UploadDescImage">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">更新服务</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { postMethodCommon, getMethodCommon } from '../../../api/common';
let BASE_IMAGE_URL = process.env.VUE_APP_BASE_IMG_URL;
export default {
  name:"AddForm",
  props:['id'],
  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:1,
      fileList: [],
      serviceType:null,
    }
  },
  created(){
    this.getDictionary();
    this.getServiceDetail();
  },
  methods:{
    getServiceDetail(){
     
      postMethodCommon("/CimService/GetServiceById?id="+this.id).then(res=>{
        if(res.code == 200){
          this.addForm = res.result;
          if(res.result.cover_img!=null){
            this.coverImage = {
                id: res.result.cover_img.id,
                path:res.result.cover_img.path
            }
          }else{
            // this.coverImage = {
            //     id:"",
            //     path:""
            // }
          }
         
         
          res.result.desc_imgs.forEach((item,index)=>{
             console.log("item",item);
            let obj = {
              id:item.id,
              path:item.path
            }
             this.descImages.push(obj);
             
          })
         console.log(this.descImages);
        }
      })
    },
    delImage(type,path,index){
      postMethodCommon("/CimService/DeleteFileByPath?paths="+path).then(res=>{
        console.log(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 ='/Files/Upload'
      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();
        } 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/Upload`
        postMethodCommon(url, formData).then(res => {
          if (res.code === 200) {
            _this.addForm.filepath = res.result[0].filePath

            _this.addForm.coverImage = this.coverImage;
            _this.addForm.descImages = this.descImages;
            delete _this.addForm.cover_img;
            delete _this.addForm.desc_imgs;
            postMethodCommon("/CimService/AddOrUpdate",this.addForm).then(response=>{
              if(response.code == 200){
                this.$emit("editSuccess");
                this.$message({
                  type:"success",
                  message:"更新服务成功"
                })
              }
            })
          }
        })
      }else{
        _this.addForm.coverImage = this.coverImage;
        _this.addForm.descImages = this.descImages;
        delete _this.addForm.cover_img;
        delete _this.addForm.desc_imgs;
        postMethodCommon("/CimService/AddOrUpdate",this.addForm).then(response=>{
          if(response.code == 200){
            this.$emit("editSuccess");
            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
    }
  }
}
</script>
<style scoped>
.service-type-btn{
  width:100%;
  height:180px;
  text-align: center;
  margin-top:100px;
}
</style>