<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>

          <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="searchReset">重置</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>

    <div style="display:flex">
      <div style="flex: none;width:200px">
        <a-tree :load-data="onLoadData" :tree-data="treeData" @select="onClickTree" />
      </div>

      <div style="flex:auto;width:80%;">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="onMeterReading" 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>
          <div style="float: right; color: #f00;">
            <span style="margin-right: 20px;">已缴费金额 (元):{{ statistical.paidMoney || 0 }}</span>
            <span>待缴费金额 (元):{{ statistical.unPaidMoney || 0 }}</span>
          </div>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="onBatchCallpay"><a-icon type="message" />催缴</a-menu-item>
              <a-menu-item key="2" @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,
              getCheckboxProps: onCheckboxProps
            }" class="j-table-force-nowrap" @change="handleTableChange">
            <span slot="residentPhone" slot-scope="text, record">
              <span>{{record.residentName}},{{record.residentPhone}}</span>
            </span>
            <span slot="roomId" slot-scope="text, record">
              <span>{{record.buildingName}}{{record.unitName}}{{record.roomName}}</span>
            </span>
            <span slot="action" slot-scope="text, record">
              <a @click="onDetail(record.id)">查看</a>
              <template v-if="record.paymentStatus === 'unPaid'">
                <a-divider type="vertical" />
                <a @click="onCallPay(record.id)">催缴</a>
                <a-divider type="vertical" />
                <a @click="handleDelete(record.id)">删除</a>
              </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, callPayMentApi,getTotalMoneyApi } from '@/api/api'
import { downFile } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import NoticeModal from './modules/NoticeModal'
import { PAYMENT_STATUS, RELATION_SHIP, filterDictTextByStatic } from '@/assets/static.js'

const columns = [
  {
    title: '收费类型',
    dataIndex: 'chargeTypeName',
    key: 'chargeTypeName',
    align: 'center',
  },
  {
    title: '收费项目',
    dataIndex: 'chargeItem',
    key: 'chargeItem',
    align: 'center',
  },
  {
    title: '与业主关系',
    dataIndex: 'relationShip',
    key: 'relationShip',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(RELATION_SHIP, text)
    },
  },
  {
    title: '住户',
    dataIndex: 'residentPhone',
    key: 'residentPhone',
    scopedSlots: { customRender: 'residentPhone' },
    align: 'center',
    ellipsis: true
  },
  {
    title: '房屋编号',
    dataIndex: 'roomId',
    scopedSlots: { customRender: 'roomId' },
    key: 'roomId',
    align: 'center',
  },
  {
    title: '金额(元)',
    dataIndex: 'totalAmount',
    key: 'totalAmount',
    align: 'center',
  },
  {
    title: '本期读表时间',
    dataIndex: 'meterReadingTime',
    key: 'meterReadingTime',
    align: 'center',
  },
  {
    title: '缴费状态',
    dataIndex: 'paymentStatus',
    key: 'paymentStatus',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(PAYMENT_STATUS, text)
    },
  },
  {
    title: '缴费单号',
    dataIndex: 'paymentNum',
    key: 'paymentNum',
    align: 'center',
  },
  {
    title: '缴费日期',
    dataIndex: 'paymentTime',
    key: 'paymentTime',
    align: 'center',
  },
  {
    title: '创建日期',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
    fixed: 'right',
  },
]

export default {
  name: 'PermissionListAsync',
  mixins: [JeecgListMixin],
  components: { NoticeModal },
  data() {
    return {
      // 表头
      columns: columns,
      url: {
        list: '/property-community/payment/communityPayment/list',
        delete: '/property-community/payment/communityPayment/delete',
        deleteBatch: '/property-community/payment/communityPayment/deleteBatch',
        exportXlsUrl: '/property-community/payment/communityPayment/exportXls',
        importExcelUrl: 'property-community/payment/communityPayment/importExcel',
        downloadExcelUrl: '/property-community/payment/communityPayment/downloadPaymentTemplate',
      },
      treeData: [],
      statistical: {},
    }
  },
  created() {
    this.getBuildingList()
    this.getTotalMoney()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    onCheckboxProps(record) {
      let props = {
        disabled: record.paymentStatus === 'paid',
        name: record.chargeTypeName,
      }
      return props
    },
    async getBuildingList() {
      let { result } = await getBuildingListApi()
      this.treeData = result.map((item) => {
        return {
          title: item.buildingName,
          key: item.id,
        }
      })
    },
    async getTotalMoney() {
      let { result } = await getTotalMoneyApi({ type: 'payment' })
      this.statistical = result
    },
    onClickTree(value, option) {
      console.log(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()
    },
    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()
        }
      })
    },
    onMeterReading() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '抄表'
      this.$refs.modalForm.disableSubmit = false
    },
    onBatchCallpay() {
      // console.log(this.selectionRows)
      let chooseIds = this.selectedRowKeys.join(',')
      this.onCallPay(chooseIds)
    },
    onDetail(id) {
      this.$router.push({
        path: '/property/living-detail?id=' + id,
      })
    },
    onCallPay(chooseIds) {
      let that = this
      this.$confirm({
        title: '催缴账单',
        content: '是否催缴当前选择的账单发送给对应业主?',
        onOk: function () {
          that.loading = true
          callPayMentApi({ chooseIds })
            .then((res) => {
              if (res.success) {
                //重新计算分页问题
                that.$message.success(res.message)
                // that.searchQuery();
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
      })
    },
    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>