<template>
  <div>
    <el-drawer
      v-loading="loading"
      :show-close="false"
      :title="curObj.id ? '编辑楼盘' : '新增楼盘'"
      :wrapper-closable="false"
      :close-on-press-escape="false"
      :visible.sync="isShow"
      size="960px"
      custom-class="xl-drawer"
      direction="rtl"
    >
      <base-form ref="ruleForm" class="lib-edit" :data="formData" :is-inline="false" label-width="110px" :insertSlotArr="[24,25]">
        <div slot="OI24" class="scoped-house-type">
          <div class="sht-main">
            <div class="sht-op" v-for="(ht, three) in houseTypeArr" :key="three">
              <el-upload
                class="sht-img"
                :action="`${domainUrl}/adm/upload/cloud`"
                :data="{logic_type: 'estate', token}"
                name="upload"
                :show-file-list="false"
                :on-success="houseTypeUploadSuccess"
                :on-error="houseTypeUploadError"
                :before-upload="houseTypeUploadBefore"
              >
                <img v-if="ht.img_url" :src="ht.img_url + '_adm0'" class="img" @click="houseTypeUploadImg(three)">
                <i v-else class="el-icon-plus icon" @click="houseTypeUploadImg(three)"/>
                <img v-if="ht.img_url" :src="ht.img_url + '_adm0'" class="sht-img-big">
              </el-upload>
              <div class="sht-deal">
                <el-input class="sht-input" placeholder="输面积" v-model="ht.area">
                  <template slot="append">㎡</template>
                </el-input>
                <el-select class="sht-select" v-model="ht.house_type_val" placeholder="请选择">
                  <el-option
                    v-for="item in $dictData.house_type"
                    :key="item.val"
                    :label="item.key"
                    :value="item.val">
                  </el-option>
                </el-select>
                <span class="sht-del"  @click="houseTypeDel(three)">删除</span>
              </div>
            </div>
            <div class="sht-add" @click="houseTypeAdd()">添加户型</div>
          </div>
        </div>
        <div slot="OI25" class="scoped-other-form">
          <el-form-item label="点位坐标" class="scoped-item-two item">
            纬度N<el-input v-model="cObj.latitude" disabled />
            经度E<el-input v-model="cObj.longitude" disabled />
            <el-button type="primary" class="map-btn" size="small" @click="openMap">点击从地图获取</el-button>
          </el-form-item>
        </div>
      </base-form>
      <div class="xl-form">
        <div class="xl-form-footer fixed" style="width:960px;padding-top: 20px;border-top: 1px solid #dcdcdc;right:0;">
          <el-button class="xl-form-btn t2" @click="close">关 闭</el-button>
          <el-button class="xl-form-btn t1" @click="close('confirm')">确定</el-button>
        </div>
      </div>
    </el-drawer>
    <handle-map :is-show="isShowMap" @close="closeMap" />
  </div>
