<template>
  <com-head :options="headList" showCtrl v-model="mpStatus">
    <el-form label-width="90px" inline="true">
      <el-form-item label="VR项目：">
        <el-input v-model="search.state.houseTitle" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="项目类型：">
        <el-select v-model="search.state.type" placeholder="全部">
          <el-option v-for="(item) in houseType" :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.estateName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="公司：">
        <com-company v-model="search.state.belongCompany" />
      </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 label="提审时间：">
        <el-date-picker
          v-model="time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="提审时间：">
        <el-date-picker
          v-model="submitAuditTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item class="searh-btns">
        <el-button @click="search.reset">重置</el-button>
        <el-button type="primary" @click="search.submit">查询</el-button>
        <el-button type="primary" @click="exportExe" :disabled="!pag.state.total">导出</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer">
    <div class="body-head">
      <h3>{{title}}</h3>
    </div>

    <el-table
      ref="multipleTable"
      :data="dataList.state"
      tooltip-effect="dark"
      style="width: 100%"
      @row-click="selectRow"
    >
      <el-table-column label="VR项目" prop="houseTitle" v-slot:default="{ row }">
        <span  @click="shareRow(row)" style="cursor: pointer">{{row.houseTitle}}</span>
      </el-table-column>
      <el-table-column label="项目类型" prop="type" v-slot:default="{ row }">
        <span>{{getHouseName(row.type)}}</span>
      </el-table-column>
      <el-table-column label="所属楼盘" prop="estateName"></el-table-column>
      <el-table-column label="公司" prop="belongCompanyName"></el-table-column>
      <el-table-column label="创建人" prop="createByName"></el-table-column>
      <el-table-column label="提审时间" prop="submitAuditTime"></el-table-column>
      <el-table-column label="审核状态" prop="auditStatus" v-slot:default="{ row }">
        <div class="status" :class="{interactive: row.countNum > 0}" @click="row.countNum > 0  && showSelectRow(row)">
          <span>{{row.status === adoptStatus ? row.online ? '已上线': '已审核' : getExamineName(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="操作" v-slot:default="{ row }">
        <span class="oper-span" @click="shareRow(row)">预览</span>
        <span class="oper-span"
          :class="{
            disable: !(
              (row.status === noAuditStatis && (user.role === 'admin' || user.role === 'group')) ||
              (row.status === noComAuditStatus && (user.role === 'admin' || user.role === 'region'))
            )
          }" 
          @click="(
            (row.status === noAuditStatis && (user.role === 'admin' || user.role === 'group')) ||
            (row.status === noComAuditStatus && (user.role === 'admin' || user.role === 'region'))
          ) && oper.readyUpdate(row); (oper.state.operStatus = 1)" 
          v-if="auth.update">
          
          审核
        </span>
        <!-- <span
          v-if="auth.update"
          class="oper-span"
          :class="{disable: row.status !== adoptStatus}"
          @click="row.status === adoptStatus && offlineItem(row)">
          {{row.online === 1 ? '下线' : '上线' }}
        </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-dialog title="审核" v-model:show="oper.state.show" @submit="updateExamine()">
    <el-form ref="form" :model="oper.state" label-width="120px" class="examine-from">
      <el-form-item label="审核结果：">
        <el-radio-group v-model="oper.state.operStatus">
          <el-radio v-for="item in examineMap" :key="item.value" :label="item.value">{{item.name}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="审核备注：">
        <el-input type="textarea" v-model="oper.state.maker" maxlength="500" show-word-limit></el-input>
      </el-form-item>
    </el-form>
  </com-dialog>

  <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-share
    :setLogo="auth.update"
    v-if="shareData.show"
    v-model:show="shareData.show" 
    :items="shareData.data" />

</template>

<script>
import axios from 'axios';
import { computed, ref, watch, watchEffect } from "vue";
import getTableState, {getParams} from "@/state/tableRef";
import comDialog from "@/components/dialog";
import auth from "@/state/viewAuth";
import comPagination from "@/components/pagination";
import comCompany from "@/components/company-select";
import comRecord from "@/components/record";
import comHead from "@/components/head";
import comShare from "@/view/properties/estate/share";
import comUpSelect from "@/view/properties/estate/up-select";
import { dateFormat } from '@/util'
import user from '@/state/user'
import {
  getExamineViewList,
  estateExamine,
  estateOnline,
  getHouseShares,
  getHouseUpShares,
  hasHouseIsDel,
  exporrtAuditEstate
} from '@/request/config'
import { 
  HOUSE_TYPE_SELECT, 
  EXAMINE_REQ_SELECT,
  EXAMINE_SHOW_STATUS, 
  EXAMINE_ALL_STATUS,
  EXAMINE_NO_ADOPT_STATUS,
  EXAMINE_NO_COM_ADOPT_STATUS,
  EXAMINE_NO_AUDIT_STATUS,
  UN_REQ_NUM,
  EXAMINE_ADOPT_STATUS,
  EXAMINE_NO_ADOPT_ALL_STATUS,
  EXAMINE_NO_COM_AUDIT_STATUS,
  EXAMINE_DRAFT_STATUS,
  EXANINE_SUCCESS_STATUS,
  getName 
} from '@/constant'

export default {
  name: 'examine',
  setup() {
    const mpStatus = ref(user.value.role === 'region' ? EXAMINE_NO_COM_AUDIT_STATUS : EXAMINE_NO_AUDIT_STATUS)
    const headList = ref(EXAMINE_SHOW_STATUS);
    const state = getTableState({
      getUrl: getExamineViewList,
      updateUrl: estateExamine,
      operAttr: { 
        operStatus: 1,
        maker: '',
        auditId: ''
      },
      searchAttr: { 
        time: "", estateName: '', houseTitle: '', type: UN_REQ_NUM, 
        status: mpStatus.value, 
        statuslist: '',
        belongCompany: '', 
        online: '',
        startSubmitAuditTime: '', endSubmitAuditTime: '' , 
        startTime: '', endTime: '' 
      }
    });

    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 === EXAMINE_ALL_STATUS){
        state.search.value.state.statuslist = ''
      } else {
        state.search.value.state.online = ''
        state.search.value.state.statuslist = mpStatus.value  + ''
      }

    })

    const title = computed(() => {
      let item = headList.value.find(({value}) => value === state.search.value.state.operStatus)
      return item ? item.name : ''
    })
    const time = ref(null)
    const submitAuditTime = ref(null)

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

    watch(
      [() => state.search.value.state.startTime, () => state.search.value.state.endTime],
      () => {
        if (!state.search.value.state.startTime || !state.search.value.state.endTime) {
          time.value = null
        }
      }
    )

    
    watch(submitAuditTime, () => {
      if (submitAuditTime.value) {
        state.search.value.state.startSubmitAuditTime = dateFormat(new Date(submitAuditTime.value[0]), 'yyyy-MM-dd hh:mm:ss')
        state.search.value.state.endSubmitAuditTime = dateFormat(new Date(submitAuditTime.value[1]), 'yyyy-MM-dd 23:59:59')
      } else {
        state.search.value.state.startSubmitAuditTime = state.search.value.state.endSubmitAuditTime = ''
      }
    })
    watch(
      [() => state.search.value.state.startSubmitAuditTime, () => state.search.value.state.endSubmitAuditTime],
      () => {
        if (!state.search.value.state.startSubmitAuditTime || !state.search.value.state.endSubmitAuditTime) {
          submitAuditTime.value = null
        }
      }
    )

    
    

    return { ...state, headList, title, auth, time, submitAuditTime, mpStatus };
  },
  data() { 
    return {
      
      recordData: { show: false, id: 0 },
      examineMap: EXAMINE_REQ_SELECT,
      status: EXAMINE_SHOW_STATUS,
      draftStatus: EXAMINE_DRAFT_STATUS,
      noAdoptStatus: EXAMINE_NO_ADOPT_STATUS,
      adoptStatus: EXAMINE_ADOPT_STATUS,
      noAuditStatis: EXAMINE_NO_AUDIT_STATUS,
      noComAuditStatus: EXAMINE_NO_COM_AUDIT_STATUS,
      noComAdoptStatus: EXAMINE_NO_COM_ADOPT_STATUS,
      upData: {show: false, data: 0, value: {init: null, vrList: []}, row: null},
      houseType: HOUSE_TYPE_SELECT,
      shareData: { show: false, data: 0 },
      user
    }
  },

  methods: {
    async exportExe() {
      let params = {
        ...getParams(this.search.state),
        pageNum: this.pag.state.currPage,
        pageSize: this.pag.state.size
      }
      if (!params.startTime || !params.endTime) {
        return this.$alert('请先选择提审时间段', '提示')
      } else {
        const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
        if (monthDiff(this.time[0], this.time[1]) > 3) {
          return this.$alert('最多支持导出连续四个月的数据', '提示')
        }
      }
      
      let res = await axios.get(exporrtAuditEstate, { params })
      location.href = res.data.data
    },
    async shareRow(data) {
      let res = await axios.get(getHouseShares, { params: {houseId: data.id} })
      let shareItems = []
      if (res.data) {
        shareItems = res.data.map(item => ({
          ...item,
          QrCode: item.icon,
          type: item.type,
          houseTitle: item.sceneTitle || data.houseTitle,
          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) {
        this.shareData.show = true
        this.shareData.data = shareItems
      } else {
        await this.$confirm('暂无预览链接，请先设置初始场景。', '提示')
      }
    },
    getExamineName: getName(EXAMINE_SHOW_STATUS),
    getHouseName: getName(HOUSE_TYPE_SELECT),
    showSelectRow(data) {
      this.recordData.show = true
      this.recordData.id = data.id
    },
    async updateExamine() {
      if (!this.oper.state.operStatus) {
        return this.$alert('审核结果不能为空！', '提示')
      }

      await axios.post(estateExamine, {
        id: this.oper.state.auditId,
        auditStatus: this.oper.state.operStatus,
        auditRemark: this.oper.state.maker,
        auditHouseType: 1
      })

      this.$alert('审核成功', '提示')
      
      this.oper.reset()
      this.dataList.refer()
    },

    async offlineItem(data, isSelect = false) {
      if (data.operStatus === 0) return;
      let online = Number(!data.online)

      if (!online) {
        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 = []
      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 }, {})
      data.online = online
      this.upData.show = false
      this.upData.data = null
      this.upData.row = null

      this.$alert((online ? '上' : '下') + '线成功', '提示')
      this.dataList.refer()
    },
    preview(data) {
      let link = data.status === this.adoptStatus ? data.vrLink : data.innerVrLink

      if (link) {
        window.open(link)
      } else {
        this.$alert('当前项没有链接！', '提示')
      }
    },
    
  },
  components: {
    comUpSelect,
    "com-dialog": comDialog,
    "com-company": comCompany,
    "com-head": comHead,
    "com-record": comRecord,
    "com-share": comShare,
    "com-pagination": comPagination
  },
};
</script>

<style lang="scss" scoped>
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}

.examine-from {
  width: 320px;
  margin: 0 auto;
}

.interactive {
  cursor: pointer;
}

.error {
  color: var(--primaryColor);
}

</style>