<template>
  <com-head :options="headList" v-model="search.state.type" showCtrl>
    <el-form label-width="90px" inline="true">
      <el-form-item label="楼栋-单元：">
        <el-input v-model="search.state.buildingUnit" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="房号：">
        <el-input v-model="search.state.roomNumber" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="建筑面积：" >
        <div class="range-number">
          <el-input v-model="search.state.constructionAreaStar" placeholder="请输入"></el-input>
          <span>至</span>
          <el-input v-model="search.state.constructionAreaEnd" placeholder="请输入"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="套内面积：">
        <div class="range-number">
          <el-input v-model="search.state.insideAreaStar" placeholder="请输入"></el-input>
          <span>至</span>
          <el-input v-model="search.state.insideAreaSnd" placeholder="请输入"></el-input>
        </div>
      </el-form-item>

      <el-form-item label="更新时间：">
        <el-date-picker
          v-model="updateTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="维护人：">
        <el-input v-model="search.state.maintenanceman" placeholder="请输入"></el-input>
      </el-form-item>
      
      <el-form-item label="状态：">
        <el-select v-model="search.state.auditStatus" placeholder="全部">
          <el-option v-for="(item) in status" :key="item.value" :label="item.name" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审核人：">
        <el-input v-model="search.state.reviewer" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="创建时间：">
        <el-date-picker
          v-model="createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="审核时间：">
        <el-date-picker
          v-model="reviewTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item class="searh-btns">
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="search.submit">查询</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer">
    <div class="body-head">
      <h3>
        <span>全部房源VR</span> 
      </h3>
      <!-- <div>
        <el-button type="primary" @click="dataList.deleteSelect" v-if="auth.delete"  :disabled="!dataList.state.length">删除</el-button>
      </div> -->
    </div>

    <el-table ref="multipleTable" :data="dataList.state" style="width: 100%" @selection-change="dataList.changeSelectRows">
      <el-table-column type="selection" width="55" @click.stop v-if="auth.deleteProject"></el-table-column>
      
      <el-table-column label="楼栋-单元" v-slot:default="{ row }">
        {{row.buildingUnit}}
      </el-table-column>
      <el-table-column label="房号" v-slot:default="{ row }">
        {{row.roomNumber}}
      </el-table-column>

      <el-table-column label="建筑面积" prop="buildArea"></el-table-column>
      <el-table-column label="套内面积" prop="roomArea"></el-table-column>
      <el-table-column label="状态" v-slot:default="{row}" width="90">
        <div class="status" :class="{interactive:row.auditStatus !== draftStatus || row.reviewer || row.reviewTime}" @click="(row.auditStatus !== draftStatus || row.reviewer || row.reviewTime) && selectRow(row)">
          <span>{{getStatusName(row.auditStatus)}}</span>
          <template v-if="row.auditStatus !== draftStatus || row.reviewer || row.reviewTime">
            <i class="el-icon-document" v-if="row.auditStatus !== noAdoptStatus && row.auditStatus !== noComAdoptStatus"></i>
            <i class="el-icon-warning-outline error" v-else></i>
          </template>
        </div>
        
      </el-table-column>
      <el-table-column label="维护人" prop="maintenanceman"></el-table-column>
      <el-table-column label="更新时间" prop="lastupdateTime"></el-table-column>
      <el-table-column label="审核人" prop="reviewer"></el-table-column>
      <el-table-column label="审核时间" prop="reviewTime"></el-table-column>
      <el-table-column label="操作" width="180" v-slot:default="{row}">
        <span
          class="oper-span" 
          @click="(~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)) && editHouse(row)" 
          :class="{disable: !~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)}" 
          v-if="auth.update"
          >
          编辑VR
        </span>
        <span
          class="oper-span" 
          @click="() => {~[adoptStatus, uplineStatus].indexOf(row.auditStatus) && (queryVR.show = true ,queryVR.data = row)}" 
          :class="{disable: (!~[adoptStatus, uplineStatus].indexOf(row.auditStatus))}" >
          查看
        </span>
        <!-- <span
          class="oper-span" 
          @click="~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.status) && editHouse(row)" 
          :class="{disable: !~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.status)}" 
          v-if="auth.deleteProject">
          删除
        </span>
         -->
        <span
          class="oper-span"
          v-if="user.role !== 'group'"
          :class="{disable: user.role === 'group' || adoptStatus === row.auditStatus || uplineStatus === row.auditStatus}"
          @click.stop="(user.role !== 'group' && row.auditStatus !== adoptStatus && row.auditStatus !== uplineStatus) && examine(row)">
          {{ ~[draftStatus, noAdoptStatus, adoptStatus, noComAdoptStatus].indexOf(row.auditStatus) ? '提审' : '撤回'}}
        </span>

        <span
          class="oper-span" 
          @click="(~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)) && delModel(row)" 
          :class="{disable: !~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)}" 
          v-if="auth.update"
          >
          删除VR
        </span>
        <span class="oper-span" @click.stop="shareRow(row)" v-if="false">预览</span>
        <span class="oper-span" @click.stop="offlineItem(row)" v-if="row.auditStatus === uplineStatus" :class="{disable: !~[adoptStatus, uplineStatus].indexOf(row.auditStatus)}">
          {{row.auditStatus === uplineStatus ? '下线' : '上线' }}
        </span>
      </el-table-column>
    </el-table>

    <com-pagination
      @size-change="pag.sizeChange"
      @current-change="pag.currentChange"
      :current-page="pag.state.currPage"
      :page-size="pag.state.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pag.state.total"/>
  </div>

  <com-query-vr v-model:show="queryVR.show" :data="queryVR.data" v-if="queryVR.show" />
  <com-record v-model:show="recordData.show" :data="recordData.id" v-if="recordData.show" />

  <com-share
    :setLogo="auth.update"
    v-if="shareData.show"
    v-model:show="shareData.show" 
    :items="shareData.data" />


  <com-vrlist v-model:show="selectVR.show" v-if="selectVR.show" @enter="item => updateModel(item)" v-model="selectVR.value" />