</template>
<script>
import { arrToObj } from '@/utils'
import handleMap from '@/components/Common/Map'
export default {
  components: {
    handleMap,
  },
  mixins,
  props: {
    isShow: Boolean,
    curObj: Object
  },
  inject: ['parentData'],
  data() {
    const token = window.sessionStorage.getItem('fp_token')
    let domainUrl = process.env.VUE_APP_BASE_API
    return {
      domainUrl,
      token,
      loading: false,
      formData: [],
      cObj: {},
      isShowMap: false,
      tempImgIndex: 0,
      ptObj: {},
      houseTypeArr: [],
    }
  },
  watch: {
    isShow: function(val) {
      if (val) {
        if (this.curObj.id) {
          this.loading = true
          this.$api.house.admestatedetail({id: this.curObj.id}).then(res => {
            let curData = res || {}
            if (curData.house_type) curData.house_type = curData.house_type.split(',')
            if (curData.product_type) curData.product_type = curData.product_type.split(',')
            if (curData.hospital_type) curData.hospital_type = curData.hospital_type.split(',')
            if (curData.high_street) curData.high_street = curData.high_street.split(',')
            if (curData.park_type) curData.park_type = curData.park_type.split(',')
            if (curData.metro_line) curData.metro_line = curData.metro_line.split(',')
            if (curData.metro_type) curData.metro_type = curData.metro_type.split(',')
            this.cObj = curData || {}
            let houseTypeArr = curData.area_data || []
            houseTypeArr.map((one) =>{
              one.product_type_name = arrToObj(this.$dictData.product_type)[one.product_type_val]
            })
            this.houseTypeArr = [...houseTypeArr]
            this.getDef()
            this.loading = false
          })
        } else {
          this.cObj = this.curObj
          this.getDef()
        }
      }
    },
  },
  methods: {
    houseTypeAdd () {
      let houseTypeArr = [...this.houseTypeArr]
      houseTypeArr.push({
        house_type_val: '',
        img_url: '',
        area: '',
      })
      this.houseTypeArr = [...houseTypeArr]
    },
    houseTypeDel (index) {
      let houseTypeArr = [...this.houseTypeArr]
      houseTypeArr.splice(index, 1)
      this.houseTypeArr = [...houseTypeArr]
    },
    // houseTypeChange (index) {
    //   let houseTypeArr = [...this.houseTypeArr]
    //   house_type_val
    //   let tempList = []
    //   let houseTypeList = houseTypeArr[one].house_type_list || []
    //   const curVal = houseTypeArr[one].house_type_list_val ||[]
    //   curVal.forEach(v =>{
    //     let cObj = {
    //       house_type_name: arrToObj(this.$dictData.house_type)[v],
    //       house_type_val: v,
    //       area_list: [{img_url: '', area: '0'}]
    //     }
    //     houseTypeList.forEach((h, hIndex) =>{
    //       if (v === String(h.house_type_val)) {
    //         cObj.area_list = houseTypeList[hIndex].area_list || []
    //       }
    //     })
    //     tempList.push(cObj)
    //   })
    //   houseTypeArr[one].house_type_list = tempList
    //   this.houseTypeArr = [...houseTypeArr]
    // },
    houseTypeUploadImg (index) {
      this.tempImgIndex = index
    },
    houseTypeUploadSuccess(res, file) {
      const data = res.data || {}
      let houseTypeArr = [...this.houseTypeArr]
      houseTypeArr[this.tempImgIndex].img_url =  `${data.url}`
      this.houseTypeArr = [...houseTypeArr]
    },
    houseTypeUploadError(file) {
      this.$msg('上传失败')
      // this.changeHandle(file)
    },
    houseTypeUploadBefore(file) {
      const isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2M!')
      }
      return isJPGPNG && isLt2M
    },
    getDef (str, strKey, strParams) {
      let params = {}
      if (str === 'change') {
        params = {...this.cObj, ...this.$refs.ruleForm.baseForm}
      } else {
        params = { ...this.cObj }
      }
      let disabled = false
      if (params.id) disabled = true
      this.formData = [
        { label: '楼盘名称', key: 'estate_name', rules: 1 },
        { label: '所属区域', key: 'area_type', type: 'select', class: 'c-3', options: this.$dictData.area_type },
        // { label: '周边医院', key: 'hospital_type', type: 'select', class: 'c-3', options: this.$dictData.hospital_type, multiple: true },
        // { label: '周边商圈', key: 'high_street', type: 'select', class: 'c-3', options: this.$dictData.high_street, multiple: true },
        // { label: '周边公园', key: 'park_type', type: 'select', class: 'c-3', options: this.$dictData.park_type, multiple: true },
        { label: '建设时间', key: 'build_time', class: 'c-3', type: 'datePicker', type2: 'month', valueFormat: 'yyyy-MM'},
        { label: '竣工时间', key: 'complete_time', class: 'c-3', type: 'datePicker', type2: 'month', valueFormat: 'yyyy-MM'},
        { label: '容积率', key: 'plot_ratio', class: 'c-3'},
        { label: '占地面积', key: 'acreage', class: 'c-3', type: 'inputFont', appendFont: '㎡'},
        { label: '建筑面积', key: 'built_up_area', class: 'c-3', type: 'inputFont', appendFont: '㎡'},
        { label: '总户数', key: 'household', class: 'c-3', type: 'inputFont', appendFont: '户', rules: [
          { validator: (rule, value, callback) => {
            if (Number(value) < 0 || isNaN(Number(value))) {
              callback(new Error('请输入数字'))
            } else {
              callback()
            }
          }, trigger: 'blur' },
          // { type: 'number', message: '请输入数字', trigger: 'blur' }
        ]},
        { label: '物业公司', key: 'property_type', class: 'c-3'},
        { label: '物业费', key: 'property_fee', class: 'c-3'},
        { label: '车位数量', key: 'parking', class: 'c-3', type: 'inputFont', appendFont: '个'},
        { label: '绿化率', key: 'green_rate', class: 'c-3', type: 'inputFont', appendFont: '%' },
        { label: '楼盘标签', key: 'estate_tag', type: 'select', class: 'c-3', options: this.$dictData.estate_tag, rules: 1 },
        { label: '自定义标签', key: 'custom_tag', class: 'c-3' },
        { label: '开发商', key: 'developer', class: 'c-3' }, 
        { label: '楼栋数', key: 'seat_sum', class: 'c-3', type: 'inputFont', appendFont: '栋' },
        { label: '产权年限', key: 'ownership', class: 'c-3' },
        { label: '初次交付时间', key: 'deliver_time', class: 'c-3', type: 'datePicker', type2: 'month', valueFormat: 'yyyy-MM'},
        { label: '楼盘单价', key: 'price_range', class: 'c-3', type: 'inputFont', appendFont: '/㎡', rules: 1 },
        { label: '户型面积区间', key: 'built_area', class: 'c-3', type: 'inputFont', appendFont: '㎡' },
        { label: '产品类型', key: 'product_type', type: 'select', options: this.$dictData.product_type, multiple: true},
        // { label: '房型', key: 'house_type', type: 'select', options: this.$dictData.house_type, multiple: true},
        // { label: '面积', label2: '多个面积英文逗号,分开(如:100,120)', key: 'house_area', type: 'inputFont', appendFont: '㎡'},
        // { label: '均价范围1', key: 'price_min', class: 'c-3', type: 'inputFont', appendFont: '元(最小)'},
        // { label: '均价范围2', key: 'price_max', class: 'c-3', type: 'inputFont', appendFont: '元(最大)'},
        { label: '楼盘地址', key: 'address', rules: 1 },
        // { label: '是否新房', key: 'is_new', type: 'select', class: 'c-3', options: this.$dictData.sys_yesno, rules: 1 },
        // { label: '梯户比', label2: '如:2梯4户', key: 'stairs_rate', class: 'c-3' },
        { label: '不利因素', key: 'minus_points' },
        { label: '楼盘图', key: 'pri_image', class: 'c-3', type: 'cuImg',
          options: {
            w: 375,
            h: 250,
            SY: 1,
          }
        , rules: 1 },
        { label: '简评', key: 'remarked', class: 'c-3s', type: 'textarea' },
      ]
      params.pri_image = this.IMadd(params.pri_image)
      this.setDefaultValue(params)
    },
    close (str) {
      if (str === 'confirm') {
        this.$refs['ruleForm'].$refs['baseForm'].validate((valid) => {
          if (valid) {
            const oldform = this.$refs.ruleForm.baseForm
            const newForm = { ...oldform }
            if (this.curObj.id) newForm.id = this.curObj.id
            newForm.longitude = this.cObj.longitude
            newForm.latitude = this.cObj.latitude
            if (!newForm.longitude) return this.$msgw('请选择经度！')
            else if (!newForm.latitude) return this.$msgw('请选择纬度！')
            if (newForm.house_type) newForm.house_type = newForm.house_type.join(',')
            if (newForm.product_type) newForm.product_type = newForm.product_type.join(',')
            if (newForm.hospital_type) newForm.hospital_type = newForm.hospital_type.join(',')
            if (newForm.high_street) newForm.high_street = newForm.high_street.join(',')
            if (newForm.park_type) newForm.park_type = newForm.park_type.join(',')
            if (newForm.metro_line) newForm.metro_line = newForm.metro_line.join(',')
            if (newForm.metro_type) newForm.metro_type = newForm.metro_type.join(',')
            newForm.custom_tag = newForm.custom_tag.replace(/，|、|\/|\\/g, ',')
            if (!newForm.standard) newForm.standard = ''
            // newForm.stairs_rate = newForm.stairs_rate.replace('，', ',')
            let houseTypeArr = this.houseTypeArr || []
            if (houseTypeArr.length === 0) {
              newForm.area_data = ''
            } else {
              newForm.area_data = JSON.stringify([...houseTypeArr])
            }
            let apiStr = 'admestateadd'
            if (this.curObj.id) apiStr = 'admestateedit'
            newForm.pri_image = this.IMdel(newForm.pri_image)
            this.$api.house[apiStr](newForm).then(data => {
              this.$msgs(newForm.id ? '编辑成功' : '新增成功')
              this.houseTypeArr = []
              this.$emit('close', newForm)
            })
          }
        })
      } else {
        this.$emit('close')
        this.houseTypeArr = []
        this.setDefaultValue()
      }
    },
    openMap() { // 定位
      this.isShowMap = true
      const pointObj = {
        latitude: this.cObj.latitude || '',
        longitude: this.cObj.longitude || '',
        address: this.cObj.address || ''
      }
      this.$root.$emit('handleMap', pointObj)
    },
    closeMap(obj) {
      if (obj) {
        const oldform = this.$refs.ruleForm.baseForm
        const newForm = { ...oldform, ...obj }
        this.cObj = newForm
        this.setDefaultValue(newForm)
      }
      this.isShowMap = false
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../../../styles/libEdit.scss';
.lib-edit {
  width: 900px;
  padding-top: 0;
  padding-left: 0;
  padding-bottom: 40px;
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
  ::v-deep .el-date-editor.el-input {
    width: 100%;
  }
}
.scoped-other-form {
  .scoped-item-two {
    .el-input {
      display: inline-block;
      width: 140px;
      margin: 0 10px;
    }
  }
}
.map-btn{
  height: 36px;
}
::v-deep .el-drawer__header {
  margin-bottom: 10px;
}

.scoped-house-type {
  margin: 20px;
  .sht-op {
    text-align: center;
    display: inline-block;
    vertical-align: middle;
    margin-right: 20px;
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #dcdcdc;
  }
  .sht-add {
    border: 1px dashed #0c78b1;
    text-align: center;
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    width: 142px;
    height: 142px;
    line-height: 142px;
    cursor: pointer;
    font-size: 16px;
    color: #0c78b1;
  }
  .sht-img {
    display: inline-block;
    vertical-align: middle;
    width: 82px;
    height: 82px;
    border: 1px dashed #999;
    position: relative;
    box-sizing: border-box;
    margin-right: 10px;
    &:hover {
      .sht-img-big {
        display: block;
      }
    }
    img {
      width: 80px;
      height: 80px;
    }
    .sht-img-big {
      position: absolute;
      top: 80px;
      left: 0;
      width: 400px;
      height: auto;
      display: none;
      box-shadow: 0 0 20px #ccc;
      z-index: 99;
    }
    .el-icon-plus {
      color: #999;
      padding: 30px;
    }
  }
  .sht-deal {
    display: inline-block;
    vertical-align: middle;
    width: 140px;
  }
  .sht-input {
    width: 140px;
    border: 1px solid #dcdcdc;
    height: 36px;
    text-align: center;
    border-radius: 0;
    outline: none;
    color: #666;
    font-size: 12px;
    margin-bottom: 10px;
  }
  .sht-select {
    width: 140px;
    margin-bottom: 10px;
  }
  .sht-del {
    font-size: 12px;
    background: #e6a23c;
    color: #fff;
    width: 100%;
    height: 26px;
    line-height: 26px;
    cursor: pointer;
    display: inline-block;
  }
}


.scoped-sp-box {
  position: absolute;
  top: -2px;
  right: 0;
  background: #fff;
  ::v-deep {
    .el-input__inner {
      width: 80px;
    }
    .el-input-group__append {
      background: #f2f2f2;
    }
  }
}
</style>
