<template>
  <div class="population-drawer">
    <m-card title="相关案件">
      <div class="case-wrap">
        <CaseList :list="caseInfo" />
      </div>
    </m-card>
    <m-card title="人口详情">
      <Tabs class="tabs" :list="tabs" horizontal @select="onSelect" />
      <template v-if="curTab === 'house'">
        <SubTitle>基本信息</SubTitle>
        <m-form
          :template="[
            'stNameFrst:所属小区|buildingAddr:门牌幢',
            'sectTypeName:小区类型|houseNo:室号',
            'cspName:物业公司|cspContacter:物业经理',
            'csName:管理处|unitFlag:有无电梯>hasElev',
            'hocName:业委会|cmtName:居委会',
          ]"
          :formatter="{ hasElev }"
          :data="houseData"
          label-width="1.2rem"
        />
        <SubTitle>房主信息</SubTitle>
        <m-form
          :template="['name:姓名|phone:手机号码', 'household:户籍|']"
          :data="{
            name: '无',
            phone: '无',
            household: '无',
          }"
          label-width="1.2rem"
        />
        <Tabs
          class="tabs"
          :list="tabs2"
          horizontal
          @select="curTab2 = $event"
        />
        <template v-if="curTab2 === 'community'">
          <m-form
            :template="[
              'stNameFrst:小区名称',
              'addrFrst:小区地址|cmtName:所属居委会',
              'totUnits:总门牌幢数|totHous:总户数',
              'stCnstArea:总建筑面积>area|landArea:占地面积>area',
              'range:小区四至范围|stNotcsparea:四至范围不包括',
            ]"
            :data="communityData"
            label-width="1.2rem"
            :formatter="formatter"
          />
        </template>
        <template v-else-if="curTab2 === 'room'">
          <template v-if="showBuildingRoom">
            <div class="person-bar">
              <div class="photo"></div>
              <div class="back-btn" @click="showBuildingRoom = false">返回</div>
            </div>
            <div class="room-table">
              <m-table
                :template="['户室|面积', 'houseNo|houseArea>area']"
                :data="buildingRoomList"
                :formatter="formatter"
              />
            </div>
          </template>
          <template v-else>
            <div
              v-if="
                communityInfo.buildingList &&
                  communityInfo.buildingList.length > 0
              "
              class="building-list"
            >
              <div
                v-for="item in communityInfo.buildingList"
                :key="item.id"
                @click="selectBuilding(item)"
              >
                <p class="title">{{ item.unitNo }}</p>
                <p class="line" />
                <p>{{ item.unitFlag ? '有' : '无' }}电梯</p>
                <p>{{ item.unitKindName }}</p>
              </div>
            </div>
            <div v-else style="height: 30vh">
              <m-empty :img="empty" hidden-text />
            </div>
          </template>
        </template>
        <template v-else-if="curTab2 === 'property'">
          <m-form
            :template="[
              'cspName:物业企业名称|hpbName:注册区县',
              'registerAddress:注册地址|orgCode:组织机构代码',
              'legalRepName:法人代表|cspContacter:企业联系人',
              'cspTel:企业联系人电话|cspFax:企业联系人传真',
              'bizLicenseValidDate:营业执照有效期|bizLicenseCode:营业执照号',
            ]"
            :data="propertyInfo"
            label-width="1.4rem"
          />
          <SubTitle>小区管理处</SubTitle>
          <m-form
            :template="[
              'csName:管理处名称|csAddress:办公地址',
              'csContacter:联系人姓名|csTel:联系人电话',
              'csDayTel:日间报修电话|nightTel:夜间报修电话',
              'csFax:管理处传真|complaintTel:物业投诉电话',
            ]"
            :data="communityInfo.manageInfo"
            label-width="1.4rem"
          />
        </template>
        <template v-else-if="curTab2 === 'committee'">
          <m-form
            :template="[
              'hocCode:业主大会代码|hocName:业主大会名称',
              'hocAddr:办公地址',
            ]"
            :data="communityInfo.hocInfo"
            label-width="1.4rem"
          />
          <SubTitle>指挥体系</SubTitle>
          <m-table
            v-if="
              communityInfo.hocInfo.memberList &&
                communityInfo.hocInfo.memberList.length > 0
            "
            :template="[
              '职位|姓名|性别|联系电话|政治面貌',
              'dirDuty|dirName|dirSex|phone|dirPoliticsStatus',
            ]"
            :data="communityInfo.hocInfo.memberList"
          />
          <m-empty v-else :img="empty" hidden-text />
        </template>
        <template v-else-if="curTab2 === 'device'">
          <div class="select-bar">
            <a-select
              v-model:value="deviceType"
              dropdown-class-name="device-selector-drop-down"
            >
              <a-select-option
                v-for="option in deviceOptions"
                :key="option.name"
                :value="option.name"
              >
                {{ option.name }}
              </a-select-option>
            </a-select>
          </div>
          <div v-if="deviceList.length > 0" class="wrapper">
            <m-table
              :template="[
                '序号|安装位置*2|名称*2|类型|维保单位*3',
                'index|ieAddr|ieName|ieType|ieUnit',
              ]"
              :data="deviceList"
            />
          </div>
          <m-empty v-else :img="empty" hidden-text />
        </template>
        <template v-else-if="curTab2 === 'public'">
          <div class="select-bar">
            <a-select
              v-model:value="publicType"
              dropdown-class-name="device-selector-drop-down"
            >
              <a-select-option
                v-for="option in publicOptions"
                :key="option.type"
                :value="option.type"
              >
                {{ option.name }}
              </a-select-option>
            </a-select>
          </div>
          <div v-if="publicList.length > 0" class="wrapper">
            <template v-if="publicType === '倒粪'">
              <SubTabs
                :list="
                  publicList.map((_, i) => ({ name: `倒粪口${i + 1}`, key: i }))
                "
                @select="curSubtabKey = $event"
              />
              <m-form
                :template="[
                  'installAddr:地址|ownership:所有权',
                  'buildingArea:建筑面积>area|type:组织架构>structure',
                  'water:排水>water|servePersonNum:服务人数',
                  'stratTime:服务时间段|serveHouseholdNum:服务户数',
                  'trashNum:垃圾桶数|photo:照片#image',
                ]"
                :data="publicList[curSubtabKey]"
                label-width="1.2rem"
                :formatter="formatter"
              />
            </template>
            <div v-else-if="publicType === '垃圾'" class="box">
              <div v-for="item in publicList" :key="item.id">
                <div>
                  <p>{{ item.dutyPersonnel }} {{ item.phone }}</p>
                  <p>{{ item.addr }}</p>
                </div>
              </div>
            </div>
            <!-- <m-table
              v-if="publicType === '充电'"
              :template="[
                '序号|安装位置*2|名称*2|类型|维保单位*3',
                'index|ieAddr|ieName|ieType|ieUnit',
              ]"
              :data="publicList"
            /> -->
          </div>
          <m-empty v-else :img="empty" hidden-text />
        </template>
      </template>
      <template v-else>
        <template v-if="showPersonDetail">
          <SubTitle>基本信息</SubTitle>
          <div class="person-bar">
            <div class="photo"></div>
            <div class="back-btn" @click="showPersonDetail = false">返回</div>
          </div>
          <m-form
            :template="[
              'cnName:姓名>getName|sex:性别',
              'birthday:出生日期|roomNo:民族',
              'nationalityName:国籍|hometown:籍贯',
              'homtownAdmArea:户籍|certCode:证件号>convertIds',
              'educationName:学历|maritalStatus:婚姻状况',
            ]"
            :data="personDetail"
            :formatter="{ getName, convertIds }"
            label-width="1.2rem"
          />
          <SubTitle>标签信息</SubTitle>
        </template>
        <template v-else>
          <SubTitle>现居住人</SubTitle>
          <m-table
            :template="[
              '姓名|国籍/户籍|证件号|性别|婚姻状况|入住时间',
              'cnName>getName|nationalityName|certCode>convertIds|sex|maritalStatus|time',
            ]"
            selectable
            :data="roomInfo.personInfo"
            :formatter="{ getName, convertIds }"
            @select="selectPerson"
          />
          <SubTitle>历史居住人</SubTitle>
          <m-table
            :template="[
              '姓名|国籍/户籍|证件号|性别|婚姻状况|入住时间',
              'cnName>getName|nationalityName|certCode>convertIds|sex|maritalStatus|time',
            ]"
            selectable
            :data="roomInfo.personInfo"
            :formatter="{ getName, convertIds }"
            @select="selectPerson"
          />
        </template>
      </template>
    </m-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, computed, watch } from 'vue'
