<template>
  <div class="add-container">
     <div class="data-operate">
        
        <span @click="$router.push({path:'/data/layer'})"><i class="el-icon-arrow-left"></i> 返回</span>
      </div>

      <div class="form-contaner">
        <el-form ref="form" size="mini" :model="form" label-width="120px">
          <el-form-item label="图层名称">
            <el-input v-model="form.name" placeholder="请输入图层名称"></el-input>
          </el-form-item>
        
          <el-form-item label="上级分类">
            <el-cascader :options="jsonDataTree" :props="{ value: 'id',label: 'name',children: 'children',checkStrictly: true}" @change="setParentId" ></el-cascader>
          </el-form-item>

          
          <el-form-item label="图层状态">
            <el-switch v-model="form.isshow"></el-switch>
          </el-form-item>
        
          <el-form-item label="图层描述">
            <el-input type="textarea" v-model="form.desc"></el-input>
          </el-form-item>

          <!-- <el-form-item label="数据表名称">
            <el-input type="text" v-model="form.tablename"></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="最小显示等级">
            <el-input v-model.number="form.layerstyle.minZoom" type="number"></el-input>
          </el-form-item>

          <el-form-item label="最大显示等级">
            <el-input v-model.number="form.layerstyle.maxZoom" type="number"></el-input>
          </el-form-item>

          <el-form-item label="图层类型">
            <el-radio-group v-model="form.layertype">
              <el-radio :label="'fill'">面</el-radio>
              <el-radio :label="'line'">线</el-radio>
              <el-radio :label="'circle'">点</el-radio>
              <el-radio :label="'symbol'">图标</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-for="(item,index) in styles[form.layertype]" :key="index" :label="item.name">

            <el-switch v-if="item.type=='radio'" v-model="form.layerstyle.style[item.label]"></el-switch>

            <el-input v-if="item.type=='input'"  type="number" v-model.number="form.layerstyle.style[item.label]"></el-input>

            <el-color-picker v-if="item.type=='color'" v-model="form.layerstyle.style[item.label]"></el-color-picker>

            <div style="100%;height:80px;" v-if="item.type=='icon'">
              <div class="icon-box" v-for="(item,index) in 12" :key="index" :style="{'border-color':selectedIcon==index ? '#2fa6f2':'rgba(0,0,0,0)'}" @click="selectIcon(index)">
                <img :src="'/images/map/layer-type-'+(index+1)+'.png'" alt="">
              </div>
            </div>
          </el-form-item>
        
          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{submitText}}</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form> 
      </div>
  </div>
