<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.gardenNumber" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="小区名称：">
        <el-input v-model="search.state.gardenName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="城市：">
        <el-select v-model="search.state.cityId" clearable  filterable placeholder="请选择">
          <el-option
            v-for="item in citys"
            :key="item.cityId"
            :label="item.cityName"
            :value="item.cityId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行政区：">
        <com-region :cityId="search.state.cityId" v-model="search.state.areaId" clearable filterable  placeholder="请输入" />
      </el-form-item>
      <el-form-item label="物业类型：">
        <el-select v-model="search.state.propertySort" clearable  filterable placeholder="请选择">
          <el-option
            v-for="item in propertys"
            :key="item.propertySort"
            :label="item.propertySortName"
            :value="item.propertySort">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="建成年代：">
        <el-date-picker
          v-model="yearsTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人：">
        <el-input v-model="search.state.auditorName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="创建人：">
        <el-input v-model="search.state.creatorName" 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 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>全部小区</span> 
      </h3>
      <div>
        <el-button type="primary" @click="oper.readyInsert" v-if="auth.add">创建小区</el-button>
        <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.delete"></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="小区编码" v-slot:default="{ row }">
        {{row.gardenNumber}}
      </el-table-column>
      <el-table-column label="小区名称" v-slot:default="{ row }">
        <a class="oper-link" @click="$router.push({name: 'secondHouse', params: { id: row.gardenId, cityId: row.cityId }})">{{row.gardenName}}</a>
      </el-table-column>

      <el-table-column label="城市" prop="cityName"></el-table-column>
      <el-table-column label="片区|商圈" v-slot:default="{ row }" >
        <span v-if="row.regionName || row.geographyAreaName">{{row.regionName}}|{{row.geographyAreaName}}</span>
      </el-table-column>
      <el-table-column label="物业类型" prop="propertySortName"></el-table-column>
      <el-table-column label="建成年代" v-slot:default="{ row }">
        <span>{{row.buildStartTime}}-{{row.buildEndTime}}</span>
      </el-table-column>
      <el-table-column label="创建人" prop="creatorName"></el-table-column>
      <el-table-column label="所属公司" prop="companyName"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="状态" v-slot:default="{row}" width="90">
        <div class="status" :class="{interactive: row.auditStatus !== draftStatus}" @click="row.auditStatus !== draftStatus && selectRow(row)">
          <span>{{getStatusName(row.auditStatus)}}</span>
          <template v-if="row.auditStatus !== draftStatus || row.auditorName || row.auditTime">
            <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="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="(~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)) && editHouse(row)" 
          :class="{disable: !~[draftStatus, noAdoptStatus, noComAdoptStatus].indexOf(row.auditStatus)}" 
          v-if="auth.update"
          >
          编辑航拍
        </span>
        <span
          class="oper-span" 
          @click="~[uplineStatus].indexOf(row.auditStatus) && editHouse(row, 1)" 
          :class="{disable: (!~[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.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-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-dialog
    title="新增二手房小区" v-model:show="oper.state.show" @submit="insertItem" @quit="oper.quit"
  >
    <el-form ref="form" :model="form" label-width="100px" class="info-from" style="width: 480px">
      <el-form-item label="小区名称：" class="mandatory" style="margin-top:60px">
        <el-autocomplete
          popper-class="my-autocomplete"
          class="inline-input"
          v-model="oper.state.gardenName"
          :fetch-suggestions="searchName"
          @focus="oper.state.gardenId = ''"
          placeholder="小区名称："
          @select="handleSelect"
        >
          <template v-slot="{ item }">
            <div class="item-layout" :class="{disable: item.disable}" @click="$event => clickEstateItem($event, item)">
              <span class="name">{{ item.gardenNumber }}</span>
              <span class="addr">{{ item.gardenName }}</span>
              <span class="addr">{{ item.regionName }}|{{ item.geographyAreaName }}</span>
              <span class="addr">{{ item.cityName }}</span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
    </el-form>

  </com-dialog>


  
</template>

<script>
import axios from 'axios'
import qrcode from 'qrcode'
import {ref,reactive, watch} from 'vue'
import getTableState from '@/state/tableRef'
import comHead from "@/components/head";
import comDialog from "@/components/dialog";
import comRegion from "@/components/region";
import comShare from "./share";
import comRecord from "./record";
import auth from "@/state/viewAuth";
import comPagination from "@/components/pagination";
import { dateFormat } 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,
  EXAMINE_NO_ADOPT_STATUS,
  EXAMINE_NO_AUDIT_STATUS,
  EXAMINE_NO_COM_ADOPT_STATUS,
  EXAMINE_ADOPT_STATUS,
  EXAMINE_UP_ONLINE_STATUS,
  getName,

  REDIRECT_AUDIT_BRING_STATUS,
  REDIRECT_AUDIT_RECALL_STATUS,
  REDIRECT_AUDIT_UP_STATUS,
  REDIRECT_AUDIT_OFF_STATUS,
  getRedirectCommunityAuditBody
} from '@/constant'
import { 
  getCommunityList1 as getCommunityList,
  deleteCommunity,
  communityOnline,
  auditCommunity,
  dismissCommunity,
  insertCommunity,
  getHdCommunityNames
} from '@/request/config'

