<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="工具名称: ">
        <el-input v-model="addForm.model.name" ></el-input>
      </el-form-item>

      <el-form-item label="是否推荐: ">
        <el-radio-group v-model="addForm.model.is_recommend">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="功能描述: ">
        <el-input v-model="addForm.model.description" ></el-input>
      </el-form-item>
      <el-form-item label="工具代码: " >
        <el-input v-model="addForm.model.code" ></el-input>
      </el-form-item>

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

      <el-form-item label="工具类型: " >
        <el-select v-model="addForm.model.typeid" placeholder="请选择工具类型" @change="serviceTypeValueChange">
         <el-option v-for="(item,index) in toolTypeOptions" :key="index" :label="item.name" :value="item.id" ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属工具: " >
        <el-select v-model="addForm.model.parentid" placeholder="请选择工具" @change="parentToolValueChange">
         <el-option v-for="(item,index) in toolOptions" :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="封面图片: " >
        <div class="image-container"  style="position:relative;width:150px;float:left;margin-right:12px;" v-if="coverImage.path!=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';
const BASE_API = process.env.VUE_APP_BASE;
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:{
        model:{},
        cover_img:null,
        describe_img_list:[],
      },
      rules:{
        name:[
            { required: true, message: '请输入服务名称', trigger: 'blur' },
        ],
        url:[
            { required: true, message: '请输入服务地址', trigger: 'blur' },
        ],
        typeid:[
            { required: true, message: '请输入服务类型', trigger: 'blur' },
        ],
        data_type:[
            { required: true, message: '请输入服务类型', trigger: 'blur' },
        ],
      },
      BASE_API : BASE_API,
      coverImage:{
        id:null,
        path:null,
      },
      descImages:[],
      bigTypeOptions:[],
      toolTypeOptions:[],
      toolOptions:[],
      limit:1,
      fileList: [],
      serviceType:null,
    }
  },
  created(){
    this.getDictionary();
    this.getToolOptions();

    this.getToolDetail();
  },
  methods:{
    getToolDetail(){
      getMethodCommon("/CimBackStageManagement/GetCimTools",{id:this.id}).then(res=>{
        if(res.code == 200){
          this.descImages=  [];
          this.addForm = res.result;
          // this.addForm.model.parentname = this.addForm.model.parentname;
          // this.addForm.model.parentid = this.addForm.model.parentid;
          // this.addForm.model.typename = this.addForm.model.typename;
          // this.addForm.model.typeid = this.addForm.model.typeid;
          this.coverImage = {
            id:"",
            path:res.result.cover_img != null ? res.result.cover_img : null,
          };
          res.result.describe_img_list.forEach(item=>{
            let obj = {
              id:"",
              path:item,
            }
            this.descImages.push(obj);
          })
        }
      })
    },
    getToolOptions(){
      getMethodCommon("/CimBackStageManagement/LoadCimToolsList",{page:1,limit:999}).then(res=>{
        if(res.code == 200){
          this.toolOptions = res.data;
          
        }
      })
    },
    delImage(type,path,index){
      postMethodCommon("/CimService/DeleteFileByPath?paths="+path).then(res=>{
        if(res.code == 200){
          if(type == 'coverImage'){
            this.coverImage.path=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
          }
          console.log(this.coverImage);
        }
			})
    },
    UploadDescImage(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){
          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.toolTypeOptions.filter((item,index)=>{
        return item.id == id;
      })
      this.addForm.model.typename = arr[0].name;
    },
    parentToolValueChange(id){
      let arr = this.toolOptions.filter((item,index)=>{
        return item.Id == id;
      })
      this.addForm.model.parentname = 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.coverImage){
         _this.addForm.cover_img = this.coverImage.path;
      }
      if(this.descImages.length>0){
        _this.addForm.describe_img_list = [];
        this.descImages.forEach(item=>{
          _this.addForm.describe_img_list.push(item.path);
        })
      }

      console.log(this.addForm);
  
      postMethodCommon("/CimBackStageManagement/AddOrUpdateCimTools",this.addForm).then(response=>{
        if(response.code == 200){
          this.$emit("editSuccess");
          this.$message({
            type:"success",
            message:"添加工具成功"
          })
        }
      })
    },
    getDictionary(){

      getMethodCommon('/Categorys/LoadList',{typeId: "CIM_TOOL_TYPE"}).then(res => {
            this.toolTypeOptions = 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>