<template>
  <div>
    <el-dialog
      v-loading="loading"
      :show-close="false"
      :close-on-click-modal="false"
      :visible.sync="isShow"
      :title="curObj.id ? '编辑房源' : '新增房源'"
      :fullscreen="false"
      :width="estate_id ? '960px' : '360px'"
      custom-class="xl-dialog"
      center
    >
      <base-form ref="ruleForm" :class="estate_id ? 'lib-edit' : 'lib-edit scoped-le2' " :data="formData" :is-inline="false" label-width="110px" :insertSlotArr="[2,4]">
        <div class="scoped-form-diy" slot="OI2">
          <div class="sfd-item">
            <div class="l">地址</div>
            <div class="r">
              <input type="text" v-model="diyFormObj.addr1" class="i"/>
              <div class="dot">栋座</div>
              <input type="text" v-model="diyFormObj.addr2" class="i" />
              <div class="dot">单元</div>
              <input type="text" v-model="diyFormObj.addr3" class="i" />
              <div class="dot">室号</div>
            </div>
          </div>
          <div class="sfd-item">
            <div class="l">户型</div>
            <div class="r">
              <input type="text" v-model="diyFormObj.hType1" class="i"/>
              <div class="dot">室</div>
              <input type="text" v-model="diyFormObj.hType2" class="i" />
              <div class="dot">厅</div>
              <input type="text" v-model="diyFormObj.hType3" class="i" />
              <div class="dot">卫</div>
            </div>
          </div>
          <div class="sfd-item">
            <div class="l">楼层</div>
            <div class="r">
              <input type="text" v-model="cObj.floor" class="i"/>
              <div class="dot t2">/</div>
              <input type="text" v-model="cObj.storeys" class="i" />
              <div class="dot">层</div>
            </div>
          </div>
          <div class="sfd-item">
            <div class="l">梯户比</div>
            <div class="r">
              <input type="text" v-model="diyFormObj.sRate1" class="i"/>
              <div class="dot">梯</div>
              <input type="text" v-model="diyFormObj.sRate2" class="i" />
              <div class="dot">户</div>
            </div>
          </div>
          <div class="sfd-item">
            <div class="l">上传视频</div>
            <div class="r">
              <video
                v-if="cObj.video"
                controls 
                muted 
                loop 
                width="300"
                >
                  <source 
                  :src="cObj.video" 
                  type="video/mp4" 
                  />
                </video>
              <div class="tip">上传新的视频:请等待<span class="b">上传成功</span>后再点击顶部的确定保存</div>
              <el-upload
                class="upload-demo"
                ref="upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :multiple="false"
                :limit="1"
                :file-list="fileList"
                @change="fileChange"
                :http-request="submitUpload"
                :auto-upload="true">
                <el-button slot="trigger" size="small" type="primary">选取新视频</el-button>
                <el-button v-if="fileNextResObj.total && fileNextResObj.total.percent === 100" size="small" type="success" style="margin-left: 10px;">{{ fileNextResObj.total ? fileNextResObj.total.percent === 100 ? '上传成功' :`上传中${parseInt(fileNextResObj.total.percent)}%` : '上传到服务器'}}</el-button>
                <el-progress v-else-if="fileNextResObj.total" class="tip3" :text-inside="true" :stroke-width="20" :percentage="parseInt(fileNextResObj.total.percent)"></el-progress>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
                <!-- v-else-if="fileNextResObj.total"  fileNextResObj.total.percent-->
              </el-upload>
            </div>
          </div>
        </div>
        <div slot="OI4">
          <div class="scoped-img-area">
            <div class="sia-op" v-for="(imgsrc,index) in imagesArr" :key="index">
              <img class="img" :src="imgsrc + '_adm0'" alt="img">
              <span class="close" @click="imgDel(index)"></span>
            </div>
            <el-upload
              class="sia-img"
              :action="`${domainUrl}/adm/upload/cloud`"
              :data="{logic_type: 'estate', token}"
              name="upload"
              :show-file-list="false"
              :on-success="roomAreaUploadSuccess"
              :before-upload="roomAreaUploadBefore"
              >
              <i class="el-icon-plus icon"/>
            </el-upload>
          </div>
        </div>
        <div slot="footer">
          <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 slot="otherItem" style="padding-left: 100px">
          <div v-for="(op, index) in historyPriceList" :key="index">{{ op.des }}</div>
        </div>

      </base-form>

      

    </el-dialog>
    <handle-map :is-show="isShowMap" @close="closeMap" />
  </div>
