<template>
  <el-row class="formContainer" style="width: 100%;height:765px;overflow-y:scroll;">
    <el-col :span="24">
      <el-form :model="ruleForm" :rules="rules" ref="formData" label-width="110px" class="demo-ruleForm">
        <el-form-item label="案件编号" prop="case_no">
          <el-input v-model="ruleForm.case_no" disabled></el-input>
        </el-form-item>
        <el-form-item label="案件详情" prop="case_description">
          <el-input v-model="ruleForm.case_description"></el-input>
        </el-form-item>
       
        <el-form-item label="违规类型" prop="typeid">
          <el-select v-model="ruleForm.typeid" placeholder="请选择" style="width:100%" clearable @change="violationChange">
                <el-option
                    v-for="item in violationOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
       
        <el-form-item label="图斑面积" prop="area">
          <el-input v-model="ruleForm.area"></el-input>
        </el-form-item>

        <el-form-item label="县/区" prop="countyid">
          
            <el-row >
                <el-col :span="18">
                    <el-select v-model="ruleForm.countyid" placeholder="请选择" style="width:100%" @change="cityChange">
                        <el-option
                            v-for="item in cityDatas"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-button type="default" style="margin-left:12px;" @click="getZoning()">自动获取</el-button>
                </el-col>
            </el-row>

        </el-form-item>
        <el-form-item label="乡镇/街道" prop="streetid">
          <el-select v-model="ruleForm.streetid" placeholder="请选择" style="width:100%" @change="streetChange">
                <el-option
                    v-for="item in streetDatas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="社区/村" prop="communityid" :key="communitynameKey">
            <el-select v-model="selectcommunityname" placeholder="请选择" style="width:100%" @change="communtyChange">
                    <el-option
                        v-for="item in communtDatas"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="现场照片" prop="pic_list">
            <div style="display:flex;flex-wrap:wrap;">
                <div v-for="(item,index) in abbreviationPicListData" :key="index" style="width:200px;height:100px;margin:5px;position:relative;float:left;margin-right:12px;">
                    <div style="position:absolute;top:0px;right:6px;">
                        <el-button type="primary" icon="el-icon-search" circle size="mini" @click="lookImage(index)"></el-button>
                        <el-button type="danger" :disabled="ruleForm.is_intact==99?true:false" icon="el-icon-delete" circle size="mini" @click="delImage(index,item)"></el-button>
                    </div>
                       <img :src="item.thumbnail" style="width:200px;height:100px;cursor:pointer" @click="lookImage(index)">
                </div>
                <div style="float:left;width:200px;height:100px;border:1px solid #dcdcdc;border-radius:4px;margin-top:6px;margin-left:4px;line-height:100px;">
                    <!-- <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <i  class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload> -->
                     <el-upload
                        :action="imageUploadUrl"
                        class="avatar-uploader"
                        :show-file-list="false"
                        name="files"
                        :data="{project:'DroneEnforcement'}"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <i  class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </div>
            </div>
        </el-form-item>
        <div class="buttonContainer">
          <el-button @click="resetForm('formData')">取消</el-button>
          <el-button type="primary" :disabled="ruleForm.is_intact==99?true:false" @click="saveForm('formData')">保存</el-button>
          <el-button type="success" :disabled="ruleForm.is_intact==99?true:false" @click="submitForm('formData')">提交</el-button>
          <el-button type="warning" :disabled="ruleForm.is_intact==99?true:false" @click="eventClose(ruleForm)">关闭</el-button>
        </div> 
      </el-form>
    </el-col>

     <el-image-viewer v-if="lookimageviewer"  :on-close="closeViewer" style="z-index:100000000;width:55%;overflow:hidden" :url-list="[priwImg]" ></el-image-viewer>

  </el-row>
</template>

