<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="业主姓名">
              <a-input placeholder="请输入业主姓名" v-model="queryParam.ownerName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-model-item label="房屋用途">
              <a-select style="width: 100%" v-model="queryParam.useTo" placeholder="请选择房屋用途">
                <a-select-option v-for="item in useOptions" :key="item.value"
                  :value="item.value">{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-model-item label="审核状态">
              <a-select style="width: 100%" v-model="queryParam.auditStatus" placeholder="请选择审核状态">
                <a-select-option v-for="item in certificationOptions" :key="item.value"
                  :value="item.value">{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="searchQuery">查询</a-button>
              <a-button style="margin-left: 8px" @click="onSearchReset">重置</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>

    <div style="display:flex">
      <div style="flex: none;width:200px" v-if="treeData.length">
        <a-tree v-if="treeDataFlag" :load-data="onLoadData" :tree-data="treeData" @select="onClickTree"
          style="max-height: 600px;overflow-y:auto" />
      </div>

      <div style="flex:auto;padding-left:10px">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          <a-button icon="download" @click="downloadExportXls()">模板下载</a-button>
          <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
            :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload>
          <a-button type="primary" icon="download" @click="handleExportXls('业主管理')">导出</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
          </a-dropdown>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{
            selectedRowKeys.length }}</a>项&nbsp;&nbsp;
            <a style="margin-left: 24px" v-if="selectedRowKeys.length > 0" @click="onClearSelected">清空</a>
          </div>

          <a-table ref="table" size="middle" :scroll="{x:true}" bordered rowKey="id" :columns="columns"
            :dataSource="dataSource" :pagination="ipagination" :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" class="j-table-force-nowrap"
            @change="handleTableChange">
            <span slot="ownerName" slot-scope="text, record">
              <span>{{record.ownerName}}，{{record.ownerPhone}}</span>
            </span>
            <span slot="residentName" slot-scope="text, record">
              <span>{{record.relationShip === '1' ? record.ownerName : `${record.residentName}，${record.residentPhone}`}}</span>
            </span>
            <span slot="buildingName" slot-scope="text, record">
              <span>{{record.buildingName}}{{record.unitName}}{{record.roomName}}</span>
            </span>
            <span slot="action" slot-scope="text, record">
              <template v-if="record.auditStatus === 'waitAudit'">
                <a @click="onRoutetAdd(record.id)">审核</a>
              </template>
              <template v-else-if="record.auditStatus === 'refuse'">
                <a @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" placement="topLeft">
                  <a>删除</a>
                </a-popconfirm>
              </template>
              <template v-else>
                <a @click="handleEdit(record)">编辑</a>

                <a-divider type="vertical" />
                <a-dropdown>
                  <a class="ant-dropdown-link">
                    更多 <a-icon type="down" />
                  </a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a href="javascript:;" @click="handleDetail(record)">详情</a>
                    </a-menu-item>

                    <a-menu-item>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" placement="topLeft">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </span>
          </a-table>

        </div>
        <!-- table区域-end -->
      </div>
    </div>

    <notice-modal ref="modalForm" @ok="modalFormOk"></notice-modal>
  </a-card>
</template>

<script>
import { getBuildingListApi, getUnitListApi, getRoomListApi, downloadOwnerTemplate } from '@/api/api'
import { downFile } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import NoticeModal from './modules/NoticeModal'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { RELATION_SHIP, filterDictTextByStatic } from '@/assets/static.js'
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'

const columns = [
  {
    title: '业主',
    dataIndex: 'ownerName',
    scopedSlots: { customRender: 'ownerName' },
    key: 'ownerName',
    align: 'center',
  },
  {
    title: '与业主关系',
    dataIndex: 'relationShip',
    key: 'relationShip',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(RELATION_SHIP, text)
    },
  },
  {
    title: '住户',
    dataIndex: 'residentName',
    key: 'residentName',
    scopedSlots: { customRender: 'residentName' },
    align: 'center',
  },
  {
    title: '房屋用途',
    dataIndex: 'useTo',
    key: 'useTo',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByCache('house_purpose', text)
    },
  },
  {
    title: '房屋编号',
    dataIndex: 'buildingName',
    key: 'buildingName',
    scopedSlots: { customRender: 'buildingName' },
    align: 'center',
  },
  {
    title: '建筑面积（m2）',
    dataIndex: 'floorSpace',
    key: 'floorSpace',
    align: 'center',
  },
  {
    title: '是否认证',
    dataIndex: 'isAuth',
    key: 'isAuth',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByCache('yn', text)
    },
  },
  {
    title: '审核状态',
    dataIndex: 'auditStatus',
    key: 'auditStatus',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByCache('auditStatus', text)
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
  },
]

