<template>
  <div class="main">
    <m-title area="title" :editable="false"> 静安智慧房管 </m-title>
    <m-grid
      v-if="layout.boxNum > 0"
      :template="layout.template"
      columns="1fr 1.5fr 1fr"
      :rows="`${layout.rows}`"
    >
      <Map ref="mapRef" @event="onMapClick" />
      <div
        v-for="(_, index) in new Array(layout.boxNum)"
        :key="index"
        class="box"
        :area="`box${index + 1}`"
      >
        <m-animate
          :enter="
            layout.template.some((item) => item.startsWith(`box${index + 1}`))
              ? 'fadeInLeft'
              : 'fadeInRight'
          "
          :leave="
            layout.template.some((item) => item.startsWith(`box${index + 1}`))
              ? 'fadeOutLeft'
              : 'fadeOutRight'
          "
        >
          <component
            :is="componentList[components[index]]"
            v-if="!!components[index] && !fullScreen"
          />
        </m-animate>
      </div>
    </m-grid>
    <m-modal v-model="showModal" title="选择展示屏">
      <div class="list-content">
        <div v-for="item in list" :key="item.id" class="item">
          <p>{{ item.configName }}</p>
          <p>{{ item.updateTime }}</p>
          <n-button size="tiny" type="info" ghost dashed @click="check(item)">
            查看
          </n-button>
        </div>
      </div>
    </m-modal>
  </div>
  <MapBtns
    :full-screen="fullScreen"
    :is-default-screen="isDefaultScreen"
    :only-one-view="onlyOneView"
    @touch="handleMapBtnsEvents"
  />
  <m-modal v-model="showCommunityDrawer" title="小区档案" width="70%">
    <div class="community-info">
      <m-sub>小区基本信息</m-sub>
      <m-form
        :template="[
          'stNameFrst:小区名称|stNameScnd:小区别名|addrFrst:小区地址',
          'finishDate:竣工日期|stCnstArea:总建筑面积(㎡)|isOpen:小区封闭与否',
          'hoName:房管办|streetName:街道|loopLineName:环线',
          'stCspEast:小区四至范围东|getStCspWest:小区四至范围西|stCspSouth:小区四至范围南',
          'stCspNorth:小区四至范围北|stNotcsparea:四至不包括|stKind:小区性质',
          'sectType:小区类型|cspServiceTypeName:物业服务类型|totOngParks:地面停车位数量',
          'totUngParks:地下停车位数量|landArea:占地面积|totUnits:总门牌数',
          'totHous:总户数||',
        ]"
        :data="info"
      />
      <m-sub>小区管理处信息</m-sub>
      <m-form
        :template="[
          'csName:管理处名称|csAddress:办公地址|csContacter:管理处联系人',
          'csTel:联系人联系电话|csDayTel:日间报修电话|nightTel:夜间报修电话',
          'complaintTel:物业投诉电话|csFax:管理处传真|csPostCode:管理处邮编',
        ]"
        :data="info"
      />
      <m-sub>物业企业信息</m-sub>
      <m-form
        :template="[
          'cspName:物业企业名称|cspContractStartDate:合同开始日期|cspContractEndDate:合同结束日期',
          'legalRepName:企业法人代表|cspTel:企业联系电话|cspContacter:企业联系人',
          'cspAddr:办公地址||',
        ]"
        :data="info"
      />
      <m-sub>小区经理信息</m-sub>
      <m-form
        :template="[
          'csmName:姓名|csmJobCode:上岗证号|certType:证件类型',
          'csmJobQualification:资格证书名称|csmJobLog:资格证书编号|csmTel:固定电话',
          'credentialsNo:证件号码||',
        ]"
        :data="info"
      />
      <m-sub>业主大会信息</m-sub>
      <m-form
        :template="[
          'hocCode:业主大会代码|hocName:名称|hocAddr:地址',
          'electionDate:选举时间|directorName:主任|deputyDirectorName:副主任',
          'commValidDate:任期|hocTerm:第几届|recordDate:业主大会备案日期',
          'onwersTypeoperName:业主大会运作情况类别|onwersTransitionName:换届情况类别|conStartDate:业委会任期起始时间',
          'conEndDate:业委会任期结束时间||',
        ]"
        :data="info"
      />
      <m-sub>居委会信息</m-sub>
      <m-form
        :template="[
          'cmtName:居委会名称|cmtAddr:居委会地址|cmtDirectorName:居委主任姓名',
          'cmtSecretaryName:居委书记姓名||',
        ]"
        :data="info"
      />
    </div>
  </m-modal>
  <m-modal v-model="showSearchModal" title="搜索">
    <SearchView @select="onSelectCommunity" />
  </m-modal>
