<template>
  <div class="page-content">
    <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="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">
              <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="请输入业主名称"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="业主联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerPhone">
                <a-input v-model="model.ownerPhone" placeholder="请输入业主联系方式"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="证件类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="certificateType">
                <a-select style="width: 100%" v-model="model.certificateType" placeholder="请选择证件类型">
                  <a-select-option value="1">身份证</a-select-option>
                  <a-select-option value="2">港澳通行证</a-select-option>
                  <a-select-option value="3">护照</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="certificateNo">
                <a-input v-model="model.certificateNo" placeholder="请输入证件号码"></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="relationShip">
                <a-select style="width: 100%" v-model="model.relationShip" placeholder="请选择与业主关系">
                  <a-select-option v-for="item in relationShipList" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row v-if="model.relationShip && model.relationShip !== 'self'">
            <a-col :span="12">
              <a-form-model-item label="住户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="residentName">
                <a-input v-model="model.residentName" placeholder="请输入住户姓名"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="住户联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="residentPhone">
                <a-input v-model="model.residentPhone" placeholder="请输入住户联系方式"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex" justify="end">
            <a-col :span="4">
              <a-button @click="onCancel">取消</a-button>
              <a-button @click="onSubmit" type="primary" style="margin-left: 10px;">确认</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-spin>
  </div>
</template>

<script>
  import { getBuildingListApi, getUnitListApi, getRoomListApi } from '@/api/api'
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import {ajaxGetDictItems,getDictItemsFromCache} from '@/api/api'
  import { isMobile } from '@/utils/validate'
  import {RELATION_SHIP} from '@/assets/static.js'

  export default {
    name: 'PropertyChargruleForm',
    inject:['closeCurrent'],
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      const validateToNextPhone = (rule, value, callback)=> {
        if (value && isMobile(value)) {
          callback();
        } else {
          callback('请输入正确的联系人电话！');
        }
      }
      return {
        relationShipList: RELATION_SHIP,
        model:{
          buildingId: '',
          buildingName: '',
          unitId: '',
          unitName: '',
          roomId: '',
          roomName: '',
          useTo: '',
          floorSpace: '',
          ownerName: '',
          ownerPhone: '',
          certificateType: '1',
          certificateNo: '',
          relationShip: '',
          residentName: '',
          residentPhone: ''
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          roomId: [{ required: true, message: '请选择关联房屋', trigger: 'change' }],
          ownerName: [{ required: true, message: '请输入业主名称', trigger: 'blur' }],
          ownerPhone: [
            { required: true, message: '请输入业主联系方式', trigger: 'blur' },
            { validator: validateToNextPhone }
          ],
          relationShip: [{ required: true, message: '请选择与业主关系', trigger: 'change' }],
          residentName: [{ required: true, message: '请输入住户姓名', trigger: 'blur' }],
          residentPhone: [{ required: true, message: '请输入住户联系方式', trigger: 'blur' }]
        },
        url: {
          add: "/property-community/info/communityOwner/add",
          edit: "/property-community/info/communityOwner/edit",
          queryById: "/property-community/wechat/communityOwner/queryById"
        },
        treeData: [],


        dictOptions: [
          {label: '商用', value: 1},
          {label: '普通住宅', value: 2},
          {label: '商住合一', value: 3}
        ]
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.add ()
    },
    methods: {
      async getBuildingList() {
        let {result} = await getBuildingListApi()
        this.treeData = result.map(item=> {
          return {
            value: item.id,
            label: item.buildingName,
            pId: 0,
            disabled: true
          }
        })
      },
      onSelectRoom(value, node) {
        console.log(node)
        let data = node.dataRef
        this.model.roomId = data.value
        this.model.roomName = data.label
        this.model.useTo = data.useTo
        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
      },
      ruleNumberInput(event) {
        let rateValue = event.target.value.replace(/[^\d]/g,"");//清除"数字"和"."和"-"以外的字符
        this.model['empowerDays'] = rateValue
      },
      add () {
        this.getBuildingList()
        this.edit(this.modelDefault);
      },
      async edit(record) {
        if(record.buildingId) {
          let {result} = await getBuildingListApi()
          this.treeData = result.map(item=> {
            return {
              value: item.id,
              label: item.buildingName,
              pId: 0,
              disabled: true
            }
          })
          let unitResult = await getUnitListApi({id: record.buildingId})
          let unitChildren = unitResult.result.map(item=> {
            return {
              value: item.id,
              label: item.unitName,
              pId: record.buildingId,
              parent: {value: record.buildingId, label: record.buildingName},
              disabled: true
            }
          })
          let unitKey = this.treeData.findIndex(item=>item.value === record.buildingId)
          this.treeData[unitKey]['children'] = unitChildren
  
          let roomResult = await getRoomListApi({id: record.unitId})
          let roomChildren = roomResult.result.map(item=> {
            return {
              value: item.id,
              label: item.roomNum,
              pId: record.unitId,
              parent: {value: record.unitId, label: record.unitName},
              isLeaf: true
            }
          })
          let roomKey = this.treeData[unitKey]['children'].findIndex(item=>item.value === record.unitId)
          this.treeData[unitKey]['children'][roomKey]['children'] = roomChildren
        }
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      onCancel() {
        this.closeCurrent()
      },
      onSubmit () {
        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.closeCurrent()
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      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,
                useTo: item.useTo,
                floorSpace: item.floorSpace,
                parent: {...treeNode.dataRef},
                isLeaf: true
              }
            })
            this.treeData = [...this.treeData];
            resolve();
          }
        });
      }
    }
  }
</script>
<style scoped lang="less">
.page-content {
  min-height: 430px;
  background-color: #fff;
  padding-top: 20px;
}
</style>