<template>
  <a-spin :spinning="confirmLoading">
    <div class="title-top">
      <h3>{{title}}</h3>
      <div class="button">
        <a-button @click="onCancel">返回</a-button>
        <a-button type="danger" @click="onExamine(2)" v-if="pageType == '2'">审核驳回</a-button>
        <a-button type="primary" @click="onExamine(1)" v-if="pageType == '2'">审核通过</a-button>
        <a-button type="primary" @click="onExamine(3)" v-if="pageType == '3'">确认</a-button>
      </div>
    </div>

    <a-card title="请选择对账" v-if="pageType === '3'">
      <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.chargeTypeName" placeholder="请选择收费类型">
                  <a-select-option v-for="item in chargeTypeOptions" :key="item.typeCode" :value="item.typeName">{{item.typeName}}</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="searchReset">重置</a-button>
              </a-col>
            </span>
          </a-row>
        </a-form>
      </div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        已选择 <a style="font-weight: 600"> {{ selectionRows.length }}</a>个缴费单,共计<span style="color:red">{{totalMoney}}</span>元
        <a style="margin-left: 24px" v-if="selectedRowKeys.length > 0" @click="onClearSelected">清空</a>
      </div>
      <a-row>
        <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>
        </a-table>
      </a-row>
    </a-card>

    <j-form-container :disabled="pageType !== '3'">
      <a-form-model ref="form" :model="model" slot="detail">
        <a-card title="对账信息" v-if="pageType !== '3'">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="对账单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="id">
                <a-input v-model="model.id" placeholder="请输入对账单号"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="对账开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reconciliationBeginDate">
                <a-input v-model="model.reconciliationBeginDate" placeholder="请输入对账开始时间"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="对账结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reconciliationEndDate">
                <a-input v-model="model.reconciliationEndDate" placeholder="请输入对账结束时间"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="操作人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
                <a-input-number v-model="model.createBy" :min="1" placeholder="请输入操作人" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="操作日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                <a-input v-model="model.createTime" placeholder="请输入操作日期"></a-input>
              </a-form-model-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-model-item label="小区审核状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="communityAuditStatus">
                <a-select v-model="model.communityAuditStatus" style="width:100%">
                  <a-select-option v-for="item in communityAuditStatusList" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col> -->
          </a-row>
        </a-card>
      </a-form-model>
    </j-form-container>
    <a-card title="对账明细" v-if="pageType !== '3'">
      <p>已添加{{dataSource.length}}个缴费单,共计<span style="color:red">{{model.reconciliationAmount}}</span>元</p>
      <a-row>
        <div>
          <a-table ref="table" size="middle" :scroll="{ x: true}" bordered rowKey="id" :columns="columns"
            :dataSource="dataSource" :pagination="ipagination" :loading="loading"  class="j-table-force-nowrap">
            <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>
          </a-table>
        </div>
      </a-row>
    </a-card>
    <a-card title="审核记录" v-if="pageType === '1'">
      <a-row>
        <div>
          <a-table ref="table" size="middle" :scroll="{ x: 600}" bordered rowKey="id" :columns="recordColumns"
            :dataSource="recordList"  class="j-table-force-nowrap">
          </a-table>
        </div>
      </a-row>
    </a-card>
    <a-card title="审核说明" v-if="pageType === '2'">
      <a-textarea placeholder="请输入审核说明" v-model="auditDescription" />
    </a-card>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { addCommunityAccountPageApi, getCommunityRecordListApi, getDetailReconciliationApi, getAccountListByIdApi, communityAuditAccountPageApi, getChargeListApi } from '@/api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { PAYMENT_STATUS, RELATION_SHIP, filterDictTextByStatic, RECONCILIATION_STATUS } from '@/assets/static.js'