</template>

<script>
import axios from 'axios'
import {ref, watch} from 'vue'
import getTableState from '@/state/tableRef'
import comHead from "@/components/head";
import comShare from "../share";
import comRecord from "./record";
import comVrlist from "./vrlist";
import comQueryVr from "./queryvr";

import qrcode from 'qrcode'
import auth from "@/state/viewAuth";
import comPagination from "@/components/pagination";
import router from '@/router'
import { dateFormat, strToParams } from '@/util'
import user from '@/state/user'
import {
  EXAMINE_SHOW_SELECT_STATUS_2 as EXAMINE_SHOW_SELECT_STATUS,
  EXAMINE_SHOW_SELECT_STATUS_3 as EXAMINE_SHOW_SELECT_STATUS_TEXT,
  EXAMINE_DRAFT_STATUS,
  UN_REQ_NUM,
  EXAMINE_NO_ADOPT_STATUS,
  EXAMINE_NO_AUDIT_STATUS,
  EXAMINE_NO_COM_ADOPT_STATUS,
  EXAMINE_ADOPT_STATUS,
  EXAMINE_UP_ONLINE_STATUS,
  EXAMINE_NO_COM_AUDIT_STATUS,
  getName,
  
  getRedirectRoomAuditBody
} from '@/constant'
import { 
  getCommunityByHouseId,
  getSecondHouseList,
  deleteSecondHouse,
  auditSecondHouse,
  dismissSecondHouse,
  secondHouseOnline
} from '@/request/config'

const getTimeMapSearch = (searchKey, search) => {
  const time = ref(null)
  const start = `${searchKey}Start`
  const end = `${searchKey}End`

  watch(time, () => {
    if (time.value) {
      search.value.state[start] = dateFormat(new Date(time.value[0]), 'yyyy-MM-dd hh:mm:ss').toString()
      search.value.state[end] = dateFormat(new Date(time.value[1]), 'yyyy-MM-dd 23:59:59').toString()
    } else {
      search.value.state[start] = search.value.state[end] = ''
    }
  })

  watch(
    () => search.value.state[start], 
    () => {
      if (!search.value.state[start]) {
        time.value = null
      }
    }
  )
  watch(
    () => search.value.state[end], 
    () => {
      if (!search.value.state[end]) {
        time.value = null
      }
    }
  )

  return time
}

