<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('4')" v-if="pageType == '2'">审核驳回</a-button>
        <a-button type="primary" @click="onExamine('3')" v-if="pageType == '2'">审核通过</a-button>
        <!-- <a-button type="primary" @click="onSettlement()" 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 v-else :disabled="true">
      <a-form-model ref="form" :model="model" slot="detail">
        <a-card title="基本信息">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="结算单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="balanceNum">
                <a-input v-model="model.balanceNum" placeholder="请输入结算单号"></a-input>
              </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="createBy">
                <a-input v-model="model.createBy" placeholder="请输入提交人"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="结算金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="balanceMoney">
                <a-input-number v-model="model.balanceMoney" placeholder="请输入结算金额" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="结算方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="balanceWay">
                <a-input v-model="model.balanceWay" placeholder="请输入结算方式"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="对账信息">
          <a-row>
            <div>
              <a-table ref="table" size="middle" :scroll="{x:true}" bordered rowKey="id" :columns="columns"
                :dataSource="dataSource" :pagination="false" class="j-table-force-nowrap">
              </a-table>
            </div>
          </a-row>
        </a-card>
        <a-card title="操作信息">
          <a-row>
            <div>
              <a-table ref="table" size="middle" :scroll="{x:true}" bordered rowKey="id" :columns="handleColumns"
                :dataSource="handleDataSource" :pagination="false" class="j-table-force-nowrap">
                <span slot="balanceStatus">已付款</span>
              </a-table>
            </div>
          </a-row>
        </a-card>
      </a-form-model>
    </j-form-container>

    <a-modal v-model="remarksVisible" :title="`${remarksModel.balanceStatus === '3' ? '通过' : '驳回'}说明`" @ok="submitHandleOk">
      <a-form-model ref="form" :model="remarksModel">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="{ xs: { span: 24 },sm: { span: 3 } }" :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }" prop="remarks">
              <a-textarea placeholder="请输入备注" v-model="remarksModel.remarks" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </a-spin>
</template>

<script>
import { getshareBalanceApi, auditshareBalanceApi } from '@/api/api'
import { httpAction, getAction } from '@/api/manage'
import { filterDictTextByStatic, FENLICENTRAL_AUDIT_STATUS, BALANCE_STATUS, PAY_WAY } from '@/assets/static.js'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

const columns = [
  {
    title: '订单编号',
    dataIndex: 'orderNum',
    key: 'orderNum',
    align: 'center',
  },
  {
    title: '提交时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '用户账号',
    dataIndex: 'buyerName',
    key: 'buyerName',
    align: 'center',
  },
  {
    title: '订单金额',
    dataIndex: 'totalMoney',
    key: 'totalMoney',
    align: 'center',
  },
  {
    title: '支付方式',
    dataIndex: 'payWay',
    key: 'payWay',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(PAY_WAY, text)
    }
  },
  {
    title: '订单来源',
    dataIndex: 'orderSource',
    key: 'orderSource',
    align: 'center',
    customRender: function (text) {
      return '小程序'
    },
  },
  {
    title: '订单状态',
    dataIndex: 'reconciliationStatus',
    key: 'reconciliationStatus',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(FENLICENTRAL_AUDIT_STATUS, text)
    }
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks',
    align: 'center',
  },
  {
    title: '所属平台',
    dataIndex: 'propertyName',
    key: 'propertyName',
  },
  {
    title: '所属小区',
    dataIndex: 'communityName',
    key: 'communityName',
  },
]
const handleColumns = [
  {
    title: '操作者',
    dataIndex: 'createBy',
    key: 'createBy',
    align: 'center',
  },
  {
    title: '操作时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '订单状态',
    dataIndex: 'reconciliationStatus',
    key: 'reconciliationStatus',
    align: 'center',
    customRender: function (text) {
      return filterDictTextByStatic(BALANCE_STATUS, text)
    }
  },
  {
    title: '付款状态',
    dataIndex: 'balanceStatus',
    key: 'balanceStatus',
    align: 'center',
    scopedSlots: { customRender: 'balanceStatus' }
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks',
    align: 'center',
  }
]
export default {
  name: 'PropertySettledForm',
  inject: ['closeCurrent'],
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '',
      pageType: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      url: {
        add: '/property-central/property/propertySettled/add',
        list: '/property-central/partners/shareBenefit/listBalance?platformType=central'
      },
      disableMixinCreated: true,
      columns: columns,
      handleColumns: handleColumns,
      handleDataSource: [],

      remarksVisible: false,
      remarksModel: {
        remarks: '',
        balanceStatus: ''
      }
    }
  },
  computed: {
    totalMoney() {
      return this.selectionRows.reduce((prev,cur,index,arr)=> {
        return parseFloat((prev + cur.totalMoney).toFixed(2))
      }, 0)
    }
  },
  methods: {
    onCheckboxProps(record) {
      let props = {
        disabled: record.paymentStatus === 'paid',
        name: record.chargeTypeName,
      }
      return props
    },
    async getPageDetail() {
      let { result } = await getshareBalanceApi({ id: this.$route.query.id })
      this.edit(result)
    },
    onCancel() {
      this.closeCurrent()
    },
    edit(record) {
      this.model = Object.assign({}, record.shareBalance)
      this.dataSource = [...record.shareBenefitsList]
      this.handleDataSource = [...record.list]
    },
    onExamine(status) {
      this.remarksModel.balanceStatus = status
      this.remarksVisible = true
    },
    submitHandleOk() {
      auditshareBalanceApi({
        id: this.$route.query.id,
        ...this.remarksModel
      }).then((res) => {
        this.$message.success(`${this.remarksModel.balanceStatus === '3' ? '审核通过' : '审核驳回'}成功`)
        this.closeCurrent()
      })
    },
    onSettlement() {
      if(this.selectionRows.length === 0) {
        this.$message.warning('请选择对账单！')
        return
      }
      let shareBenefitIds = this.selectionRows.map(item=>item.id).join(',')
      this.handleEdit({balanceMoney: this.totalMoney, shareBenefitIds}, '申请结算')
    },
    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.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    }
  },
  mounted() {
    this.pageType = this.$route.query.type
    if (this.$route.query.type == '1') {
      this.title = '详情'
      this.getPageDetail()
    } else if (this.$route.query.type == '2') {
      this.title = '审核'
      this.getPageDetail()
    } else if (this.$route.query.type == '3') {
      this.title = '结账申请'
      this.loadData()
    }
  }
}
</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>