<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="12">
            <a-form-model-item label="楼宇" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buildingName">
              <my-popup
                v-model="model.buildingName"
                icon="bank"
                field="name"
                title="选择楼宇"
                :multi="false"
                url="/property-community/building/communityBuilding/list"
                :columns="buildingColumns"
                @callback="onChoseBuilding"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="单元" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitObj">
              <a-select style="width: 100%" v-model="model.unitObj" placeholder="请选择单元" labelInValue>
                <a-select-option v-for="item in unitList" :key="item.id" :value="item.id">{{item.unitName}}</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="useTo">
              <a-select style="width: 100%" v-model="model.useTo" placeholder="请选择房屋用途">
                <a-select-option v-for="item in purposeOptions" :key="item.value" :value="item.value">{{item.label}}</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="roomNum">
              <a-input v-model="model.roomNum" placeholder="请输入房屋号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="建筑面积" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="floorSpace">
              <a-input type="number" v-model="model.floorSpace" placeholder="请输入建筑面积"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="房间户型" :labelCol="{ xs: { span: 24 }, sm: { span: 3 } }" prop="bedroomCount">
              <div style="display:flex;align-items:center;">
                <a-input style="width:100px" type="number" v-model="model.bedroomCount" placeholder="室数量"></a-input>
                <span style="margin:0 10px">室</span>
                <a-input style="width:100px" type="number" v-model="model.officeCount" placeholder="厅数量"></a-input>
                <span style="margin:0 10px">厅</span>
                <a-input style="width:100px" type="number" v-model="model.kitchenCount" placeholder="厨房数量"></a-input>
                <span style="margin:0 10px">厨</span>
                <a-input style="width:100px" type="number" v-model="model.toiletCount" placeholder="卫生间数量"></a-input>
                <span style="margin-left:10px">卫</span>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="房屋状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roomStatus">
              <a-select style="width: 100%" v-model="model.roomStatus" placeholder="请选择房屋状态">
                <a-select-option v-for="item in statusOptions" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import myPopup from '@/components/custom/myPopup'
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import {ajaxGetDictItems,getDictItemsFromCache, getUnitListApi} from '@/api/api'
  import {filterDictTextByCache} from '@/components/dict/JDictSelectUtil'

  export default {
    name: 'PropertyChargruleForm',
    components: {
      myPopup
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        purposeOptions: [],
        statusOptions: [],
        model:{
          buildingId: '',
          buildingName: '',
          unitObj: '',
          useTo: '',
          roomNum: '',
          floorSpace: '',
          bedroomCount: '',
          officeCount: '',
          kitchenCount: '',
          toiletCount: '',
          roomStatus: ''
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          buildingId: [{ required: true, message: '请输入楼宇', trigger: 'blur' }],
          unitObj: [{ required: true, message: '请输入单元', trigger: 'blur' }],
          useTo: [{ required: true, message: '请选择房屋用途', trigger: 'change' }],
          roomNum: [{ required: true, message: '请输入房屋号', trigger: 'blur' }],
          floorSpace: [{ required: true, message: '请输入建筑面积', trigger: 'blur' }],
          roomStatus: [{ required: true, message: '请选择房屋状态', trigger: 'change' }]
        },
        url: {
          add: "/property-community/building/communityRoom/add",
          edit: "/property-community/building/communityRoom/edit",
          queryById: "/property-community/building/communityRoom/queryById"
        },
        buildingColumns: [
          {
            title: '楼宇名称',
            dataIndex: 'buildingName',
            key: 'buildingName',
            align: 'center'
          },
          {
            title: '房屋用途',
            dataIndex: 'useTo',
            key: 'useTo',
            align: 'center',
            customRender: function(text) {
              return filterDictTextByCache('house_purpose', text);
            }
          },
          {
            title: '管理员',
            dataIndex: 'buildingAdmin',
            key: 'buildingAdmin',
            align: 'center'
          },
          {
            title: '联系方式',
            dataIndex: 'adminPhone',
            key: 'adminPhone',
            align: 'center'
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center'
          }
        ],
        unitList: []
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    watch: {
      'model.buildingName': {
        handler(newV) {
          if(newV) {
            if(this.unitList.length === 0) {
              this.onUnitList()
            }
          } else {
            this.model.unitObj = ''
          }
        },
        immediate: true
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.initDictData()
    },
    methods: {
      initDictData() {
        //优先从缓存中读取字典配置
        if(getDictItemsFromCache('house_purpose')){
          this.purposeOptions = getDictItemsFromCache('house_purpose');
          this.statusOptions = getDictItemsFromCache('house_status');
          return
        }
        // //根据字典Code, 初始化字典数组
        ajaxGetDictItems('house_purpose', null).then((res) => {
          if (res.success) {
            this.purposeOptions = res.result;
          }
        })
        // //根据字典Code, 初始化字典数组
        ajaxGetDictItems('house_status', null).then((res) => {
          if (res.success) {
            this.statusOptions = res.result;
          }
        })
      },
      async onUnitList() {
        let {result} = await getUnitListApi({id: this.model.buildingId})
        this.unitList = result
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        console.log(record)
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      onChoseBuilding(list) {
        const row = list[0]
        this.model.buildingName = row.buildingName
        this.model.buildingId = row.id
        this.model.unitObj = ''
        this.unitList = row.communityUnitList
      },
      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, unitId: this.model.unitObj.key, unitName: this.model.unitObj.label},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>