</template>

<script lang="ts" setup>
import useLayout from '@/hooks/useLayout'
import useComponent from '@/hooks/useComponent'
import { onMounted, ref, shallowRef } from 'vue'
import { ajax, api } from '@/ajax'
import { NSpace, NButton } from 'naive-ui'
import SearchView from './components/search-view.vue'
import MapBtns from './components/map-btns.vue'
import Map from './components/map.vue'
import { bus } from '@/utils/component-list'

const mapRef = shallowRef<any>(null)
const { layout } = useLayout()
const { components, componentList } = useComponent()
const list = ref<any[]>([])
const showModal = ref(false)
const defaultConfig = {
  layout: {
    template: ['box1 . box3', 'box2 . box4', 'box2 . box5'],
    rows: '1fr 1fr 0.7fr',
    boxNum: 5,
  },
  components: {
    '0': 'A015',
    '1': 'A016',
    '2': 'A017',
    '3': 'A018',
    '4': 'A019',
  },
}
const onlyOneView = ref(false) // 目前是否为特定id的url大屏
function initConfig() {
  if (window.location.hash) {
    const id = window.location.hash.split('/')?.[1]
    ajax
      .get({
        url: api.CONFIGS,
        params: { id },
      })
      .then((res) => {
        const config = res?.data?.content?.[0] || {}
        check(config)
      })
    onlyOneView.value = true
    return
  }
  layout.value = defaultConfig.layout
  components.value = defaultConfig.components
  isDefaultScreen.value = true
}
onMounted(initConfig)

const isDefaultScreen = ref(true)
function check({ id, configJson }) {
  const config = JSON.parse(configJson)
  config?.layout && (layout.value = config.layout)
  config?.components && (components.value = config.components)
  showModal.value = false
  isDefaultScreen.value = false
  window.location.hash = `#/${id}`
}

const fullScreen = ref(false)
const showSearchModal = ref(false)

function handleMapBtnsEvents(key: string) {
  switch (key) {
    case 'list':
      ajax
        .get({
          url: api.CONFIGS,
          params: { configStatus: '1', pageSize: 9000 },
        })
        .then((res) => {
          list.value = res?.data?.content || []
          showModal.value = true
        })
      break
    case 'home':
      window.history.replaceState(
        null,
        '',
        window.location.pathname + window.location.search,
      ) // 移除hash
      initConfig()
      break
    case 'full':
      fullScreen.value = !fullScreen.value
      break
    case 'in':
      mapRef.value?.zoomIn()
      break
    case 'out':
      mapRef.value?.zoomOut()
      break
    case 'search':
      showSearchModal.value = true
      break
    default:
      break
  }
}
let pointsLayer: any
bus.on('addPoints', (data) => {
  // TODO 地图撒点
  addPoints(data)
})

function addPoints(data) {
  mapRef.value?.remove(pointsLayer)
  pointsLayer = mapRef.value?.addPoints(data)
}

