<template>
  <com-head :options="headList" v-model="search.state.type" showCtrl>
    <el-form label-width="90px" inline="true">
      <el-form-item label="楼盘id：">
        <el-input v-model="search.state.fcbEstateId" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="楼盘名称：">
        <el-input v-model="search.state.estateName" 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="updateTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核时间：">
        <el-date-picker
          v-model="auditTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="mpStatus" 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 class="searh-btns">
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="search.submit">查询</el-button>
        <el-button type="primary" @click="exportExe" :disabled="!pag.state.total" v-if="auth.export">导出</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer">
    <div class="body-head">
      <h3>
        <span>全部楼盘</span> 
      </h3>
      <div>
        <template v-if="search.state.type === 1">
          <el-button type="primary" @click="oper.readyInsert" v-if="auth.addProject">创建</el-button>
        </template>
        <template v-else>
          <el-button type="primary">楼盘全景设置</el-button>
          <el-button type="primary" @click="oper.readyInsert">添加二手房</el-button>
        </template>
        <el-button type="primary" @click="dataList.deleteSelect" v-if="auth.deleteProject"  :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 }">
        <img :src="row.coverImagUrl" class="cover-img">
      </el-table-column> -->
      <el-table-column label="楼盘id" v-slot:default="{ row }">
        {{row.fcbEstateId}}
      </el-table-column>
      <el-table-column label="楼盘名称" v-slot:default="{ row }">
        
        <a class="oper-link" v-if="row.houseId && ~[adoptStatus].indexOf(row.status)" @click="editHouse(row, 1)">{{row.estateName}}</a>
        <span v-else>{{row.estateName}}</span>
      </el-table-column>
      <!-- <el-table-column label="VR项目" v-slot:default="{ row }">
        <a class="oper-link" @click="openHouse(row)">{{row.houseTitle}}</a>
      </el-table-column> -->
      <el-table-column label="航拍数量" prop="building" v-slot:default="{ row }">
        {{row.building || 0}}
      </el-table-column>
      <el-table-column label="景观图数量" prop="garden" v-slot:default="{ row }">
        {{row.garden || 0}}
      </el-table-column>
      <el-table-column label="售楼处数量" prop="sales" v-slot:default="{ row }">
        {{row.sales || 0}}
      </el-table-column>
      <el-table-column label="样板间数量" prop="house" v-slot:default="{ row }">
        {{row.house || 0}}
      </el-table-column>
      <el-table-column label="讲房售楼处数量" prop="points" v-slot:default="{ row }">
        {{row.saleVideos || 0}}
      </el-table-column>
      <el-table-column label="讲房样板间数量" prop="points" v-slot:default="{ row }">
        {{row.houseVideos || 0}}
      </el-table-column>
      <el-table-column label="讲房点位数量" prop="points" v-slot:default="{ row }">
        {{row.points || 0}}
      </el-table-column>
      <el-table-column label="创建人" prop="createByName"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column label="状态" v-slot:default="{row}" width="90">
        <div class="status" :class="{interactive: row.countNum > 0}" @click="row.countNum > 0 && selectRow(row)">
          <span>{{row.status === adoptStatus ? Number(row.online) ? '已上线': '已审核' : getStatusName(row.status)}}</span>
          <template v-if="row.countNum > 0">
            <i class="el-icon-document" v-if="row.status !== noAdoptStatus && row.status !== noComAdoptStatus"></i>
            <i class="el-icon-warning-outline error" v-else></i>
          </template>
        </div>
        
      </el-table-column>
      <el-table-column label="审核人" prop="auditorName"></el-table-column>
      <el-table-column label="审核时间" prop="auditTime"></el-table-column>
      <el-table-column label="操作" width="180" v-slot:default="{row}">
        <span
          class="oper-span" 
          @click="(row.houseId && ~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.status)) && editHouse(row)" 
          :class="{disable: !row.houseId || !~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.status)}" 
          v-if="auth.updateProject"
          >
          编辑
        </span>
        <span
          class="oper-span" 
          @click="row.houseId && ~[adoptStatus].indexOf(row.status) && editHouse(row, 1)" 
          :class="{disable: !row.houseId || (!~[adoptStatus].indexOf(row.status))}" >
          查看
        </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
          v-if="(auth.online && Number(row.online) !== 1) || (auth.offline && Number(row.online) === 1)"
          class="oper-span"
          :class="{disable: row.status !== adoptStatus}"
          @click="row.status === adoptStatus && offlineItem(row)">
          {{Number(row.online) === 1 ? '下线' : '上线' }}
        </span>
        <span
          class="oper-span"
          v-if="user.role !== 'group'"
          :class="{disable: !row.houseId || user.role === 'group' || adoptStatus === row.status}"
          @click.stop="(row.houseId && user.role !== 'group' && row.status !== adoptStatus) && examine(row)">
          {{ ~[draftStatus, noAdoptStatus, adoptStatus, noComAdoptStatus].indexOf(row.status) ? '提审' : '撤回'}}
        </span>

        <span class="oper-span" @click.stop="row.houseId && shareRow(row)" :class="{disable: !row.houseId}">预览</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-record v-model:show="recordData.show" :data="recordData.id" v-if="recordData.show" />

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

  <com-up-select 
    v-if="upData.show"
    :items="upData.data"
    v-model:show="upData.show" 
    v-model="upData.value"
    @online="offlineItem(upData.row, true)"
  />

  <com-dialog :title="operTitle" v-model:show="oper.state.show" @submit="oper.insert" @quit="oper.quit">
    <div class="add-input" v-if="search.state.type === 1">
      <label for="add-name"><span>*</span>楼盘名称：</label>
      <el-input v-model="oper.state.name" name="add-name"></el-input>
    </div>
    <select-vr v-model="oper.state.vrs" v-else />
  </com-dialog>


  
  <com-dialog
    :title="operTitle" v-model:show="oper.state.show" @submit="insertItem" @quit="oper.quit"
  >
    <el-form ref="form" :model="form" label-width="100px" class="info-from">
      <el-form-item label="楼盘名称：" class="mandatory" style="margin-top:60px">
        <el-autocomplete
          popper-class="my-autocomplete"
          class="inline-input"
          v-model="oper.state.estateName"
          :fetch-suggestions="searchName"
          @focus="oper.state.fcbEstateId = ''"
          placeholder="楼盘名称："
          @select="handleSelect"
        >
          <template v-slot="{ item }">
            <div class="item-layout" :class="{disable: item.disable}" @click="$event => clickEstateItem($event, item)">
              <div class="name">{{ item.prodName }}</div>
              <span class="addr">{{ item.prodId }}</span>
            </div>
          </template>
        </el-autocomplete>