</template>
<script>
import StyleOptions from '../../../public/styleoptions/styleoptions.json'
import { getMethodCommon, postMethodCommon } from '../../api/common';
export default {
  name:"AddLayer",
  data(){
    return {
      submitText:null,
      typetree:null,
      jsonDataTree:null,
      styles:null,
      selectedIcon:0,
      form:{
        id:"",
        // tablename:"",
        name:"",
        isshow:1,
        layerstyle:{
          style:{},
          maxZoom:null,
          minZoom:null,
        },
        layertype:"fill",
      },
      limit:999,
      fileList: [],
      serviceType:null,
      tablenameExists:false,
      newServiceId:null,
      filename:"",
    }
  },
  created(){
    if(this.$route.query){
      console.log(this.$route.query)
      this.form = this.$route.query;
      this.form.layerstyle = JSON.parse(this.$route.query.layerstyle);
      this.submitText = "保存修改"
    }else{
      this.submitText = "立即创建"
    }
    this.styles = StyleOptions;
    this.loadTypeTree();
  },
  watch:{
    
  },
  methods:{
    selectIcon(index){
      this.selectedIcon = index;
      this.form.layerstyle.style['icon-image'] = 'layer-type-'+(index+1)+'.png';
    },
    setParentId(parentId){
      this.form.typeid = parentId[parentId.length-1]
    },
    loadTypeTree(){
      getMethodCommon("/Dictionary/LoadAll").then(res=>{
        if(res.code == 200){
          this.typetree = res.result;
           this.jsonDataTree = this.transData(this.typetree, 'id', 'parentId', 'children')
           console.log("jsonDataTree",this.jsonDataTree);
        }
      })
    },
    transData(jsonArr, idStr, pidStr, childrenStr){
      // 存放的最终结果树数组
      const result = [];
      const id = idStr;
      const pid = pidStr;
      const children = childrenStr;
      const len = jsonArr.length;

      // 遍历得到以id为键名的对象(建立整棵树的索引)
      const hash = {};
      jsonArr.forEach(item => {
          hash[item[id]] = item;
      });

        for (let j = 0; j < len; j++) {
            const jsonArrItem = jsonArr[j];
            const hashItem = hash[jsonArrItem[pid]];
            if (hashItem) {
                // 如果当前项还没有children属性，则添加该属性并设置为空数组
                !hashItem[children] && (hashItem[children] = []);
                hashItem[children].push(jsonArrItem);
            } else {
                result.push(jsonArrItem);
            }
        }
        return result;
    },
    onSubmit(){
      if(this.fileList.length>0){
        this.uploadSheFile();
      }else{
        this.form.isshow = this.form.isshow ? 1 : 0;
        // this.form.layerstyle = JSON.stringify(this.form.layerstyle);
        let tempForm = {...this.form};
        tempForm.layerstyle = JSON.stringify(tempForm.layerstyle);
       
        postMethodCommon("/LayerManager/Add",tempForm).then(res=>{
          if(res.code == 200){
            this.$router.push({path:'/data/layer'})
            this.$message({
              type:"success",
              message:"修改服务成功"
            })
          }
        })
      }
      // return;
      // this.form.isshow = this.form.isshow ? 1 : 0;
      // this.form.layerstyle = JSON.stringify(this.form.layerstyle);
      // postMethodCommon("/LayerManager/Add",this.form).then(res=>{
      //   if(res.code == 200){
      //     this.newServiceId = res.result;
      //     this.uploadSheFile();
      //   }
      // })
    },      //文件上传时的钩子
    handlePreview(file) {
      console.log(file);
    },
    // 删除文件
    handleRemove(file, fileList) {
      console.log(file);
      this.fileList = fileList
    },
    // 文件上传成功
    handleSuccess() {
      this.$message.success('文件上传成功')
    },
    // 文件超出个数限制
    handleExceed(files, fileList) {
      console.log(files);
      console.log(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() {
      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
    },    //上传shp
    uploadSheFile(){
      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
        }
        console.log("formData",formData);
        // debugger;
        // let url = '/Files/UploadShpFiles?tablename='+this.form.tablename;

        let tablename = "pingyi"+parseInt(Math.random()*10000000000)
        this.$axios({
            method:"post",
            url:"http://123.132.248.154:6005/api/Files/UploadShpFiles?tablename="+tablename,
            data:formData,            //参数
            headers:{
                "Content-Type":"multipart/form-data",     //请求头携带的token
                "X-Token":localStorage.getItem("Token")
            },
        }).then(res=>{
            if (res.data.code === 200) {
              let path = res.data.result;
              let tablename = path.substr(path.lastIndexOf("\\")+1,30);
              this.form.tablename = tablename;
              this.addServer(tablename,path);
            }
        })

          // postMethodCommon(url, formData).then(res => {
          //  
          // })
        }else{
          return;
        }
    },
    //添加服务接口
    addServer(tablename,path){
      this.form.tablename = tablename;
      this.form.isshow = this.form.isshow ? 1 : 0;
      this.form.layerstyle = JSON.stringify(this.form.layerstyle);
      postMethodCommon("/LayerManager/Add",this.form).then(res=>{
        if(res.code == 200){
          this.newServiceId = res.result;

          let importShpFormData = {
            filepath:path,
            serviceid:this.newServiceId,
            tablename:this.form.tablename,
            srid: 0
          }
          this.importShpToDatabase(importShpFormData);
        }
      })
    },
    // 导入shp到数据库
    importShpToDatabase(formData){
      postMethodCommon("/LayerManager/ImportShpData",formData).then(res=>{
        if(res.code == 200){
          this.$router.push({path:'/data/layer'})
          this.$message({
            type:"success",
            message:"添加服务成功"
          })
        }else{
          this.$router.push({path:'/data/layer'})
          this.$message({
            type:"warning",
            message:"服务基本信息添加成功，导入shp文件失败，请重新导入！"
          })
        }
      }).catch(e=>{
        console.log(e);
          this.$router.push({path:'/data/layer'})
          this.$message({
            type:"warning",
            message:"服务基本信息添加成功，导入shp文件失败，请重新导入！"
          })
      })
    },
  }
}
</script>
<style scoped>
.add-container{
  width:calc( 100% - 0px);
  height: calc( 100% - 40px);
  padding:20px;
  background:#1d253d;
}
.add-container .form-contaner{
    width:1000px;
  height: calc( 100% - 60px);
  background:#1d253d;
  overflow-y:auto;
}

.add-container .form-contaner::-webkit-scrollbar{
  width:10px;
}
.data-operate{
  text-indent:5px;
  width:100%;
  height:30px;
  color:#8a91aa;
  background:#2b324f;
  line-height:30px;
  margin-bottom:30px;
  cursor: pointer;
}
.item{
  width:100%;
  height:40px;
}
.item-name{
  width:120px;
  height:40px;
  line-height:40px;
  color:#8a91aa;
  float:left;
  text-align: right;
}
.item-value{
  width: calc( 100% - 140px);
  margin-left:20px;
  float:left;
  line-height: 40px;
}
::v-deep .el-input__inner{
  background:none;
  color:#8a91aa;
  box-shadow: none;
  border:1px solid #8a91aa;
  border-radius:0px;
}
::v-deep .el-textarea__inner{
  background:none;
  color:#8a91aa;
  box-shadow: none;
  border:1px solid #8a91aa;
  border-radius:0px;
}
::v-deep .el-radio__label{
  color:#8a91aa;
}

::v-deep .el-form-item__label{
  color:#8a91aa;
}

::v-deep .el-upload-dragger{
  background:rgba(0,0,0,0);
  border-radius:0px;
  border-color:#8a91aa;
  color:#8a91aa;
}
::v-deep .el-upload__text{
  color:#8a91aa;
}

::v-deep .el-color-picker__trigger{
  border-radius:0px;
  border:1px solid #8a91aa;
}
.icon-box{
  width:64px;
  height:64px;
  float:left;
  border:2px solid rgba(0,0,0,0);
  line-height: 64px;
  text-align: center;
  margin-right:6px;
  margin-bottom:6px;
  cursor:pointer;
  border-radius:3px;
}
.icon-box img{
  width:48px;
  margin-top:8px;

}
</style>