<template>
  <div>
    <el-drawer
      :show-close="false"
      :title="type === 'edit' ? '编辑一房一价' : '新增一房一价'"
      :wrapper-closable="false"
      :close-on-press-escape="false"
      :visible.sync="isShow"
      size="1100px"
      custom-class="xl-drawer"
      direction="rtl"
    >
      <div v-if="this.type === 'add'" class="scoped-top">
        <base-form slot="content" ref="ruleForm" :data="searchData" :noLabel="false" labelWidth="100px">
          <div slot="footer">
            <el-button icon="el-icon-Plus" class="xl-form-btn bgc2" @click="batchAdd">批量添加</el-button>
          </div>
        </base-form>
      </div>
      <table-list
        :listLoading="false"
        listLoadStr="createdClose"
        :data="tableData2"
        :columns="listConfig"
        :current-page="currentPage"
        :page-size="pageSize"
        :total-records="totalRecords"
        @currentChange="pageHandle"
        :operationsDefaultLength="4"
      />
      <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 v-if="this.type === 'add'" class="xl-form-btn t1" @click="close('confirm')">保存</el-button>
        </div>
      </div>
    </el-drawer>
    <rpt-edit
      :isShow="isREShow"
      :curObj="reObj"
      :roomAreaList="roomAreaList"
      @close="closeREPopup"
     />
  </div>
