<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.typename" placeholder="请选择" style="width:100%"  @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-select v-model="ruleForm.countyname" 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-form-item>
        <el-form-item label="乡镇/街道" prop="streetid">
          <el-select v-model="ruleForm.streetname" 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">
          <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" icon="el-icon-delete" circle size="mini" @click="delImage(index)"></el-button> -->
                    </div>
                       <img :src="item" style="width:200px;height:100px;cursor:pointer" @click="lookImage(index)">
                </div>
            </div>
        </el-form-item>
      </el-form>
    </el-col>
    <el-image-viewer v-if="lookimageviewer" :on-close="closeViewer" style="z-index:100000000;width:45%;position:absolute;left: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} 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" , "ruleFormId"],
  components:{
    ElImageViewer
  },
  data() {
    return {
        selectcommunityname:this.ruleForm.communityname,
        listQueryId:this.ruleForm.id,
        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' }
            ]
        }
    }
  },
  watch: {
    ruleForm: function (e) {
        this.selectcommunityname = e.communityname
    },
    ruleFormId: function (e) {
        this.listQueryId = e
        this.getFormData()
    },
    
  },
  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 = '探沂镇'
  },
  methods: {
    beforeAvatarUpload(file) {

        return new Promise((resolve, reject) => {
            let isLt2M = file.size / 1024 / 1024 < 0.5 // 判定图片大小是否小于4MB
            if (isLt2M) {
                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
        this.picListData.push(BASE_IMAGE_URL+'/'+res.result[0].filePath);
        //   缩略图
        this.abbreviationPicListData.push(BASE_IMAGE_URL+'/S_'+res.result[0].filePath);
    },
     handleRemove(file, fileList) {
    },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      lookImage(idx){
          this.priwImg = this.picListData[idx];
          this.lookimageviewer = true;

      },
      closeViewer(){
          this.lookimageviewer = false;
      },
      delImage(idx){
          this.picListData = this.picListData.filter((item,index)=>{
              if(index == idx){
                //   this.deleteImageList.push(item.split("6001/")[1]);
                //    this.thoroughDelImage(item.split("6001/")[1].replace(/\//g,"%5C"));
                // Common\2022\20220211\2022021116344031570158.png
              }
              return index != idx;
          })
           this.abbreviationPicListData = this.abbreviationPicListData.filter((item,index)=>{
              if(index == idx){
                //   this.deleteImageList.push(item.split("6001/")[1]);
                //    this.thoroughDelImage(item.split("6001/")[1].replace(/\//g,"%5C"));
                // Common\2022\20220211\2022021116344031570158.png
              }
              return index != idx;
          })
      },
    thoroughDelImage(imgpath){
        DeleteDroneFiles({path:imgpath}).then(res=>{
            if(res.code == 200){

            }
        })
    },
    resetForm(){
        this.close()
    },
    close(){
        this.$emit('close')
    },
    getFormData(){
        this.picListData = []
        this.abbreviationPicListData = []
        getMethodCommon('/DroneCaseinfo/GetCaseInfo',{id: this.listQueryId}).then(res => {
            this.formData = res.result
            // console.log("formData",this.formData);
            res.result.pic_list.forEach(item =>{
                let src = BASE_API + '/' + item;
                this.picListData.push(src);
                // 缩略图
                let abbreviationSrc = BASE_API+"/S_"+item;
                this.abbreviationPicListData.push(abbreviationSrc);
            })
        })
    },
    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)
                }
            })
        })
    },
    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)
            }
        })
    },
    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;
        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]);
        }
        
        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]);
        }
        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>
