<template>
  <el-dialog
    :title="modalTitle"
    :visible.sync="modalVisible"
    :width="formLabelWidth"
    top="2vh"
    @close="handleCancel">
    <div class="mobile">
      <div class="hc-box add">
        <div class="hc-box-header">
            产品类别信息
        </div>
        <div class="hc-box-wrap">
            <el-form label-width="90px" :model="form" :rules="rules" ref="from" class="from">
                <el-form-item label="行政区域:" prop="areaAdd">
                   <el-cascader
                    ref="areaSelect"
                    v-model="form.areaAdd"
                    style="width:100%;"
                    :props="areaProps"
                    @change="handleSelectArea($event)"
                    clearable
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="区域名称:" prop="povertyAreaName">
                    <el-input type="text" v-model="form.povertyAreaName" :disabled="limit.isRead"></el-input>
                </el-form-item>
                <el-form-item label="区域描述:">
                    <el-input type="textarea"
                              :rows="3"
                              v-model="form.areaDesc"
                              :disabled="limit.isRead"></el-input>
                </el-form-item>
            </el-form>
            <el-row :gutter="20">
              <el-col :span="24">
                  <el-divider content-position="left">贫困户图片</el-divider>
                  <div class="uploadImg">
                     <el-upload
                       v-if="!limit.isRead"
                       accept=".jpg, .png"
                       :headers="upload.headers"
                       :action="upload.url"
                       :disabled="upload.isUploading"
                       :on-progress="handleFileUploadProgress"
                       :on-success="handleFileSuccess"
                       :file-list="fileList">
                       <el-button size="small" type="primary">点击上传</el-button>
                       <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                     </el-upload>
                     <ul class="uploadImgList">
                       <li v-for="(item,index) in form.areaImages" :key="index">
                         <img :src="imgRequest + item + '?imageView2/1/w/200/h/200'">
                         <span class="del" @click="handelImgRemove(index)" v-if="!limit.isRead"><i class="el-icon-delete-solid"></i></span>
                       </li>
                     </ul>
                  </div>
              </el-col>
            </el-row>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="submit" v-if="!limit.isRead">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import { areaTree , saveArea , updateArea} from "@/api/belongToSubject/area";
