<template>
  <div class="page-content">
    <a-spin :spinning="confirmLoading">
      <h4 style="padding:20px 0 0 50px;line-height:30px;">审核流程</h4>
      <div class="row-box">
        <a-steps :current="1">
          <a-step title="提交住户信息" description="2020.09.09 10:12" />
          <a-step title="物业审核" />
          <a-step title="认证通过" />
        </a-steps>
      </div>
      <h4 style="padding:20px 0 0 50px;line-height:30px;">住户基础资料</h4>
      <j-form-container :disabled="true">
        <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.trim="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-form-model>
      </j-form-container>
      <h4 style="padding:20px 0 0 50px;line-height:30px;">审核意见</h4>
      <div class="row-box">
        <a-textarea style="width:500px" v-model="auditOpinion" placeholder="请输入" allow-clear />
        <a-row type="flex" justify="end">
          <a-button @click="onCancel">取消</a-button>
          <a-button @click="onSubmit('auditPass')" type="primary" style="margin-left: 10px;">审核通过</a-button>
          <a-button @click="onSubmit('refuse')" type="danger" style="margin-left: 10px;">审核驳回</a-button>
        </a-row>
      </div>
    </a-spin>
  </div>
</template>

<script>
  import { geCommunityOwnertInfoApi, getBuildingListApi, getUnitListApi, getRoomListApi, auditCommunityOwnerApi } from '@/api/api'
  import { isMobile, isValidIDCard, isValidPassport, isValidPermit } from '@/utils/validate'
  import {RELATION_SHIP} from '@/assets/static.js'

  export default {
    name: 'PropertyChargruleForm',
    inject:['closeCurrent'],
    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 }
          ],
          certificateNo: [{
            trigger: 'blur',
            message: '请输入业主联系方式',
            required: true
            // validator: function(rule, value, callback) {
            //   if (value) {
            //     callback();
            //   } else {
            //     callback('请输入正确的联系人电话！');
            //   }
            // }
          }],
          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: [],

        auditOpinion: '',
        dictOptions: [
          {label: '商用', value: 1},
          {label: '普通住宅', value: 2},
          {label: '商住合一', value: 3}
        ]
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.getPageDetail()
    },
    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
      },
      async getPageDetail() {
        let {result} = await geCommunityOwnertInfoApi({id: this.$route.query.id})
        this.edit(result)
      },
      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()
      },
      async onSubmit (auditStatus) {
        let res = await auditCommunityOwnerApi({
          id: this.$route.query.id,
          auditOpinion: this.auditOpinion,
          auditStatus
        })
        this.$message.success(res.message);
        this.closeCurrent()
      },
      onChange() {},
      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-bottom: 50px;
  .row-box {
    padding: 0 50px;
    width: 90%;
  }
}
</style>