import Tabs, { TabsProp } from '../components/tabs.vue'
import SubTabs from '../components/sub-tabs.vue'
import SubTitle from '../components/sub-title.vue'
import CaseList from '../components/case-list.vue'
import { ajax, api } from '@/ajax'
import empty from '@/assets/images/empty.png'
import { convertName, convertIds } from '@/tools/index'

export default defineComponent({
  name: 'PopulationDrawer',
  components: { Tabs, SubTitle, CaseList, SubTabs },
  props: {
    communityInfo: {
      type: Object as PropType<{ [key: string]: any } | null>,
      default: () => {
        return {}
      },
    },
    propertyInfo: {
      type: Object as PropType<{ [key: string]: any } | null>,
      default: () => {
        return {}
      },
    },
    caseInfo: {
      type: Array as PropType<any[] | null>,
      default: () => {
        return []
      },
    },
    roomInfo: {
      type: Object as PropType<any[] | null>,
      default: () => {
        return {}
      },
    },
    buildingInfo: {
      type: Object as PropType<any[] | null>,
      default: () => {
        return {}
      },
    },
  },
  setup(props) {
    const curTab = ref('house')
    const tabs = ref<TabsProp[]>([
      {
        key: 'house',
        name: '房屋信息',
      },
      {
        key: 'person',
        name: '实住人',
      },
    ])
    const curTab2 = ref('community')
    const tabs2 = ref<TabsProp[]>([
      {
        key: 'community',
        name: '小区信息',
      },
      {
        key: 'room',
        name: '门牌户室',
      },
      {
        key: 'property',
        name: '物业信息',
      },
      {
        key: 'committee',
        name: '业委会',
      },
      {
        key: 'device',
        name: '设施设备',
      },
      {
        key: 'public',
        name: '公共设施',
      },
    ])
    const onSelect = (tab: string) => {
      curTab.value = tab
      if (tab === 'house') {
        curTab2.value = 'community'
      }
    }

    const houseData = computed(() => {
      const { communityInfo, buildingInfo, roomInfo } = props
      return { ...communityInfo, ...buildingInfo, ...roomInfo }
    })
    const communityData = computed(() => {
      const { communityInfo = {} } = props
      const keys = [
        { name: '北', key: 'stCspNorth' },
        { name: '南', key: 'stCspSouth' },
        { name: '西', key: 'getStCspWest' },
        { name: '东', key: 'stCspEast' },
      ]
      const range = keys.map((item) =>
        communityInfo && communityInfo[item.key]
          ? item.name + communityInfo[item.key]
          : null
      )

      return {
        ...communityInfo,
        range: range.filter((e) => e !== null).join('，'),
      }
    })

    const showPersonDetail = ref(false)
    const personDetail = ref<unknown>(null)
    const selectPerson = (person: any) => {
      personDetail.value = person
      showPersonDetail.value = true
    }
    const hasElev = (val: boolean | null) => {
      return val ? '有' : '无'
    }

    const showBuildingRoom = ref(false)
    const buildingRoomList = ref<any>([])
    const selectBuilding = async (data: any) => {
      const { content } = (
        await ajax.get({
          url: api.GET_ROOM,
          params: { pageSize: 100, addr_l: data.unitAddr },
        })
      ).data
      buildingRoomList.value = content
      showBuildingRoom.value = true
    }
    const getName = (_: unknown, data: any) => {
      return convertName(data.cnName) || data.enName
    }
    const deviceType = ref('大门')
    const deviceOptions = ref([
      { name: '大门', type: 'gate' },
      { name: '监控', type: 'monitor' },
      { name: '防盗门', type: 'security' },
      { name: '电梯', type: 'elevator' },
      { name: '消防泵', type: 'fire' },
    ])
    const deviceList = computed(() => {
      const { deviceList: list } = props.communityInfo as any
      if (!list || list.length === 0) return []
      return list
        .filter((e: any) => e.ieClassify.includes(deviceType.value))
        .map((e: any, i: number) => ({ index: i + 1, ...e }))
    })

    const publicList = ref([])
    const publicType = ref('倒粪')
    const publicOptions = ref([
      { name: '倒粪口', type: '倒粪' },
      { name: '垃圾箱', type: '垃圾' },
      { name: '菜场菜店', type: '菜' },
      { name: '药店药房', type: '药' },
      { name: '便利店', type: '便利' },
      { name: '充电桩', type: '充电' },
    ])
    const curSubtabKey = ref('0')
    watch(
      () => publicType.value,
      async (type) => {
        curSubtabKey.value = '0'
        const markets = ['菜', '药', '便利']
        if (markets.includes(type)) {
          const { content } = (
            await ajax.get({
              url: api.GET_MARKETS,
              params: {
                pageSize: 1000,
                labelName_l: type,
              },
            })
          ).data
          publicList.value = content || []
        } else if (type === '倒粪') {
          const { content } = (
            await ajax.get({
              url: api.GET_DUNGS,
              params: {
                pageSize: 1000,
                sectIds: (communityData.value as any).sectId,
              },
            })
          ).data
          publicList.value = content || []
        } else if (type === '垃圾') {
          const { content } = (
            await ajax.get({
              url: api.GET_BINS,
              params: {
                pageSize: 1000,
                sectId: (communityData.value as any).sectId,
              },
            })
          ).data
          publicList.value = content || []
        } else {
          publicList.value = []
        }
      },
      { immediate: true }
    )

    const formatter = {
      area(val: unknown) {
        return val ? `${val}㎡` : '无'
      },
      structure(val: string, data: any) {
        return `${val}(${+data.havePourDung === 1 ? '有' : '无'}倒粪口/${
          +data.haveGarbageRoom === 1 ? '有' : '无'
        }垃圾箱房/${+data.haveUrinal === 1 ? '有' : '无'}小便池)`
      },
      water(_: unknown, data: any) {
        return `${+data.haveAboveWater === 1 ? '有' : '无'}上水/${
          +data.haveBelowWater === 1 ? '有' : '无'
        }下水`
      },
    }
    watch(
      () => curTab.value,
      () => {
        // 重置选项
        deviceType.value = '大门'
        publicType.value = '倒粪'
        curSubtabKey.value = '0'
      }
    )
    return {
      curTab,
      tabs,
      curTab2,
      tabs2,
      onSelect,
      houseData,
      communityData,
      selectPerson,
      personDetail,
      showPersonDetail,
      hasElev,
      showBuildingRoom,
      selectBuilding,
      buildingRoomList,
      getName,
      convertIds,
      deviceType,
      deviceOptions,
      deviceList,
      publicList,
      publicType,
      publicOptions,
      curSubtabKey,
      formatter,
      empty,
    }
  },
})
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'