export default {
  name: 'addMobiel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: 'title'
    },
    action: {
      type: String,
      default: 'add'
    },
    selectRow: {
      type: Object,
      default:null
    }
  },
  watch: {
    visible(newVal, oldVal) {
      this.modalVisible = newVal;
    },
    title(newVal, oldVal) {
      this.modalTitle = newVal;
    },
    action(newVal, oldVal) {
      this.modalAction = newVal;
    },
    selectRow(newVal, oldVal) {
      this.modalSelectRow = newVal;
    }
  },
  data() {
    return {
      modalTitle: this.title,
      modalVisible: this.visible,
      modalAction: this.action,
      modalSelectRow: this.selectRow,
      formLabelWidth: '1024px',
      //窗口权限
      limit: {
        isRead: false, //是否只读
        isAdd: false //是否可写
      },
      //验证
      rules: {
        povertyAreaName: [{ required: true, message: '区域名称不能为空!', trigger: 'blur' }],
        areaAdd: [{ required: true, message: '行政区域 不能为空!', trigger: 'blur' }]
      },
      //属性
      inputVisible: false,
      inputValue:'',
      //行政区域
      areaProps:{
        lazy: true,
        checkStrictly:true,
        lazyLoad (node, resolve) {
          if (node.level === 0) {
             resolve( [{ label: '重庆市',value:'156050',leaf:false }] );
          }else{
             let params = {
               upCode:node.data.value
             }
             areaTree(params).then(res => {
                const areas = res.retBody.map((value,i) => ({
                   value:value.code,
                   label:value.name,
                   leaf:value.level >= 5
                }))
                resolve(areas)
             })
          }
        }
      },
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/upload/fileImg",
      },
      //图片列表
      fileList:[],
      //表单
      form: {
        areaImages:[],
        areaAdd:[]
      }
    };
  },
  created() {
    switch (this.modalAction) {
      case 'add':
        this.limit.isAdd = true;
        break;
      case 'edit':
        this.limit.isAdd = true;
        break;
      case 'view':
        this.limit.isRead = true;
        console.log(this.modalSelectRow)
        let datas = Object.assign({},this.modalSelectRow)
        datas.areaAdd = [datas.provinceId,datas.cityId,datas.countyId,datas.townId,datas.villageId]
        datas.areaImages = datas.areaImages === '' ? [] : datas.areaImages.split(';')
        this.form = datas
        console.log(datas)


        break;
      default:
        break;
    }
  },
  methods: {
    //区域code赋值
    handleSelectArea(event){
      let nodesCode = this.$refs.areaSelect.getCheckedNodes()[0].data.value;
      let nodesLable = this.$refs.areaSelect.getCheckedNodes()[0].data.label;
      let activeIndex = event.length
      if(activeIndex == 1){
        this.form.provinceName = nodesLable
        this.form.provinceId = nodesCode
        this.form.cityName = ''
        this.form.countyName = ''
        this.form.townName = ''
        this.form.villageName = ''
        this.form.cityId = ''
        this.form.countyId = ''
        this.form.townId = ''
        this.form.villageId = ''
      }else if(activeIndex == 2){
        this.form.cityId  = nodesCode
        this.form.countyName = nodesLable
        this.form.countyName = ''
        this.form.townName = ''
        this.form.villageName = ''
        this.form.countyId = ''
        this.form.townId = ''
        this.form.villageId = ''
      }else if(activeIndex == 3){
        this.form.countyId = nodesCode
        this.form.cityName = nodesLable
        this.form.townName = ''
        this.form.villageName = ''
        this.form.townId = ''
        this.form.villageId = ''
      }else if(activeIndex == 4){
        this.form.townId = nodesCode
        this.form.townName = nodesLable
        this.form.villageName = ''
        this.form.villageId = ''
      }else if(activeIndex == 5){
        this.form.villageId = nodesCode
        this.form.villageName = nodesLable
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
       this.upload.isUploading = true;
    },
    // 上传成功处理
    handleFileSuccess(response, file, fileList){
       this.fileList = []
       this.form.areaImages.push(response.retBody)
       this.upload.isUploading = false;
    },
    // 图片删除
    handelImgRemove(i){
      this.form.areaImages.splice(i,1)
    },
    //表单提交
    submit() {
      this.$refs.from.validate(valid => {
        if (valid) {
          let params = Object.assign({},this.form)
          params.areaAddress = params.provinceName  + params.cityName + params.townName + params.villageName
          params.areaImages = params.areaImages.join(";")
          console.log(params,this.modalAction)
          if(this.modalAction === 'add'){
             saveArea(params).then(res => {
                 if (res.retHead.errCode === 0) {
                     this.msgSuccess("操作成功");
                     this.modalVisible = false
                    this.$emit('closeModal', true);
                 }else{
                   this.msgError("保存失败，请检查!");
                 }
             });
          }else{
            updateArea(params).then(res => {
                if (res.retHead.errCode === 0) {
                    this.msgSuccess("操作成功");
                    this.modalVisible = false
                   this.$emit('closeModal', true);
                }else{
                  this.msgError("保存失败，请检查!");
                }
            });
          }
        } else {
          return false;
        }
      });
    },
    //窗口关闭
    handleCancel() {
      this.$emit('closeModal', false);
    }
  }
};
</script>

<style lang="scss" scoped>

  .el-cascader-menu .el-radio {
    display: table;
    vertical-align: middle;
    width: 90%;
    height: 100%;
    position: absolute;
    box-sizing: border-box;
    margin-left:-20px;
    padding-left:10px;
  }
  .el-cascader-menu .el-radio .el-radio__input {
    display: table-cell;
    vertical-align: middle;
  }

  .hc-box{
    border:1px solid #e9e9e9;
    margin-bottom:20px;
    .hc-box-header{
        height:40px;
        line-height:40px;
        background:#fafafa;
        font-weight:bold;
        color:#333;
        padding:0 15px;
        .action{
          margin-left:10px;
          color:#304FFE
        }
    }
    .uploadImg{
      padding:0 30px 30px 30px;
      .uploadImgList{
        list-style:none;
        margin:0;
        padding:15px 0;
        display:flex;
        flex-flow: row;
        li{
          position:relative;
          border:1px solid #ddd;
          border-radius:6px;
          width:120px;
          height:120px;
          margin-right:13px;
          img{
            width:100%;
            height:100%;
            border-radius:6px;
          }
          .del{
            display:none;
            position:absolute;
            top: -9px;
            right: -9px;
            cursor:pointer;
            i{
              font-size:20px;
              color:red;
            }
          }
          &:hover{
            .del{
              display:block;
            }
          }
        }
      }
    }
  }
</style>