</template>
<script>
import { arrToObj } from '@/utils'
import handleMap from '@/components/Common/Map'
import * as qiniu from 'qiniu-js'
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,
      imagesArr: [],
      roomAreaList: [],
      estate_id: '',
      diyFormObj: {},
      fileList: [],
      fileConfig: {},
      fileNextResObj: {},
      fileCompleteResObj: {},
      historyPriceList: [],
    }
  },
  created () {
    this.$api.base.admuploadtoken().then(res => {
      this.fileConfig = res || {}
    })
  },
  watch: {
    isShow: function(val) {
      if (val) {
        if (this.curObj.id) {
          this.loading = true
          this.$api.house.admeshousedetail({id: this.curObj.id}).then(res => {
            let cObj = res || {}
            this.historyPriceList = cObj.history_price ? JSON.parse(cObj.history_price) : []
            this.imagesArr = cObj.images ? cObj.images.split(',') : []
            this.cObj = {...cObj}
            this.getDef()
            let diyFormObj = {...this.diyFormObj}
            const addr = cObj.house_no ? cObj.house_no.split('-') : []
            const hType = cObj.house_type ? cObj.house_type.split('-') : []
            const sRate = cObj.stairs_rate ? cObj.stairs_rate.split('-') : []
            diyFormObj = {
              addr1: addr[0],
              addr2: addr[1],
              addr3: addr[2],
              hType1: hType[0],
              hType2: hType[1],
              hType3: hType[2],
              sRate1: sRate[0],
              sRate2: sRate[1],
            }
            this.diyFormObj = {...diyFormObj}
            this.loading = false
          })
        } else {
          this.cObj = this.curObj
          this.imagesArr = []
          this.getDef()
        }
      }
    },
  },
  methods: {
    submitUpload() {
      if (this.fileNextResObj.total) {
        this.$msgConfrm('正在上传中,如需重新上传,请保存当前页面重新上传')
        return
      }
      const upload = this.$refs.upload || {}
      const curFile = upload.uploadFiles[0] || {}

      let config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
        debugLogLevel: 'INFO'
      }
      let putExtra = {
        fname: "",
        params: {},
        mimeType: null
      }

      let next = (response) =>{
        console.log(response)
        this.fileNextResObj = response
      }
      let complete = (response) =>{
        let cObj = this.cObj
        cObj.video = `${this.fileConfig.domain}/${response.key}`
        this.cObj = {...cObj}
      }

      let subscription;
      // 调用sdk上传接口获得相应的observable,控制上传和暂停
      let observable = qiniu.upload(curFile.raw, curFile.name, this.fileConfig.token, putExtra, config);
      observable.subscribe(next, null, complete)

      // this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      this.fileNextResObj = {}
      let cObj = this.cObj
      cObj.video = ''
      this.cObj = {...cObj}
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    fileChange (e) {
      console.log(e)
    },
    imgDel (index) {
      this.imagesArr.splice(index, 1)
    },
    roomAreaUploadSuccess(res, file) {
      const data = res.data || {}
      this.imagesArr.push(`${data.url}`)
    },
    roomAreaUploadBefore(file) {
      const isJPGPNG = file.type.toLowerCase() === 'image/jpeg' || file.type.toLowerCase() === 'image/png'
      const isLtM = file.size / 1024 / 1024 < 500
      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG PNG GIF 格式!')
      }
      if (!isLtM) {
        this.$message.error('上传图片大小不能超过 500M!')
      }
      return isJPGPNG && isLtM
    },
    getDef (str) {
      let params = {}
      params = { ...this.cObj }
      if (str === 'edit') {
        params = {...this.$refs.ruleForm.baseForm, ...params}
      }
      // if (!params.custom_tag) params.custom_tag = '洪楼房源'
      if (params.estate_id) {
        this.estate_id = params.estate_id
        this.formData = [
          { label: '所属楼盘', key: 'estate_id', rules: 1, type: 'selectRemote', changeHandle: this.estateChange,
            remoteParams: { skey: 'estate_name', api: `house.admestatelist?estate_tag=二手`, opKey: 'estate_name', opVal: 'id' },
            remoteOptions: [
              { keyRO: params.estate_name, valRO: params.estate_id }
            ]
          },
          { label: `面积产品户型`, label2: `快捷选择工具`, key: `HT`, type: 'select', options: this.roomAreaList, changeHandle: this.htChange,},
          
          { label: '房源标题', key: 'title', rules: 1},
          { label: '户型图', key: 'house_img', class: 'c-3', type: 'uploads' },
          { label: '房源封面', key: 'pri_image', rules: 1, class: 'c-3', type: 'cuImg',
            options: {
              w: 375,
              h: 250,
              SY: 1,
            }
          }, 
          { label: '面积', key: 'area', 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' },
          ]},
          { label: '总价', key: 'price', 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' },
          ]},
          { label: '实际总价', key: 'floor_price', 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' },
          ]},
          { label: '业主称呼', class: 'c-3', key: 'owner' },
          { label: '业主电话', class: 'c-3', key: 'owner_phone' },
          { label: '装修状态', key: 'is_dec', class: 'c-3', type: 'select', options: this.$dictData.room_dec },
          { label: '满几年', key: 'full_year', class: 'c-3', type: 'select', options: this.$dictData.house_room_year },
          { label: '有电梯', key: 'is_elevator', class: 'c-3', type: 'select', options: this.$dictData.sys_yesno },
          { label: '交房时间', key: 'delivery_at', type: 'datePicker', class: 'c-3', type2: 'month', valueFormat: 'yyyy-MM'},
          { label: '显示隐藏', key: 'hide_status', class: 'c-3', type: 'select', options: this.$dictData.hide_status },
          { label: '户型方位', key: 'position', class: 'c-3', type: 'select', options: this.$dictData.room_position },
          { label: '自定义标签', class: 'c-3', key: 'custom_tag', rules: 1 },
          { label: '置业经理', key: 'sale_id', rules: 1, class: 'c-3', type: 'selectRemote',
            remoteParams: { skey: 'sale_name', api: `user.admsaleuserlist?page_size=999`, opKey: 'sale_name', opVal: 'id' },
            remoteOptions: [
              { keyRO: params.sale_name, valRO: params.sale_id }
            ]
          },
          // { label: '销售状态', key: 'is_sold', class: 'c-3', type: 'select', options: this.$dictData.sys_yesno },
          { label: '(对外展示)房源简介', key: 'introduce', type: 'textarea' },
          { label: '备注', key: 'remarked', type: 'textarea' },
        ]
      } else {
        this.formData = [
          { label: '所属楼盘', key: 'estate_id', rules: 1, type: 'selectRemote', changeHandle: this.estateChange,
            remoteParams: { skey: 'estate_name', api: `house.admestatelist?estate_tag=二手`, opKey: 'estate_name', opVal: 'id' },
          },
        ]
      }
      params.pri_image = this.IMadd(params.pri_image)
      this.setDefaultValue(params)
    },


    estateChange (estate_id, op, cur) {
      if (estate_id) {
        this.estate_id = estate_id
        this.$api.house.admestatehousearealist({estate_id}).then(res => {
          const list = res.list || []
          const htObj = arrToObj(this.$dictData.house_type)
          const ptObj = arrToObj(this.$dictData.product_type)
          list.map(item => {
            item.key = `${ptObj[item.product_type]}-${htObj[item.house_type]}-${item.area}㎡`
            item.val = item.id
          })
          this.roomAreaList = [...list]
          this.cObj.estate_id = estate_id
          this.cObj.area_type = cur.area_type
          this.cObj.address = cur.address
          this.cObj.latitude = cur.latitude
          this.cObj.longitude = cur.longitude
          this.cObj.estate_name = cur.estate_name
          this.cObj.title = `${cur.estate_name}-${arrToObj(this.$dictData.area_type)[cur.area_type]}`
          this.cObj.product_type = ''
          this.cObj.house_type = ''
          this.cObj.area = ''
          this.cObj.house_img = ''
          this.cObj.HT = ''
          this.getDef('edit')
        })
      } else {
        this.estate_id = ''
      }
    },
    htChange (val) {
      this.roomAreaList.forEach(ra => {
        if (val === ra.id) {
          this.cObj.product_type = ra.product_type
          this.cObj.house_type = ra.house_type
          this.cObj.area = ra.area
          this.cObj.house_img = ra.pri_image + '_adm0'
          this.cObj.HT = val
          this.cObj.title = `${ra.key}(${arrToObj(this.$dictData.area_type)[this.cObj.area_type]})`
          
          this.getDef('edit')
          const hType = ra.house_type ? ra.house_type.split('') : []
          this.diyFormObj.hType1 = hType[0]
          this.diyFormObj.hType2= hType[1]
          this.diyFormObj.hType3 = hType[2]
        }
        return
      })
    },
    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
            if (this.diyFormObj.addr1 && this.diyFormObj.addr2 && this.diyFormObj.addr3) {
              newForm.house_no = `${this.diyFormObj.addr1}-${this.diyFormObj.addr2}-${this.diyFormObj.addr3}`
            } else {
              this.$msg('请输入楼栋单号房间号')
              return
            }
            if (this.diyFormObj.hType1 && this.diyFormObj.hType2 && this.diyFormObj.hType3) {
              newForm.house_type = `${this.diyFormObj.hType1}-${this.diyFormObj.hType2}-${this.diyFormObj.hType3}`
            } else {
              this.$msg('请输入户型')
              return
            }
            if (this.diyFormObj.sRate1 && this.diyFormObj.sRate2) {
              newForm.stairs_rate = `${this.diyFormObj.sRate1}-${this.diyFormObj.sRate2}`
            } else {
              this.$msg('请输入梯户比')
              return
            }
            if (this.cObj.floor && this.cObj.storeys) {
              newForm.floor = this.cObj.floor
              newForm.storeys = this.cObj.storeys
            } else {
              this.$msg('请输入楼层')
              return
            }
            
            if (this.cObj.product_type) newForm.product_type = this.cObj.product_type
            if (this.cObj.video) newForm.video = this.cObj.video
            // newForm.longitude = this.cObj.longitude
            // newForm.latitude = this.cObj.latitude
            // if (!newForm.longitude) return this.$msgw('请选择经度!')
            // else if (!newForm.latitude) return this.$msgw('请选择纬度!')
            const imgUrlArr = this.imagesArr.map(urlStr => {
              return urlStr
            })
            newForm.images = imgUrlArr.join(',')
            newForm.pri_image = this.IMdel(newForm.pri_image)
            newForm.custom_tag = newForm.custom_tag.replace(/,|、|\/|\\/g, ',')
            let apiStr = 'admeshouseadd'
            if (this.curObj.id) apiStr = 'admeshouseedit'
            this.$api.house[apiStr](newForm).then(data => {
              this.$msgs(newForm.id ? '编辑成功' : '新增成功')
              this.productData = []
              this.diyFormObj = {
                addr1: '',
                addr2: '',
                addr3: '',
                hType1: '',
                hType2: '',
                hType3: '',
                sRate1: '',
                sRate2: '',
              }
              this.$emit('close', newForm)
            })
          }
        })
      } else {
        this.$emit('close')
        this.productData = []
        this.diyFormObj = {
          addr1: '',
          addr2: '',
          addr3: '',
          hType1: '',
          hType2: '',
          hType3: '',
          sRate1: '',
          sRate2: '',
        }
        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;
  &.scoped-le2 {
    width: 300px;
  }
  ::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-img-area {
  text-align: left;
  padding: 0 40px;
  .sia-op {
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #f2f2f2;
    width: 80px;
    height: 80px;
    position: relative;
    &:hover {
      .img-big {
        display: block;
      }
    }
    .img {
      width: 80px;
      height: 80px;
    }
    .close {
      position: absolute;
      width: 20px;
      height: 20px;
      top: -10px;
      right: -10px;
      background: url(../../../../assets/icon_g_close.png) no-repeat;
      background-size: 20px;
      cursor: pointer;
    }
    .img-big {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 400px;
      height: auto;
      display: none;
      box-shadow: 10px 10px 10px #ccc;
      z-index: 99;
    }
  }
  .sia-img {
    display: inline-block;
    vertical-align: middle;
    width: 80px;
    height: 80px;
    overflow: hidden;
    border: 1px dashed #999;
    margin-bottom: 10px;
    .el-icon-plus {
      color: #999;
      padding: 30px;
    }
  }
}


.scoped-form-diy {
  width: 100%;
  .sfd-item {
    padding-bottom: 16px;
    display: flex;
    .l {
      width: 110px;
      text-align: right;
      padding-right: 12px;
      font-size: 14px;
      color: #606266;
      font-weight: bold;
    }
    .r {
      flex: 1;
    }
    .tip {
      color: #f00;
      .b {
        font-weight: bold;
        display: inline-block;
        font-size: 20px;
      }
    }
    .tip2 {
      display: inline-block;
      width: 300px;
      color: #606266;
    }
    .tip3 {
      display: inline-block;
      margin-left: 10px;
      width: 300px;
    }
    .i {
      border: 0;
      border-bottom: 1px solid #dcdcdc;
      width: 50px;
      text-align: center;
      outline: none;
    }
    .dot {
      display: inline-block;
      width: 50px;
      &.t2 {
        text-align: center;
      }
    }
  }
}


</style>