.population-drawer
  display flex
  justify-content space-between
  >div
    width 35%
    &:last-child
      width 64%
  .case-wrap
    height 85vh
    overflow hidden
.person-bar
  display flex
  justify-content space-between
  .back-btn
    padding 0 .06rem
    background $primary-color
    cursor pointer
    border-radius .02rem
    margin .04rem 0
    font-size .09rem
    &:hover
      background $secondary-color
.building-list
  max-height 40vh
  overflow-y auto
  >div
    display inline-block
    width 24%
    margin .06rem 0 0 .06rem
    background linear-gradient(to right, rgba(124,139,154,.4), rgba(70,83,97,.4))
    box-shadow 0 0 .04rem 0 rgba(45,51,66,.5)
    border-radius .03rem
    box-sizing border-box
    padding .04rem .08rem
    cursor pointer
    border .01rem solid transparent
    transition all .1s ease
    &:hover
      background linear-gradient(to right, rgba(124,139,154,.2), rgba(70,83,97,.2))
      border .01rem solid rgba(130,207,255,.3)
    p
      color #ccc
      font-size .09rem
      &.title
        font-weight bold
        font-size .11rem
        color #fff
      &.line
        border-bottom .01rem dotted rgba(91,213,255,.4)
        margin .04rem 0
.room-table
  max-height 38vh
  overflow-y auto
.wrapper
  max-height 35vh
  overflow-y auto
  .box
    $full()
    display flex
    flex-wrap wrap
    >div
      width 23.4%
      height 1rem
      margin-right .1rem
      margin-bottom @margin-right
      background url('@/assets/images/default.jpeg') 100% / 100% 100% no-repeat
      position relative
      >div
        background rgba(0,0,0,0.6)
        color #fff
        position absolute
        left 0
        right 0
        bottom 0
        padding .02rem .05rem
</style>

<style lang="stylus">
$bg = rgba(13, 39, 76, .7)
$size = .1rem
$height = .2rem

.select-bar
  margin .04rem 0
  .ant-select
    background $bg
    min-width .9rem
    .ant-select-selector
      min-width .9rem
      border-top none
      border-left none
      border-right none
      height $height
      .ant-select-selection-item
        font-size $size
        line-height $height
        text-align center
        color #fff
        font-weight bold
    .ant-select-arrow
      font-size $size * 0.8
.device-selector-drop-down
  &.ant-select-dropdown
    background $bg
    font-size $size
    .ant-select-item
      font-size $size
      line-height $height / 2
    .ant-select-item-option-selected:not(.ant-select-item-option-disabled)
      background $bg
      font-size $size
</style>