const columns = [
  {
    title: '收费类型',
    dataIndex: 'chargeTypeName',
    key: 'chargeTypeName',
    width: 120,
    align: 'center',
  },
  {
    title: '收费项目',
    dataIndex: 'chargeItem',
    key: 'chargeItem',
    width: 220,
    align: 'center',
  },
  {
    title: '与业主关系',
    dataIndex: 'relationShip',
    key: 'relationShip',
    width: 120,
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(RELATION_SHIP, text)
    },
  },
  {
    title: '住户',
    dataIndex: 'residentPhone',
    key: 'residentPhone',
    width: 160,
    scopedSlots: { customRender: 'residentPhone' },
    align: 'center',
  },
  {
    title: '房屋编号',
    dataIndex: 'roomId',
    scopedSlots: { customRender: 'roomId' },
    key: 'roomId',
    width: 140,
    align: 'center',
  },
  {
    title: '金额(元)',
    dataIndex: 'totalAmount',
    key: 'totalAmount',
    width: 120,
    align: 'center',
  },
  {
    title: '本期读表时间',
    dataIndex: 'meterReadingTime',
    key: 'meterReadingTime',
    width: 150,
    align: 'center',
  },
  // {
  //   title: '缴费状态',
  //   dataIndex: 'paymentStatus',
  //   key: 'paymentStatus',
  //   width: 120,
  //   align: 'center',
  //   customRender: function (text) {
  //     return filterDictTextByStatic(PAYMENT_STATUS, text)
  //   },
  // },
  {
    title: '缴费单号',
    dataIndex: 'paymentNum',
    key: 'paymentNum',
    width: 120,
    align: 'center',
  },
  {
    title: '缴费日期',
    dataIndex: 'paymentTime',
    key: 'paymentTime',
    width: 150,
    align: 'center',
  },
  {
    title: '创建日期',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150,
    align: 'center',
  }
]
const recordColumns = [
  {
    title: '审核平台',
    dataIndex: 'platformName',
    key: 'platformName',
    width: 100,
    align: 'center',
  },
  {
    title: '审核状态',
    dataIndex: 'auditStatus',
    key: 'auditStatus',
    width: 100,
    align: 'center',
    // customRender: (text)=> {
    //   return filterDictTextByStatic(RECONCILIATION_STATUS, text)
    // },
  },
  {
    title: '审核说明',
    dataIndex: 'refuseDesc',
    key: 'refuseDesc',
    width: 200,
    align: 'center',
    ellipsis: true
  },
  {
    title: '审核人',
    dataIndex: 'createBy',
    key: 'createBy',
    width: 100,
    align: 'center'
  },
  {
    title: '审核时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 100,
    align: 'center',
  }
]
export default {
  name: 'PropertySettledForm',
  inject: ['closeCurrent'],
  mixins: [JeecgListMixin],
  data() {
    return {
      communityAuditStatusList: RECONCILIATION_STATUS,
      title: '',
      pageType: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      url: {
        list: '/property-community/property/communityReconciliation/communityAccountPage'
      },
      chargeTypeOptions: [],
      auditDescription: '',
      columns: columns,
      disableMixinCreated: true,
      recordColumns: recordColumns,
      recordList: []
    }
  },
  computed: {
    totalMoney() {
      return this.selectionRows.reduce((prev,cur,index,arr)=> {
        return parseFloat((prev + cur.totalAmount).toFixed(1))
      }, 0)
    }
  },
  methods: {
    onCheckboxProps(record) {
      let props = {
        disabled: record.paymentStatus === 'paid',
        name: record.chargeTypeName,
      }
      return props
    },
    async getCommunityReconciliation() {
      let formModel = await getDetailReconciliationApi({
        id: this.$route.query.id
      })
      this.model = {...formModel.result}
      let formList = await getAccountListByIdApi({
        reconciliationId: this.$route.query.id
      })
      this.dataSource = [...formList.result.records]
      let record = await getCommunityRecordListApi({
        dataId: this.$route.query.id,
        auditType: 'reconciliation'
      })
      this.recordList = [...record.result]
    },
    onCancel() {
      this.closeCurrent()
    },
    contactPhoneChange(e) {
      if(!this.model.adminLoginName) {
        this.model.adminLoginName = e.target.value
      }
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.model.registAdress = [record.provinceCode, record.cityCode, record.countyCode]
      this.visible = true
    },
    onExamine(type) {
      if(type === 3) {
        this.confirmLoading = true
        addCommunityAccountPageApi({
          // paymentIds: this.selectionRows.map(item=>item.id).join(',')
          payments: this.selectionRows
        }).then(res=> {
          this.confirmLoading = false
          this.$message.success(res.message)
          this.closeCurrent()
        })
      } else {
        this.confirmLoading = true
        communityAuditAccountPageApi({
          auditStatus: type === 1 ? 'auditPass' : 'refuse',
          id: this.$route.query.id,
          refuseDesc: this.auditDescription
        }).then(res=> {
          this.confirmLoading = false
          this.$message.success(`${type === 1 ? '审核' : '驳回'}成功!`)
          this.closeCurrent()
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          //this.model.registAdress = undefined
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                this.closeCurrent()
              } else {
                that.$message.success(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    async getChargeList() {
      let {result} = await getChargeListApi()
      this.chargeTypeOptions = result
    }
  },
  mounted() {
    //备份model原始值
    //this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.pageType = this.$route.query.type
    if (this.$route.query.type == '1') {
      this.title = '详情'
      this.getCommunityReconciliation()
    } else if (this.$route.query.type == '2') {
      this.title = '审核'
      this.getCommunityReconciliation()
    } else if (this.$route.query.type == '3') {
      this.title = '新增对账'
      this.loadData()
      this.getChargeList()
    }
  }
}
</script>
<style lang="less" scoped>
.title-top {
  background: #fff;
  padding: 0 25px;
  line-height: 50px;
  height: 50px;
  margin-bottom: 5px;
  h3 {
    font-weight: bold;
    display: inline-block;
  }
  .button {
    float: right;
    .ant-btn {
      margin-left: 15px;
    }
  }
}
</style>
<style>
.area-select {
  width: 100% !important;
}
</style>