export default {
  name: 'housing',
  setup() {
    const headList = ref([{ name: "二手房", value: 1 }])
    const state = getTableState({
      getUrl: getSecondHouseList,
      delUrl: deleteSecondHouse,
      pagAttr: {listMap: {roomid: 'id'}},
      searchAttr: {
        gardenId: router.currentRoute.value.params.id,
        cityId: router.currentRoute.value.params.cityId,
        buildingUnit: "",
        roomNumber: '',
        maintenanceman: '',
        auditStatus: UN_REQ_NUM,
        reviewer: '',
        updateTimeStart: '',
        updateTimeEnd: '',
        createTimeStart: '',
        createTimeEnd: '',
        reviewTimeStart: '',
        reviewTimeEnd: '',
        insideAreaSnd: '',
        insideAreaStar: '',
        constructionAreaStar: '',
        constructionAreaEnd: '',
      }
    })

    state.dataList.value._delete = async (data) => {
      await axios.post(deleteSecondHouse, {}, {params: {roomid: data.roomid} })
    }

    const names = ref([])
    const initNames = ref([])
    
    return { 
      ...state, 
      headList, 
      auth, 
      user, 
      initNames, 
      names,
      updateTime: getTimeMapSearch('updateTime', state.search),
      auditTime: getTimeMapSearch('auditTime', state.search),
      createTime: getTimeMapSearch('createTime', state.search),
      reviewTime: getTimeMapSearch('reviewTime', state.search)
    };
  },
  data() {
    return {
      gardenName: '',
      status: EXAMINE_SHOW_SELECT_STATUS,
      uplineStatus: EXAMINE_UP_ONLINE_STATUS,
      draftStatus: EXAMINE_DRAFT_STATUS,
      noAdoptStatus: EXAMINE_NO_ADOPT_STATUS,
      noComAdoptStatus: EXAMINE_NO_COM_ADOPT_STATUS,
      noAuditStatus: EXAMINE_NO_AUDIT_STATUS,
      adoptStatus: EXAMINE_ADOPT_STATUS,
      recordData: { show: false, id: 0 },
      selectVR: { show: false, data: null, value: null },
      queryVR: { show: false, data: null },
      shareData: { show: false, data: 0 }
    }
  },
  methods: {
    clickEstateItem(ev, item) {
      if (item.disable) {
        ev.stopPropagation()
      }
    },
    getStatusName: getName(EXAMINE_SHOW_SELECT_STATUS_TEXT),
    selectRow(data) {
      this.recordData.show = true
      this.recordData.id = data.vrId
    },
    async shareRow(raw, type = 1) {
      if (!raw.vRUrl) {
        return this.$confirm('暂无有效链接', '提示')
      }

      const vrLink = process.env.VUE_APP_DOMAIN + raw.vRUrl
      const QrCode = await qrcode.toDataURL(vrLink)

      let shareItems = [{
        QrCode: QrCode,
        type: 'building',
        noRandow: true,
        houseTitle: raw.buildingUnit + raw.roomNumber,
        epcVrLink: vrLink.replace('hengda.html', 'epc.html'),
        vrLink: vrLink,
        innerVrLink: process.env.VUE_APP_INTRANET_DOMAIN + raw.vRUrl,
        status: raw.auditStatus,
      }]

      if (type === 1) {
        this.shareData.show = true
        this.shareData.data = shareItems
      } else {
        window.open(type === 1 ? shareItems[0].vrLink : shareItems[0].epcVrLink)
      }
    },
    openHouse(data) {
      return this.shareRow(data)
      // if (data.status === this.adoptStatus) {
      //   window.open(data.vrLink)
      // } else {
      //   window.open(data.innerVrLink)
      // }
    },
    async offlineItem(data) {
      data.cityId = this.$route.params.cityId
      data.gardenName = this.gardenName
      if (data.auditStatus !== EXAMINE_ADOPT_STATUS && data.auditStatus !== EXAMINE_UP_ONLINE_STATUS) return;

      if (data.auditStatus === EXAMINE_UP_ONLINE_STATUS) {
        if (!(await this.$msgbox({
          message: '下线后VR链接将无法继续访问，确定要下线吗？', 
          title: '下线',
          showCancelButton: true,
          confirmButtonText: '下线',
          cancelButtonText: '取消',
        }))) {
          return;
        }
      }

      const status = data.auditStatus === EXAMINE_UP_ONLINE_STATUS ? EXAMINE_DRAFT_STATUS : EXAMINE_UP_ONLINE_STATUS

      await axios.post(
        secondHouseOnline,
        getRedirectRoomAuditBody(data, status)
      )
      this.$alert((status === EXAMINE_UP_ONLINE_STATUS ? '上' : '下') + '线成功', '提示')
      this.dataList.refer()
    },

    async examine(data) {
      data.cityId = this.$route.params.cityId
      data.gardenName = this.gardenName

      console.log(data)
      if (~[this.draftStatus, this.noAdoptStatus, this.adoptStatus, this.noComAdoptStatus].indexOf(data.auditStatus)) {
        await this.shareRow(data)
        if (!this.shareData.show) {
          return;
        }
        this.shareData.show = false

        // await axios.post(auditSecondHouse, getRedirectRoomAuditBody(data, EXAMINE_NO_COM_AUDIT_STATUS))
        const status = user.value.role === 'group' || user.value.role === 'admin' || user.value.role === 'region' 
          ? EXAMINE_NO_AUDIT_STATUS
          : EXAMINE_NO_COM_AUDIT_STATUS
        
        await axios.post(auditSecondHouse, getRedirectRoomAuditBody(data, status))
        
        // data.auditId = res.data.auditId
        this.$alert('提审成功', '提示')
      } else {
        await axios.post(dismissSecondHouse, getRedirectRoomAuditBody(data, EXAMINE_DRAFT_STATUS))
        this.$alert('撤销成功', '提示')
      }

      this.dataList.refer()
    },
    resetSearch() {
      let type = this.search.state.type
      this.search.reset()
      this.search.state.type = type
    },
    async updateModel(raw) {
      const upload = {
        vrModelName: raw.sceneName,
        num: raw.num,
        vrCover: raw.thumb,
        vRUrl: `/hengda.html?m=${raw.num}&prodId=${this.search.state.gardenId}&houseId=${this.selectVR.data.roomlistingId}&businessType=2`
      }

      await axios.post(dismissSecondHouse, getRedirectRoomAuditBody({
        ...this.selectVR.data,
        ...upload
      }, EXAMINE_DRAFT_STATUS, '', this.selectVR.data.roomlistingId))

      this.selectVR.show = false
      this.dataList.refer()
    },
    async delModel(row) {
      if (!row.vRUrl) {
        return this.$alert('暂无有效链接', '提示')
      }
      await axios.post(dismissSecondHouse, getRedirectRoomAuditBody({
        ...row,
        vrCover: '',
        vRUrl: '',
      }, EXAMINE_DRAFT_STATUS, '', this.selectVR.data.roomlistingId))

      this.selectVR.show = false
      this.dataList.refer()
    },
    editHouse(item, isView = 0) {
      if (isView) {
        const params = strToParams(item.vRUrl.substr(item.vRUrl.indexOf('?')))
        
        const link = '/epc.html?m=' + params.m + '&token=' + user.value.token
        return window.open(link)
      } else {
        if (item.vRUrl) {
          const params = strToParams(item.vRUrl.substr(item.vRUrl.indexOf('?')))
          this.selectVR.value = params.m
        } else {
          this.selectVR.value = null
        }
        
        this.selectVR.show = true
        this.selectVR.data = item
      }
      // let link = process.env.VUE_APP_PREFIX + '/sh_house/edit.html?m=' + item.id + '&h=' + item.gardenId + '&canView=' + isView
      // window.open(link)
    }
  },
  watch: {
    '$route': {
      immediate: true,
      async handler(newVal, oldVal) {
        if (newVal.name !== "secondHouse" || (this.search.state.gardenId === newVal.params.id && oldVal)) return;
        try {
          this.search.state.gardenId = newVal.params.id
          let res = await axios.get(getCommunityByHouseId, { params: { gardenId: newVal.params.id } })
          this.gardenName = res.data.gardenName
          document.querySelector('.player').querySelector('.active span').textContent = this.gardenName
          this.gardenId = res.data.gardenId
        } catch (e) {
          this.$router.back()
        }
      } 
    }
  },
  components: {
    comVrlist,
    comQueryVr,
    "com-head": comHead,
    "com-record": comRecord,
    "com-share": comShare,
    "com-pagination": comPagination
  },
};
</script>

<style lang="less">

.my-autocomplete {
  li {
    line-height: normal;
    padding: 0 !important;
    .item-layout {
      padding: 7px !important;
      display: flex;
      justify-content: space-between;
      span {
        flex: none;
      }

    }
    .item-layout.disable {
      cursor: not-allowed;

      *{
        color: #c0c4cc;
      }
    }
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 16px;
    }
    .addr {
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 16px;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}


.info-from .el-form-item__content{
  width: calc(100% - 100px);
}
.info-from .el-form-item__content .inline-input {
  width: 100%;
}
</style>

<style lang="scss" scoped>

.add-input {
  width: 250px;
  margin: 40px auto;
  padding-left: 80px;
  position: relative;

  label {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);

    span {
      color: var(--primaryColor);
    }
  }
}

.cover-img {
  width: 32px;
  height: 32px;
}

.status {
  &.interactive {
    cursor: pointer;
  }

  i {
    vertical-align: text-bottom;
    margin-left: 5px;
    font-size: 1.2rem;
    color: rgb(144,144,150);
    
    &.error {
      color: var(--primaryColor);
    }
  }
}

</style>