const showCommunityDrawer = ref(false)
const info = ref({
  caoInfo: null,
  ppInfo: {
    _id: {
      timestamp: 1.629786446e9,
      counter: 1.573359e7,
      randomValue1: 3636833.0,
      randomValue2: 28341.0,
    },
    localUpdateTime: '2021-08-24 14:27:26',
    syncTime: '',
    legalRepName: '范锋铭',
    bizLicenseCode: '',
    cspTel: '62318697',
    cspFax: '',
    sign: '1',
    dwPkCsp: '5B00D78A8C4F2BA53D7E418D43F50F4A',
    cspContacter: '黄蓓',
    registerAddress: '上海市嘉定区金沙江路3131号2幢1781号',
    cspId: '1811291179633917',
    marketCsp: 'S301811291179633917',
    bizLicenseValidDate: '',
    orgCode: '91310114MA1GUABG5L',
    cspEntQualification: '',
    realtyId: '',
    totSects: '3',
    hpbId: '310114000000',
    id: '1811291179633917',
    cspGuid: 'S301811291179633917',
    codeValidDate: '',
    cspAddr: '余姚路608号4号103室',
    cspName: '上海佑广物业管理有限公司',
  },
  cmInfo: {
    _id: {
      timestamp: 1.629786443e9,
      counter: 1.5732455e7,
      randomValue1: 3636833.0,
      randomValue2: 28341.0,
    },
    syncTime: '',
    certTypeName: '',
    manageCommunityCount: '',
    certType: '',
    csmName: '黄蓓',
    operatorSign: '',
    sign: '1',
    csmJobCode: '',
    csmGuid: 'S301906211184598055',
    operator: '',
    csmId: '1906211184598055',
    csmJobLog: '1603000173300012',
    cspId: '1811291179633917',
    dwPkCspSectManger: '430FB005F3704F956B87280D3494DB0A',
    id: '1906211184598055',
    localUpdateTime: '2021-08-24 14:27:23',
    credentialsNo: '',
    creator: '',
    creatorSign: '',
    csmPhone: '',
    csmTel: '',
    marketCspSectManger: 'S301906211184598055',
    dwPkCsp: '5B00D78A8C4F2BA53D7E418D43F50F4A',
    updateTime: '',
    marketCsp: 's301811291179633917',
    createTime: '',
    csmJobQualification: '助理物业管理师',
    cspName: '上海佑广物业管理有限公司',
  },
  icInfo: null,
  febInfo: null,
  rcInfo: null,
  _id: {
    timestamp: 1.629792499e9,
    counter: 2547848.0,
    randomValue1: 9444117.0,
    randomValue2: 18755.0,
  },
  stKindName: '商品房',
  cspTel: '62318697',
  csId: '1911211187592660',
  totOngParks: 40.0,
  landArea: '82',
  commValidDate: '1',
  sign: '1',
  hoName: '曹家渡街道房管办事处（曹家渡街道物业管理中心）',
  csmJobCode: '',
  finishDateStage: '1',
  csmJobLog: '1603000173300012',
  cspId: '1811291179633917',
  directorName: '金树姗',
  hocId: '1911211187592612',
  id: '120302190529156',
  cspAddr: '余姚路608号4号103室',
  stCspNorth: '安远路',
  totHous: 233.0,
  stCnstArea: 22577.14,
  cmtId: '0',
  conStartDate: '2018-09-19',
  houseMgn: '',
  cspContacter: '黄蓓',
  sectTypeName: '住宅',
  hoId: '310106000137',
  isOpen: '否',
  marketHoc: 'S301911211187592612',
  totUnits: 46.0,
  stNotcsparea: '',
  stNameScnd: '',
  cspServiceType: '2',
  csmJobQualification: '助理物业管理师',
  cspName: '上海佑广物业管理有限公司',
  cspServiceTypeName: '专业委托物业管理（业主大会阶段）',
  streetId: '310106014000',
  legalRepName: '范锋铭',
  csmName: '黄蓓',
  loopId: '200000000001',
  hocTerm: '1',
  sectId: '120302190529156',
  hocAddr: '余姚路402弄10号',
  hocCode: '0601404130',
  csmId: '1906211184598055',
  stNameFrst: '静安恬园',
  cspContractStartDate: '2019-07-01',
  streetName: '曹家渡街道',
  onwersTransition: '1',
  stKind: '01',
  deputyDirectorName: '王勇',
  onwersTypeoper: '1',
  recordDate: '',
  localUpdateTime: '2021-08-24 16:08:18',
  hocGuid: 'S301911211187592612',
  cspContractEndDate: '2021-06-30',
  sectType: '1',
  establishIC: '2',
  stCspEast: '延平路',
  hocName: '上海市静安区静安恬园业主大会',
  stCspSouth: '余姚路',
  totUngParks: 0.0,
  addrFrst: '余姚路380-400（双）号 402弄1-9、11号',
  dwPkHoc: '90FADF61F74AB90CAF8834E8FEE8576B',
  electionDate: '20180824',
  loopLineName: '中环以内',
  hpbId: '310106000000',
  finishDate: '',
  getStCspWest: '泰州路',
  conEndDate: '2023-09-19',
})
const onMapClick = () => {
  showCommunityDrawer.value = true
}

const onSelectCommunity = (data: any) => {
  // TODO 搜索小区后点选小区撒点
  addPoints([data])
}
</script>

<style lang="stylus" scoped>
@import '../components/MyComponent/main.styl'
.main
  width 100%
  height 100%
  display flex
  flex-direction column
.box
  border-radius .02rem
  background transparent
  $blur(0)
  position relative
  overflow hidden
.list-content
  max-height 60vh
  overflow-y auto
  >.item
    font-size .12rem
    font-weight bold
    display flex
    align-items center
    padding .05rem
    &:nth-of-type(2n+1)
      background rgba(0,0,0,.5)
    &:hover
      background rgba(255,255,255,.2)
    >p
      flex 1
      overflow hidden
      white-space nowrap
      text-overflow ellipsis
      &:nth-of-type(2)
        flex 2
        margin 0 .1rem
.community-info
  >.my-sub
    margin-top .1rem
    font-size .12rem
    padding-left .1rem
    background-clip text
    -webkit-background-clip text
    -webkit-text-fill-color transparent
    background-image linear-gradient(to bottom, #FFD1B2, #FF8635)
</style>