<script>
import * as imageConversion from 'image-conversion'
import {getMethodCommon,postMethodCommon} from "@/api/common";
import {DeleteDroneFiles,GetOrgAreaByPoint} from '@/api/forms.js'
let BASE_API = process.env.VUE_APP_BASE_IMG_URL
import ElImageViewer from 'element-ui/packages/image/src/image-viewer.vue'
let BASE_IMAGE_URL = process.env.VUE_APP_BASE_IMG_URL;
export default {
  name: "form",
  props:["ruleForm"],
  components:{
    ElImageViewer
  },
  data() {
    return {
        communitynameKey:1,
        selectcommunityname:this.ruleForm.communityname,
        dialogImageUrl: '',
        dialogVisible: false,
        priwImg:null,
        lookimageviewer:false,
        deleteImageList:[],
        formData:[],
        imageUploadUrl:BASE_IMAGE_URL+"/api/Platform/Upload?project=DroneEnforcement",
        picListData:[],
        abbreviationPicListData:[],
        violationOptions: [],
        caseStatusOptions: [],
        handleOptions: [
            { id: 0 , name: '待办'},
            { id: 1 , name: '在办'},
            { id: 2 , name: '办结'}
        ],
        areasDatas:[],
        cityDatas:[],
        streetDatas:[],
        communtDatas:[],
        rules: {
            typeid: [
                { required: true, message: '违规类型不得为空', trigger: 'blur' }
            ],
            handle_status_id: [
                { required: true, message: '处理状态不得为空', trigger: 'blur' }
            ]
        }
    }
  },
  created() {
    this.getFormData()
  },
  mounted(){
    this.getNoBuildStatus() //获取违规类型
    this.getCaseStatusOptions() //获取案件类型
    this.getAreasData() //获取地区
    this.ruleForm.countyid = 'e49b02f6-70b0-4f47-bdda-41a69002be11'
    this.ruleForm.countyname = '费县'
    // this.ruleForm.streetid = '2637e090-56ae-45bc-a57d-abe9e55438a4'
    // this.ruleForm.streetname = '探沂镇'
    
  },
  watch:{
    //  '$store.state.townshipName':function(e){
    //       this.ruleForm.streetname = e.name;
    //   },
  },
  methods: {
    //   获取区划,
      getZoning(){
          GetOrgAreaByPoint({lng:this.formData.info.lng,lat:this.formData.info.lat}).then(res=>{
              this.ruleForm.streetid = res.result.streetid;

              this.streetChange(this.ruleForm.streetid);

              this.ruleForm.communityid = res.result.communityid;

              if(this.ruleForm.communityid){
                let arr = this.areasDatas.filter(item=>{
                    return item.id == this.ruleForm.communityid;
                })
                this.ruleForm.communityname = arr[0].name;
              }
              if(this.ruleForm.communityid){
                this.communtyChange(this.ruleForm.communityid);
              }
              this.selectcommunityname = this.ruleForm.communityname;
            //   this.communitynameKey = Math.random();
          })
      },
    beforeAvatarUpload(file) {

        return new Promise((resolve, reject) => {
            let isLt2M = file.size / 1024 / 1024 < 0.5 // 判定图片大小是否小于4MB
            if (isLt2M) {
                // console.log("file",file);
                resolve(file)
            }else{
                // console.log("resFile",file) // 压缩到300KB,这里的400就是要压缩的大小,可自定义
                imageConversion.compressAccurately(file,300).then(res=>{
                    resolve(res)
                })
            }
           
        })


        
        // const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        // if (!isLt2M) {
        //     this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return isJPG && isLt2M
    },
     handleAvatarSuccess(res, file) {
        //   赋值picListData
        let item = {};
        item.path = BASE_IMAGE_URL+'/'+res.result[0].filePath;
        item.thumbnail = BASE_IMAGE_URL+'/S_'+res.result[0].filePath;
        this.picListData.push(item);
        //   缩略图
        this.abbreviationPicListData.push(item);
    },
     handleRemove(file, fileList) {
    },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      lookImage(idx){
          this.priwImg = this.picListData[idx].path;
          this.lookimageviewer = true;

      },
      closeViewer(){
          this.lookimageviewer = false;
      },
      delImage(idx,img){
          this.picListData = this.picListData.filter((item,index)=>{
              if(index == idx){
                if(img.id != null){
                    this.thoroughDelImage(img.id);
                }
              }
              return index != idx;
          })
          this.abbreviationPicListData = this.abbreviationPicListData.filter((item,index)=>{
              if(index == idx){
               
              }
              return index != idx;
          })
      },
    thoroughDelImage(imgid){
        DeleteDroneFiles([imgid]).then(res=>{
            if(res.code == 200){

            }
        })
    },
    resetForm(){
        this.close()
    },
    close(){
        this.$emit('close')
    },
    getFormData(){
        this.picListData = []
        getMethodCommon('/DroneCaseinfo/GetCaseInfo',{id: this.ruleForm.id}).then(res => {
            this.formData = res.result
            // console.log("res",res.result);
            res.result.pics.forEach(item=>{
                let src = item.path;
                item.path = BASE_API + '/' + item.path;
                item.thumbnail = BASE_API + '/S_' + src;
                this.picListData.push(item);
                this.abbreviationPicListData.push(item);
            })
        })
    },
    getNoBuildStatus(){
        getMethodCommon('/Categorys/LoadList',{typeid: "DRONE_CASE_TYPE"}).then(res => {
            this.violationOptions = res.result
        })
    },
    getCaseStatusOptions(){
        getMethodCommon('/Categorys/LoadList',{typeid: "DRONE_CASE_STATUS"}).then(res => {
            this.caseStatusOptions = res.result
        })
    },
    getAreasData(){
        getMethodCommon('/Orgs/LoadOrgList',{name:'费县'}).then(res => {
            this.areasDatas = res.result
            res.result.forEach(item =>{
                if(item.parentName == '临沂市'){
                    this.cityDatas.push(item)
                }
                if(item.parentId == this.ruleForm.countyid){
                    this.streetDatas.push(item)
                }
                if(item.parentId == this.ruleForm.streetid){
                    this.communtDatas.push(item)
                }
            })
            // console.log("streetDatas",this.streetDatas)
            // let _this = this;
            // let arr = this.streetDatas.filter(item=>{
            //     console.log(111);
            //     return item.name == _this.$store.state.townshipName.name;
            // })
            // this.ruleForm.streetid = arr[0].id;
            // this.streetChange(this.ruleForm.streetid);
        })
    },
    violationChange(data){
        this.violationOptions.forEach(item =>{
            if(item.id == data){
                this.ruleForm.typename = item.name
            }
        })
    },
    handleStatusChange(data){
        this.handleOptions.forEach(item =>{
            if(item.id == data){
                this.ruleForm.handle_status_name = item.name
            }
        })
    },
    cityChange(data){
        
        this.streetDatas = []
        this.ruleForm.streetid = ''
        this.ruleForm.streetname = ''
        this.ruleForm.communityid = ''
        this.ruleForm.communityname = ''
        this.cityDatas.forEach(item =>{
            if(item.id == data){
                this.ruleForm.countyname = item.name
            }
        })
        this.areasDatas.forEach(item =>{
            if(item.parentId == data){
                this.streetDatas.push(item)
            }
        })
    },
    streetChange(data){
        this.communtDatas = []
        // this.ruleForm.communityid = ''
        // this.ruleForm.communityname = ''
        this.streetDatas.forEach(item =>{
            if(item.id == data){
                this.ruleForm.streetname = item.name
            }
        })
    
        this.areasDatas.forEach(item =>{
            if(item.parentId == data){
                this.communtDatas.push(item)
            }
        })
        this.communitynameKey = Math.random();
        // this.communtyChange(this.ruleForm.communityid);
        this.ruleForm.communityname = null;
        this.ruleForm.communityid = null;
        // this.selectcommunityname = this.ruleForm.communityname;
        this.selectcommunityname = null;
        
    },
    communtyChange(data){
        this.communtDatas.forEach(item =>{
            if(item.id == data){
                this.ruleForm.communityid = item.id
                this.ruleForm.communityname = item.name
            }
        })
    },
    caseStatusChange(data){
        this.caseStatusOptions.forEach(item =>{
            if(item.id == data){
                this.ruleForm.case_status_name = item.name
            }
        })
    },
    handleImagePath(str){
        let portPath = str.substr(str.lastIndexOf(":"));
        let path = portPath.substr(portPath.indexOf('/')+1);
        return path;
    },
    //保存
    saveForm(){
        this.formData.info = this.ruleForm
        let arr = this.picListData;
        // console.log("arr",arr);
        this.formData.pic_list  = [];
        for(let i =0;i<arr.length;i++){
            // this.formData.pic_list[i]=this.picListData[i].split("6001/")[1];
            this.formData.pic_list[i]=this.handleImagePath(this.picListData[i].path);
        }
        postMethodCommon('/DroneCaseinfo/AddDroneCaseInfo',this.formData).then(res => {
            if(res.code == 200){
                this.$notify({
                    title: '成功',
                    message: '保存成功',
                    type: 'success',
                    duration: 2000
                })
            this.close();
            }
        })

    },
    eventClose(data){
        this.$confirm('确认关闭此案件?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
            getMethodCommon('/DroneCaseinfo/CloseDroneCaseInfo',{id: data.id}).then(res => {
                if(res.code == 200){
                this.$message({
                    type: 'success',
                    message: '关闭成功!'
                });
                this.close();
                }
            })
            
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消关闭'
            });          
        });
    },
    submitForm(formName){ //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editData();
        } else {
          return false;
        }
      });
    },
    editData(){
        this.formData.info = this.ruleForm
        this.formData.info.is_intact = 1
        let arr = this.picListData;
        this.formData.pic_list  = [];
        for(let i =0;i<arr.length;i++){
            // this.formData.pic_list[i]=this.picListData[i].split("6001/")[1];
             this.formData.pic_list[i]=this.handleImagePath(this.picListData[i].path);
        }
        postMethodCommon('/DroneCaseinfo/UpdateDroneCaseInfoIntact',this.formData).then(res => {
            if(res.code == 200){
                this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                })
            this.close();
            }
        })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 0px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.formContainer{
  width:100%;
  height:400px;
 
}
.formContainer::-webkit-scrollbar {
  width: 10px;
  height: 10px;
 
}
.formContainer::-webkit-scrollbar-track {
  border-radius: 10px;
}
.formContainer::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: rgba(0,0,0,0.1);
}
.custom-theme .el-form-item{
    margin-bottom: 15px !important;
}
.custom-theme .el-form-item__error{
    padding-top: 0 !important;
}
::v-deep .el-form-item__label{
    font-size: 12px !important;
    font-weight: normal !important;
}
.demo-ruleForm{
    padding: 10px 20px 20px 0;
}
.buttonContainer{
    display: flex;
    width: 60%;
    margin: 0 auto;
    justify-content: space-around;
}
.avatar-uploader{
    width:200px;
    height:100px;
    line-height: 100px;
}
.avatar-uploader-icon{
    height:100px;
    line-height: 100px;
}
</style>
