<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="收费标准" :labelCol="{ xs: { span: 24 }, sm: { span: 2 } }" :wrapperCol="wrapperCol" prop="chargingStandardId">
              <a-select style="width:50%" v-model="model.chargingStandardId" placeholder="请选择收费标准" @change="onStandardChange">
                <a-select-option v-for="item in ruleList" :key="item.id" :value="item.id">{{item.chargeTypeCodeName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="收费类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="chargeTypeName">
              <a-input v-model="model.chargeTypeName" placeholder="请输入" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="收费项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="chargeItem">
              <a-input v-model="model.chargeItem" placeholder="请输入" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="关联房屋" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roomId">
              <a-tree-select
                v-model="model.roomId"
                style="width: 100%"
                :defaultExpandAll="true"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择关联房屋"
                :load-data="onLoadData"
                @select="onSelectRoom"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" style="padding-left:16px">
            <p style="line-height:30px">{{this.model.buildingName}}{{this.model.unitName}}{{this.model.roomName}}</p>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="业主" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerName">
              <a-input v-model="model.ownerName" placeholder="请输入" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="住户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="residentName">
              <a-input v-model="model.residentName" placeholder="请输入" disabled></a-input>
            </a-form-model-item>
          </a-col>

          <template v-if="model.designFormulas === 2">
            <a-col :span="12">
              <a-form-model-item label="房屋面积" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="floorSpace">
                <a-input v-model="model.floorSpace" placeholder="请输入房屋面积" style="width:100%" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="单价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitPrice">
                <a-input v-model="model.unitPrice" placeholder="请输入单价" style="width:100%" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </template>
          <template v-if="model.designFormulas === 3">
            <a-col :span="12">
              <a-form-model-item label="上期度数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastDegrees">
                <a-input v-model="model.lastDegrees" placeholder="请输入上期度数" style="width:100%" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="本期度数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentDegrees">
                <a-input-number v-model="model.currentDegrees" placeholder="请输入本期度数" style="width:100%" @change="onDegreesChange"></a-input-number>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="用量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useAmount">
                <a-input v-model="model.useAmount" placeholder="请输入用量" style="width:100%" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="单价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitPrice">
                <a-input v-model="model.unitPrice" placeholder="请输入单价" style="width:100%" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :span="12">
            <a-form-model-item label="金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalAmount">
              <a-input v-model="model.totalAmount" placeholder="请输入金额" style="width:100%" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="时间" :labelCol="{ xs: { span: 24 }, sm: { span: 2 } }" :wrapperCol="wrapperCol" prop="meterReadingTime">
              <j-date placeholder="请选择时间" v-model="model.meterReadingTime" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss" style="width: 50%;" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { formatDate } from '@/utils/util'
  import { getBuildingListApi, getUnitListApi, getRoomListApi, geCommunityRuleListApi, queryByRoomIdApi, queryLastDegreesByIdApi} from '@/api/api'

  export default {
    name: 'PropertyChargruleForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        ruleList: [],
        treeData: [],
        amount: 0,
        model:{
          chargeCycle: '',
          chargeItem: '',
          chargingStandardId: '',
          chargeTypeCode: '',
          chargeTypeId: '',
          chargeTypeName: '',
          unitPrice: '',
          designFormulas: 3,

          ownerId: '',
          buildingId: '',
          buildingName: '',
          unitId: '',
          unitName: '',
          roomId: '',
          roomName: '',
          floorSpace: '',
          ownerName: '',
          ownerPhone: '',
          residentName: '',
          residentPhone: '',
          relationShip: '',

          lastDegrees: '',
          currentDegrees: '',
          useAmount: '',
          totalAmount: '',
          meterReadingTime: ''
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        confirmLoading: false,
        validatorRules: {
          chargingStandardId: [{ required: true, message: '请选择收费标准', trigger: 'change' }],
          roomId: [{ required: true, message: '请选择关联房屋', trigger: 'change' }],
          currentDegrees: [{ required: true, message: '请输入本期度数', trigger: 'blur' }],
          // useAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
          meterReadingTime: [{ required: true, message: '请选择抄表时间', trigger: 'change' }]
        },
        url: {
          add: "/property-community/payment/communityPayment/add",
          edit: "/property-community/payment/communityPayment/edit",
          queryById: "/property-community/payment/communityPayment/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.getRuleList()
    },
    methods: {
      async getRuleList() {
        let {result} = await geCommunityRuleListApi()
        this.ruleList = result.map(item=> {
          return {
            ...item,
            chargeTypeCodeName: `${item.chargeTypeCode}-${item.chargeTypeName}`
          }
        })
      },
      async getBuildingList() {
        let {result} = await getBuildingListApi()
        this.treeData = result.map(item=> {
          return {
            value: item.id,
            label: item.buildingName,
            pId: 0,
            disabled: true
          }
        })
      },
      onStandardChange(id) {
        let row = this.ruleList.find(item=>item.id === id)
        this.model.chargeCycle = row.chargeCycle
        this.model.chargeItem = row.chargeItem
        this.model.chargeTypeCode = row.chargeTypeCode
        this.model.chargeTypeId = row.chargeTypeId
        this.model.chargeTypeName = row.chargeTypeName
        this.model.designFormulas = row.designFormulas
        this.amount = row.amount
        this.model.unitPrice = this.model.designFormulas === 1 ? '' : row.amount
        if(this.model.designFormulas === 1) {
          this.model.totalAmount = this.amount.toFixed(2)
        }
        if(this.model.designFormulas === 2 && this.model.roomId) {  // 获取上期度数
          this.model.totalAmount = (this.model.unitPrice * this.model.floorSpace).toFixed(2)
        }
        if(this.model.designFormulas === 3 && this.model.roomId) {  // 获取上期度数
          this.onqueryLastDegreesById()
        }
      },
      add () {
        this.getBuildingList()
        this.modelDefault.meterReadingTime = formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss')
        this.edit(this.modelDefault);
      },
      edit (record) {
        console.log(record)
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      onSelectRoom(value, node) {
        let data = node.dataRef
        this.model.roomId = data.value
        this.model.roomName = data.label
        this.model.floorSpace = data.floorSpace
        this.model.unitId = data.parent.value
        this.model.unitName = data.parent.label
        this.model.buildingId = data.parent.parent.value
        this.model.buildingName = data.parent.parent.label
        this.onqueryByRoomId()
        if(this.model.designFormulas === 2) {
          this.model.totalAmount = (this.model.unitPrice * this.model.floorSpace).toFixed(2)
        }
      },
      async onqueryLastDegreesById() {
        let res = await queryLastDegreesByIdApi({ownerId: this.model.ownerId,chargeTypeId: this.model.chargeTypeId})
        this.model.lastDegrees = res.result
        if(this.model.currentDegrees) {
          this.onDegreesChange(this.model.currentDegrees)
        }
      },
      async onqueryByRoomId() {
        let res = await queryByRoomIdApi({roomId: this.model.roomId})
        if(res.code === 200) {
          this.model.ownerName = res.result.ownerName
          this.model.ownerPhone = res.result.ownerPhone
          this.model.residentName = res.result.residentName
          this.model.residentPhone = res.result.residentPhone
          this.model.relationShip = res.result.relationShip
          this.model.ownerId = res.result.id
          if(this.model.designFormulas === 3 && this.model.chargeTypeId) {
            this.onqueryLastDegreesById()
          }
        } else {
          this.$message.warning(res.message);
          this.model.roomId = ''
          this.model.roomName = ''
          this.model.floorSpace = ''
          this.model.unitId = ''
          this.model.unitName = ''
          this.model.buildingId = ''
          this.model.buildingName = ''
        }
      },
      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 {
                value: item.id,
                label: item.unitName,
                pId: treeNode.dataRef.id,
                parent: {...treeNode.dataRef},
                disabled: true
              }
            })
            this.treeData = [...this.treeData];
            resolve();
          } else {  // 房屋
            let {result} = await getRoomListApi({id: treeNode.eventKey})
            treeNode.dataRef.children = result.map(item=> {
              return {
                value: item.id,
                label: item.roomNum,
                pId: treeNode.dataRef.id,
                floorSpace: item.floorSpace,
                parent: {...treeNode.dataRef},
                isLeaf: true
              }
            })
            this.treeData = [...this.treeData];
            resolve();
          }
        });
      },
      onDegreesChange(value) {
        if(this.model.lastDegrees || this.model.lastDegrees == 0) {
          this.model.useAmount = (value - Number(this.model.lastDegrees)).toFixed(2)
          this.model.totalAmount = (Number(this.model.useAmount) * this.amount).toFixed(2)
        }
      },
      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';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>