<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="住户姓名">
              <j-input placeholder="请输入住户姓名" v-model="queryParam.residentName"></j-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:180px" 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="width:60%;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="residentName" slot-scope="text, record">
              <span>{{`${record.residentName},${record.residentPhone}`}}</span>
            </span>
            <span slot="buildingName" slot-scope="text, record">
              <span>{{record.buildingName}}{{record.unitName}}{{record.roomName}}</span>
            </span>
            <span slot="label" slot-scope="text, record">
              <!-- <span>{{record.label | filterLabel}}</span> -->
              <div>
                <a-tag color="blue" v-if="record.relationShip === 'self'">业主</a-tag>
                <a-tag color="red" v-if="record.labelCommitteeDesc">{{record.labelCommitteeDesc}}</a-tag>
                <a-tag color="orange" v-if="record.labelDestituteDesc">{{record.labelDestituteDesc}}</a-tag>
              </div>
            </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 v-if="!!record.labelCommitteeCode">
                      <a @click="handlePerssion(record.id)">授权</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a href="javascript:;" @click="onHandleSetting(record.id, '3')">详情</a>
                    </a-menu-item>
                    <a-menu-item v-if="!record.labelCommitteeCode">
                      <a href="javascript:;" @click="onHandleSetting(record.id, '1')">设置业委会</a>
                    </a-menu-item>
                    <a-menu-item v-if="record.destituteAuditStatus !== 'auditPass' && record.destituteAuditStatus !== 'waitAudit'">
                      <a href="javascript:;" @click="onHandleSetting(record.id, '2')">{{record.destituteAuditStatus === 'refuse' ? '修改特困人员' : '设置特困人员'}}</a>
                    </a-menu-item>
                    <a-menu-item v-if="!!record.labelCommitteeCode">
                      <a-popconfirm title="确定撤销业委会吗?" @confirm="()=> onDeleteIndustry(record.id)" placement="topLeft">
                        <a>撤销业委会</a>
                      </a-popconfirm>
                    </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>
    <!-- 右侧的角色权限配置 -->
    <user-role-modal ref="modalUserRole"></user-role-modal>
  </a-card>
</template>

<script>
import { getBuildingListApi, getUnitListApi, getRoomListApi, geQueryByOwnerIdApi, geCommunityDeleteApi } from '@/api/api'
import { downFile } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import NoticeModal from './modules/NoticeModal'
import UserRoleModal from './modules/UserRoleModal'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { RELATION_SHIP, filterDictTextByStatic, INDUSTRY_JOB, OWNER_LEBEL } from '@/assets/static.js'
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
const labelAllList = [{label: '业主', value: 'owner'}].concat(INDUSTRY_JOB, OWNER_LEBEL)
const columns = [
  {
    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: 'destituteAuditStatus',
    key: 'destituteAuditStatus',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByCache('auditStatus', text)
    }
  },
  {
    title: '标签',
    dataIndex: 'label',
    key: 'label',
    align: 'center',
    scopedSlots: { customRender: 'label' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
    fixed: 'right'
  },
]

export default {
  name: 'PermissionListAsync',
  mixins: [JeecgListMixin],
  components: {
    NoticeModal,
    UserRoleModal
  },
  data() {
    return {
      treeDataFlag: true,
      useOptions: [],
      certificationOptions: [
        {label: '待审核', value: 'waitAudit'},
        {label: '审核通过', value: 'auditPass'},
        {label: '已驳回', value: 'refuse'}
      ],
      // 表头
      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: [],
    }
  },
  filters: {
    filterLabel(value) {
      if(value) {
        let labelList = value.split(',')
        let valueList = []
        labelList.forEach(item=> {
          let findValue = labelAllList.find(row=>row.value === item)
          valueList.push(findValue.label)
        })
        return valueList.join(',')
      } else {
        return ''
      }
    }
  },
  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
      })
    },
    onHandleSetting(id, type) {
      this.$router.push({
        path: `/information/owner-setting?id=${id}&type=${type}`
      })
    },
    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 + '.xlsx')
        } 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 + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handlePerssion(ownerId) {
      geQueryByOwnerIdApi({ownerId}).then(res=> {
        let roleId = res.result.roleId
        this.$refs.modalUserRole.show(roleId)
      })
    },
    onDeleteIndustry(id) {
      geCommunityDeleteApi({id}).then(res=> {
        this.$message.success(res.message);
        this.loadData()
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.auditPass {
  color: #67C23A;
}
.refuse {
  color: #F56C6C;
}
</style>