</template>
<script>
import { arrToObj } from '@/utils'
import baseTable from '_m/baseTable.js'
import RptEdit from './RoomPriceTypeEdit.vue'
export default {
  components: {
    RptEdit
  },
  mixins: [...mixins, baseTable],
  props: {
    isShow: Boolean,
    curObj: Object,
    type: String,
  },
  inject: ['parentData'],
  data() {
    return {
      apiStr: 'house.admestatelotterypricelist',
      searchForm: {},
      noCreated: true,
      isLEShow: false,
      cObj: {},
      searchData: [],
      roomAreaList: [],
      isREShow: false,
      reObj: {},
    }
  },
  computed: {
    tableData2() {
      const arr = [...this.tableData]
      arr.map(item => {
        if (item.house_img) item.houseImg = item.house_img + '_adm0'
        if (this.type === 'add') item.noCan = true
      })
      return arr
    }
  },
  mounted() {
    this.getDef()
    this.listConfig = {
      rows: [
        { label: '楼栋', prop: 'building_num', type: 'input', width: '100px'},
        { label: '层高', prop: 'floor_height', type: 'input', width: '60px'},
        { label: '楼层', prop: 'storey', type: 'input', width: '60px'},
        { label: '房号', prop: 'room', type: 'input', width: '60px'},
        { label: '建筑面积(㎡)', prop: 'built', type: 'input', width: '80px'},
        { label: '套内面积(㎡)', prop: 'space', type: 'input', width: '80px'},
        { label: '毛坯单价(元/㎡)', prop: 'blank', type: 'input', width: '90px'},
        { label: '装修单价(元/㎡)', prop: 'decoration', type: 'input', width: '90px'},
        { label: '户型名', prop: 'house_type', width: '100px'},
        { label: '户型图', prop: 'houseImg', type: 'img'},
        { label: '操作', width: 200, type: 'handle2', operations:
          [
            { label: '保存', func: this.saveHandle, btnType: 'primary', hide: 'noCan' },
            { label: '修改户型', func: this.openREPopup, btnType: 'success', hide: 'noCan' },
            { label: '删除', func: this.delHandle, btnType: 'danger' },
          ]
        }
      ]
    }
  },
  watch: {
    isShow: function(val) {
      if (val) {
        if (this.type === 'edit') {
          this.searchForm = {
            estate_id: this.curObj.estate_id,
            lottery_id: this.curObj.id,
          }
          this.fetchData()
        } else {
          this.totalRecords = 1
          this.currentPage = 1
          this.tableData = []
        }
        this.getDef()
        this.$api.house.admestatehousearealist({estate_id: this.curObj.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 = `${htObj[item.house_type]}${item.area}㎡-${ptObj[item.product_type]}`
            item.key2 = `${htObj[item.house_type]}`
            item.val = item.id
          })
          this.roomAreaList = [...list]
        })
      }
    },
  },
  methods: {
    openREPopup(row) {
      // console.log(row)
      this.reObj = row
      this.isREShow = true
    },
    closeREPopup(obj) {
      this.isREShow = false
      if (obj) {
        this.fetchData()
      }
    },
    getData () {
      this.$api.house.admestatelotterypricelist({
        estate_id: this.curObj.estate_id,
        lottery_id: this.curObj.id,
      }).then(res => {
        let list = res.list || []
        list.map(item => {
          item.houseImg = item.house_img + '_adm0'
        })
        this.tableData = [...list]
      })
    },
    saveHandle (row) {
      this.$api.house.admestatelotterypriceedit(row).then(res => {
        this.fetchData()
        this.$msgs('更新成功~')
      })
    },
    getDef (str) {
      if (str === 'col') {
        let params = {...this.$refs.ruleForm.baseForm}
        let addArr = []
        const colArr = new Array(Number(params.batchCol)).fill({i: "add"})
        colArr.forEach((item, itemIndex) => {
          addArr.push({ label: `${itemIndex + 1}-建筑面积(㎡)`, key: `${itemIndex + 1}-built` })
          addArr.push({ label: `${itemIndex + 1}-套内面积(㎡)`, key: `${itemIndex + 1}-space` })
          addArr.push({ label: `${itemIndex + 1}-户型`, key: `${itemIndex + 1}-HT`, type: 'select', options: this.roomAreaList})
        })
        this.searchData = [
          { label: '每层户数', key: 'batchCol', changeHandle: this.colChange },
          { label: '多少层', key: 'batchRow' },
          { label: '楼栋名', key: 'building_num' },
          { label: '层高', key: 'floor_height' },
          { label: '装修单价', key: 'decoration' },
          ...addArr,
        ]
        this.setDefaultValue(params, 'searchData')
      } else {
        this.searchData = [
          { label: '每层户数', key: 'batchCol', changeHandle: this.colChange },
          { label: '多少层', key: 'batchRow' },
          { label: '楼栋名', key: 'building_num' },
          { label: '层高', key: 'floor_height' },
          { label: '装修单价', key: 'decoration' },
        ]
      }
    },
    colChange (val) {
      this.getDef('col')
    },
    batchAdd () {
      const oldform = this.$refs.ruleForm.baseForm
      const newForm = { ...oldform }
      let curArr = [...this.tableData]
      let newArr = new Array(Number(newForm.batchRow) * Number(newForm.batchCol)).fill({
        ...newForm
      })
      newArr.forEach((n, i) => {
        let rowIndex = Math.floor(i / newForm.batchCol) + 1
        let colIndex = Math.floor(i % newForm.batchCol) + 1
        let built = ''
        let space = ''
        let house_type = ''
        let house_img = ''
        let houseImg = ''
        for (let f in newForm) {
          if (f.indexOf(colIndex + '-built') > -1) {
            built = newForm[f]
          }
          if (f.indexOf(colIndex + '-HT') > -1) {
            this.roomAreaList.forEach(ra => {
              if (newForm[f] === ra.id) {
                house_type = ra.key2
                houseImg = ra.pri_image + '_adm0'
                house_img = ra.pri_image
              }
            })
          }
          if (f.indexOf(colIndex + '-space') > -1) {
            space = newForm[f]
          }
        }
        curArr.push({
          ...n,
          storey: rowIndex,
          room: `${rowIndex}0${colIndex}`,
          built,
          space,
          house_type,
          house_img,
          houseImg,
          blank: 1,
        })
      })
      this.tableData = [...curArr]
      this.setDefaultValue({}, 'searchData')
    },
    delHandle(row) {
      this.$msg(`您确定要删除该楼盘吗？`, 'confirm', () => {
        if (this.type === 'add') {
          let arr = [...this.tableData]
          let cIndex = ''
          arr.map((item, index) => {
            if (item.randomId === row.randomId) {
              cIndex = index
            }
          })
          arr.splice(cIndex, 1)
          this.tableData = [...arr]
        } else {
          this.$api.house.admestatelotterypricedel({id: row.id}).then(res => {
            this.$msgs('删除成功~')
            this.getData()
          })
        }
      }, null, true)
    },
    close(str) {
      if (str === 'confirm') {
        let curArr = [...this.tableData]
        let newArr = []
        curArr.map(item => {
          newArr.push({
            blank: item.blank,
            building_num: item.building_num,
            built: item.built,
            decoration: item.decoration,
            floor_height: item.floor_height,
            house_type: item.house_type,
            room: item.room,
            space: item.space,
            storey: item.storey,
            house_img: item.house_img,
          })
        })
        let params = {
          estate_id: this.curObj.estate_id,
          lottery_id: this.curObj.id,
          data: JSON.stringify(newArr)
        }
        let apiStr = 'admestatelotterypriceadd'
        this.$api.house[apiStr](params).then(data => {
          this.$msgs(params.lottery_id ? '编辑成功' : '新增成功')
          this.tableData = []
          this.$emit('close', newForm)
        })
      } else {
        this.$emit('close')
        this.tableData = []
        this.setDefaultValue()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .xl-table-box {
  padding-bottom: 50px;
}
::v-deep .el-form-item {
  &:nth-child(5) {
    margin-right: 300px;
  }
}
</style>