export default {
  name: 'PermissionListAsync',
  mixins: [JeecgListMixin],
  components: {
    NoticeModal,
  },
  data() {
    return {
      treeDataFlag: true,
      useOptions: [],
      certificationOptions: [],
      // 表头
      columns: columns,
      url: {
        list: '/property-community/info/communityOwner/list',
        delete: '/property-community/info/communityOwner/delete',
        deleteBatch: '/property-community/info/communityOwner/deleteBatch',
        exportXlsUrl: '/property-community/info/communityOwner/exportXls',
        importExcelUrl: 'property-community/info/communityOwner/importExcel',
        downloadExcelUrl: 'property-community/info/communityOwner/downloadOwnerTemplate',
      },

      treeData: [],
    }
  },
  created() {
    this.getBuildingList()
    this.initDictData()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictData() {
      //优先从缓存中读取字典配置
      if (getDictItemsFromCache('owner_certification_status')) {
        this.useOptions = getDictItemsFromCache('house_purpose')
        this.certificationOptions = getDictItemsFromCache('owner_certification_status')
        return
      }
      // //根据字典Code, 初始化字典数组
      ajaxGetDictItems('house_purpose', null).then((res) => {
        if (res.success) {
          this.useOptions = res.result
        }
      })
      ajaxGetDictItems('owner_certification_status', null).then((res) => {
        if (res.success) {
          this.certificationOptions = res.result
        }
      })
    },
    async getBuildingList() {
      let { result } = await getBuildingListApi()
      this.treeData = result.map((item) => {
        return {
          title: item.buildingName,
          key: item.id,
        }
      })
    },
    onClickTree(value, option) {
      let level = option.node.pos.split('-').length
      if (level === 2) {
        this.queryParam['buildingId'] = value[0]
        this.queryParam['unitId'] = undefined
        this.queryParam['roomId'] = undefined
      }
      if (level === 3) {
        this.queryParam['buildingId'] = undefined
        this.queryParam['unitId'] = value[0]
        this.queryParam['roomId'] = undefined
      }
      if (level === 4) {
        this.queryParam['buildingId'] = undefined
        this.queryParam['unitId'] = undefined
        this.queryParam['roomId'] = value[0]
      }
      this.searchQuery()
    },
    onSearchReset() {
      this.treeDataFlag = false
      setTimeout(() => {
        this.treeDataFlag = true
      }, 30)
      this.searchReset()
    },
    onLoadData(treeNode) {
      return new Promise(async (resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        if (treeNode.pos.split('-').length === 2) {
          let { result } = await getUnitListApi({ id: treeNode.eventKey })
          treeNode.dataRef.children = result.map((item) => {
            return {
              title: item.unitName,
              key: item.id,
            }
          })
          this.treeData = [...this.treeData]
          resolve()
        } else {
          let { result } = await getRoomListApi({ id: treeNode.eventKey })
          treeNode.dataRef.children = result.map((item) => {
            return {
              title: item.roomNum,
              key: item.id,
              isLeaf: true,
            }
          })
          this.treeData = [...this.treeData]
          resolve()
        }
      })
    },
    onRoutetAdd(id) {
      this.$router.push({
        path: '/information/owner-add?id=' + id,
      })
    },
    downloadExportXls() {
      let fileName ='业主管理模板';
      downFile(this.url.downloadExcelUrl, '').then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>