const getTimeMapSearch = (search, start, end) => {
  const time = ref(null)

  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: getCommunityList,
      insertUrl: insertCommunity,
      delUrl: deleteCommunity,
      pagAttr: {listMap: {vrGardenId: 'id'}},
      operAttr: { 
        gardenId: "", 
        vrGardenId: "",
        gardenName: '',
        creatorName: user.value.info.nickName,
        creatorId: user.value.info.id,
        companyId: user.value.info.departmentId,
        companyName: ''
      },
      searchAttr: {
        gardenNumber: "",
        gardenName: '',
        cityId: '',
        readType: 'all',
        areaId: '',
        propertySort: '',
        creatorName: '',
        auditorName: '',
        startCreateTime: '',
        endCreateTime: '',
        buildStartTime: '',
        buildEndTime: ''
      }
    })


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

    const names = ref([])
    const initNames = ref([])
    const searchName = async (keyword = '', cb) => {
      if (keyword === '') return cb && cb([])
      cb && cb(names.value.map(item => ({...item, value: item.gardenName})));

      let res = await axios.post(getHdCommunityNames, {keyword: keyword, pageSize: 100, currentPage: 1})
      names.value = res.data.records
      if (!keyword) {
        initNames.value = names.value
      }
      cb && cb(names.value.map(item => ({...item, value: item.gardenName, disable: item.isGray})))
    }

    return { 
      ...state, 
      headList, 
      auth, 
      user, 
      searchName, 
      initNames, 
      names,
      yearsTime: getTimeMapSearch(state.search, 'buildStartTime', 'buildEndTime'),
      createTime: getTimeMapSearch(state.search, 'startCreateTime', 'endCreateTime'),
      citys: reactive([]),
      propertys: reactive([])
    };
  },
  data() {
    return {
      gardenName: '',
      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,
      uplineStatus: EXAMINE_UP_ONLINE_STATUS,
      recordData: { show: false, id: 0 },
      shareData: { show: false, data: 0 }
    }
  },
  methods: {
    clickEstateItem(ev, item) {
      if (item.disable) {
        ev.stopPropagation()
      }
    },
    getStatusName: getName(EXAMINE_SHOW_SELECT_STATUS_TEXT),
    async insertItem() {
      if (!this.oper.state.gardenName) {
          return this.$alert('小区名称不能为空！', '提示')
      }

      if (!this.oper.state.gardenId.trim()) {
        let estate = this.names.find(({gardenName}) => gardenName === this.oper.state.gardenName)
        if (!estate) {
          return this.$alert('无法匹配当前名称的小区！', '提示')
        } else {
          this.oper.state.gardenId = estate.gardenId
        }
      }
      
      if (this.oper.state.id) {
        this.oper.update();
      } else {
        this.oper.insert();
      }
    },
    selectRow(data) {
      this.recordData.show = true
      this.recordData.id = data.vrGardenId
    },
    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.gardenName,
        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)
      }
    },
    async offlineItem(data) {
      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 === 5 ? REDIRECT_AUDIT_OFF_STATUS : REDIRECT_AUDIT_UP_STATUS

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

    async examine(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(auditCommunity, getRedirectCommunityAuditBody(data, REDIRECT_AUDIT_BRING_STATUS))
        // data.auditId = res.data.auditId
        this.$alert('提审成功', '提示')
      } else {
        await axios.post(dismissCommunity, getRedirectCommunityAuditBody(data, REDIRECT_AUDIT_RECALL_STATUS))
        this.$alert('撤销成功', '提示')
      }

      this.dataList.refer()
    },
    resetSearch() {
      let type = this.search.state.type
      this.search.reset()
      this.search.state.type = type
    },
    editHouse(item, isView = 0) {
      let link = process.env.VUE_APP_PREFIX + '/sh_house/edit.html?m=' + item.id + '&h=' + item.gardenId + '&canView=' + isView
      window.open(link)
    }
  },
  mounted() {
    this.searchName()
  },
  components: {
    "com-head": comHead,
    "com-dialog": comDialog,
    "com-record": comRecord,
    "com-share": comShare,
    "com-pagination": comPagination,
    "com-region": comRegion
  },
};
</script>

<style lang="less">

.my-autocomplete {
  .el-autocomplete-suggestion {
    min-width: 220px;
    // width: auto !important;
  }
  li {
    line-height: normal;
    padding: 0 !important;
    .item-layout {
      padding: 7px !important;
      display: flex;
      justify-content: space-between;
      span {
        margin: 0 5px;
        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>