<!-- 
        <el-select
          v-model="oper.state.fcbEstateId"
          filterable
          placeholder="楼盘名称："
          class="estate-search"
          :filter-method="searchName"
          @focus="focuHandle">
          <el-option v-for="item in names" :key="item.prodId" :label="item.prodName" :value="item.prodId" />
        </el-select> -->
      </el-form-item>
      
      <!-- <el-form-item label="所属公司：" class="mandatory">
        <com-company v-model="oper.state.belongCompanyId" v-model:label="oper.state.belongCompanyName" hideAll />
      </el-form-item> -->
    </el-form>

  </com-dialog>

</template>

<script>
import axios from 'axios'
import {computed, ref, watch, watchEffect} from 'vue'
import getTableState, {getParams} from '@/state/tableRef'
import comHead from "@/components/head";
import comDialog from "@/components/dialog";
import comShare from "./share";
import comUpSelect from "./up-select";
import comRecord from "@/components/record";
import auth from "@/state/viewAuth";
import comPagination from "@/components/pagination";
import router from '@/router'
import { dateFormat } from '@/util'
import selectVR from "./select-VR";
import user from '@/state/user'
import {
  EXAMINE_SHOW_SELECT_STATUS,
  EXAMINE_DRAFT_STATUS,
  HOUSE_TYPE,
  UN_REQ_NUM,
  EXAMINE_NO_ADOPT_STATUS,
  EXAMINE_NO_AUDIT_STATUS,
  EXAMINE_NO_ADOPT_ALL_STATUS,
  EXAMINE_NO_COM_ADOPT_STATUS,
  EXAMINE_ADOPT_STATUS,
  EXANINE_SUCCESS_STATUS,
  getName,
} from '@/constant'
import { 
  estateOnline,
  hasHouseIsDel,
  getEstateByHouseId,
  getHouseList,
  updateHouse,
  exportHouseList,
  deleteHouse,
  getHouseIdAll,
  auditHouse,
  dismissHouse,
  insertHouse,
  uploadHouseLogo,
  getHouseShares,
  getHouseUpShares,
  getHdEstateNames
} from '@/request/config'

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

  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 mpStatus = ref(UN_REQ_NUM)
    const headList = ref(HOUSE_TYPE)
    const state = getTableState({
      getUrl: getHouseList,
      updateUrl: updateHouse,
      insertUrl: insertHouse,
      delUrl: deleteHouse,
      pagAttr: {listMap: {houseId: 'id'}},
      operAttr: { name: '', vrs: [2, 3], fcbEstateId: "", estateName: '' },
      searchAttr: {
        fcbEstateId: null,
        estateName: null,
        createStartTime: null,
        createEndTime: null,
        updateStartTime: null,
        statuslist: '',
        status: mpStatus.value, 
        updateEndTime: null,
        auditTimeStartTime: null,
        auditTimeEndTime: null,
        type: headList.value[0].value,
        estateId: router.currentRoute.value.params.id
      }
    })



    watchEffect(() => {
      if (mpStatus.value === EXANINE_SUCCESS_STATUS) {
        state.search.value.state.statuslist = EXAMINE_ADOPT_STATUS + ''
        state.search.value.state.online = 0
      } else if (mpStatus.value === EXAMINE_ADOPT_STATUS) {
        state.search.value.state.online = 1
        state.search.value.state.statuslist = mpStatus.value + ''
      } else if (mpStatus.value === EXAMINE_NO_ADOPT_ALL_STATUS) {
        state.search.value.state.online = ''
        state.search.value.state.statuslist = [EXAMINE_NO_COM_ADOPT_STATUS, EXAMINE_NO_ADOPT_STATUS].join(',')
      } else if (mpStatus.value === UN_REQ_NUM){
        state.search.value.state.statuslist = ''
      } else {
        state.search.value.state.online = ''
        state.search.value.state.statuslist = mpStatus.value  + ''
      }

    })

    const operTitle = computed(
      () => state.search.value.state.type === 1 ?
        (
          (state.oper.value.state.id ? '修改' : '新增') + '新房'
        ) :'选择二手房VR模型'
    )

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

    const names = ref([])
    const initNames = ref([])
    const searchName = async (keyword = '', cb) => {
      if (keyword === '') return cb && cb([])
      let {data: existsIds} = await axios.get(getHouseIdAll)

      cb && cb(names.value.map(item => ({...item, value: item.prodName})));

      let res = await axios.post(getHdEstateNames, {prodName: keyword, size: 100})
      names.value = res.data.records
      if (!keyword) {
        initNames.value = names.value
      }
      cb && cb(names.value.map(item => ({...item, value: item.prodName, disable: !!~existsIds.indexOf(item.prodId)})))
    }


    
    return { 
      ...state, 
      headList, 
      operTitle, 
      auth, 
      mpStatus,
      user, 
      searchName, 
      initNames, 
      names,
      createTime: getTimeMapSearch('create', state.search),
      updateTime: getTimeMapSearch('update', state.search),
      auditTime: getTimeMapSearch('auditTime', state.search)
    };
  },
  data() {
    return {
      estateName: '',
      status: EXAMINE_SHOW_SELECT_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 },
      shareData: { show: false, data: 0, list: [] },
      upData: {show: false, data: 0, value: {init: null, vrList: []}, row: null}
    }
  },
  methods: {
    async offlineItem(data, isSelect = false) {
      if (data.auditStatus === 0) return;
      let online = Number(!data.online)


      if (!online) {
        console.log('--------', data)
        let res = await axios.post(hasHouseIsDel, {prodId: data.fcbHouseId})
        if (!res.data) {
          return this.$alert('下线失败', '提示')
        }
        

        if (!(await this.$msgbox({
          message: '下线后VR链接将无法继续访问，确定要下线吗？', 
          title: '下线',
          showCancelButton: true,
          confirmButtonText: '下线',
          cancelButtonText: '取消',
        }))) {
          return;
        }
      } else if (!isSelect){
        let res = await axios.get(getHouseUpShares, { params: {houseId: data.id} })
        this.upData.show = true
        this.upData.data = res.data
        this.upData.row = data

        return;
      }
      
      let requestOnlineList = []
      if (online) {
        requestOnlineList.push(
          this.upData.data.find(({id}) => id === this.upData.value.init)
        )
        requestOnlineList.push(
          ...this.upData.value.vrList.map(id => this.upData.data.find(({id: qid}) => qid === id))
        )
        
        requestOnlineList = requestOnlineList.map(item => ({
          ...item,
          isDomeVideo: Number(!!data.points)
        }))
      }

      await axios.post(estateOnline, { houseId: data.id, online: online, requestOnlineList }, {params: {}})
      data.online = online


      this.$alert((online ? '上' : '下') + '线成功', '提示')
      this.dataList.refer()
      this.upData.show = false
      this.upData.data = null
      this.upData.row = null

    },
    async exportExe() {
      let params = {
        ...getParams(this.search.state),
        pageNum: this.pag.state.currPage,
        pageSize: this.pag.state.size
      }
      if (!params.createStartTime || !params.createEndTime) {
        return this.$alert('请先选择创建时间段', '提示')
      } else {
        const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
        if (monthDiff(this.createTime[0], this.createTime[1]) > 2) {
          return this.$alert('最多支持导出连续三个月的数据', '提示')
        }
      }
      
      let res = await axios.get(exportHouseList, { params })
      location.href = res.data
    },
    clickEstateItem(ev, item) {
      if (item.disable) {
        ev.stopPropagation()
      }
    },
    getStatusName: getName(EXAMINE_SHOW_SELECT_STATUS),
    async insertItem() {
      if (!this.oper.state.estateName) {
          return this.$alert('楼盘名称不能为空！', '提示')
      }

      if (!this.oper.state.fcbEstateId.trim()) {
        let estate = this.names.find(({prodName}) => prodName === this.oper.state.estateName)
        if (!estate) {
          return this.$alert('无法匹配当前名称的楼盘！', '提示')
        } else {
          this.oper.state.fcbEstateId = estate.prodId
        }
      }
      
      if (this.oper.state.id) {
        this.oper.update();
      } else {
        this.oper.insert();
      }
    },
    async changeLogo(file) {
      let res = await axios.post(uploadHouseLogo, {
        houseId: this.shareData.data.id, 
        file
      })

      this.shareData.data = {...this.shareData.data, ...res.data}
    },
    selectRow(data) {
      this.recordData.show = true
      this.recordData.id = data.id
    },
    async shareRow(data, type = 1) {
      let res = await axios.get(getHouseShares, { params: {houseId: data.id} })


      let shareItems = []

      if (res.data) {
        shareItems = res.data.map(item => ({
          QrCode: item.icon,
          type: item.type,
          houseTitle: item.sceneTitle || data.houseTitle,
          epcVrLink: process.env.VUE_APP_DOMAIN + item.webSite.replace('hengda.html', 'epc.html'),
          vrLink: process.env.VUE_APP_DOMAIN + item.webSite,
          innerVrLink: process.env.VUE_APP_INTRANET_DOMAIN + item.webSite,
          online: data.online,
          status: data.status,
        }))

      }

      if (shareItems.length) {
        if (type === 1) {
          this.shareData.show = true
          this.shareData.data = shareItems
        } else {
          window.open(type === 1 ? shareItems[0].vrLink : shareItems[0].epcVrLink)
        }
      } else {
        await this.$confirm('暂无预览链接，请先设置初始场景。', '提示')
      }
    },
    openHouse(data) {
      return this.shareRow(data)
      // if (data.status === this.adoptStatus) {
      //   window.open(data.vrLink)
      // } else {
      //   window.open(data.innerVrLink)
      // }
    },
    async examine(data) {
      if (~[this.draftStatus, this.noAdoptStatus, this.adoptStatus, this.noComAdoptStatus].indexOf(data.status)) {
        await this.shareRow(data)
        if (!this.shareData.show) {
          return;
        }
        this.shareData.show = false
        
        let res = await axios.post(auditHouse, { houseId: data.id, auditHouseType: 1 })
        data.auditId = res.data.auditId
        this.$alert('提审成功', '提示')
      } else {
        await axios.post(dismissHouse, { houseId: data.id, auditHouseType: 1 })
        data.auditId = null
        this.$alert('撤销成功', '提示')
      }

      this.dataList.refer()
    },
    resetSearch() {
      let type = this.search.state.type
      this.search.reset()
      this.search.state.type = type
    },
    async insertHouse() {
      let res = await axios.post(insertHouse, {}, {params: {estateId: this.$route.params.id}})
      this.editHouse({id: res.data.houseId})
    },
    editHouse(item, isView = 0) {
      let link = process.env.VUE_APP_PREFIX + '/vrscene/edit.html?m=' + item.id + '&h=' + item.fcbEstateId + '&canView=' + isView
      window.open(link)
    }
  },
  watch: {
    '$route': {
      immediate: true,
      async handler(newVal, oldVal) {
        if (newVal.name !== "housing" || (this.search.state.estateId === newVal.params.id && oldVal)) return;
        
        try {
          this.search.state.estateId = newVal.params.id
          let res = await axios.get(getEstateByHouseId, { params: { estateId: newVal.params.id } })
          this.estateName = res.data.estateName
          this.fcbEstateId = res.data.fcbEstateId
        } catch (e) {
          this.$router.back()
        }
      } 
    }
  },
  mounted() {
    this.searchName()
  },
  components: {
    "com-head": comHead,
    "com-dialog": comDialog,
    "select-vr": selectVR,
    "com-record": comRecord,
    "com-share": comShare,
    "com-pagination": comPagination,
    comUpSelect
  },
};
</script>

<style lang="less">

.my-autocomplete {
  li {
    line-height: normal;
    padding: 0 !important;
    .item-layout {
      padding: 7px !important;

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

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

    .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>

