<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">
              <a-input v-model="model.buildingName" placeholder="请输入楼宇名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="建成日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="completedDate">
              <j-date placeholder="请选择建成日期" v-model="model.completedDate"  style="width: 100%" />
            </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 dictOptions" :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="buildingArea">
              <a-input type="number" v-model="model.buildingArea" 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 } }" :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }" prop="communityUnitList">
              <div>
                <a-table
                  ref="table"
                  size="middle"
                  :scroll="{x:true}"
                  bordered
                  rowKey="key"
                  :columns="columns"
                  :pagination="false"
                  :dataSource="model.communityUnitList"
                  class="j-table-force-nowrap"
                >
                  <span slot="unitName" slot-scope="text, record">
                    <a-input v-model="record.unitName" placeholder="请输入楼宇编号"></a-input>
                  </span>
                  <span slot="action" slot-scope="text, record">
                    <a @click="onDeleteUnit(record)">删除</a>
                  </span>
                </a-table>
              </div>
              <div>
                <a-button type="primary" @click="addUnit">新增</a-button>
              </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="haveLift">
              <a-radio-group name="radioGroup" v-model="model.haveLift">
                <a-radio value="1">有</a-radio>
                <a-radio value="0">无</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="管理员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buildingAdmin">
              <a-input v-model="model.buildingAdmin" placeholder="请输入管理员"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="adminPhone">
              <a-input v-model="model.adminPhone" 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 } }" :wrapperCol="wrapperCol" prop="adminAvatar">
              <j-image-upload :isMultiple="false" text="点击上传" bizPath="scott/pic" v-model="model.adminAvatar"></j-image-upload>
            </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 { validateDuplicateValue } from '@/utils/util'
  import {ajaxGetDictItems,getDictItemsFromCache} from '@/api/api'
  import { isMobile } from '@/utils/validate'
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      align: 'center'
    },
    {
      title: '楼宇编号',
      dataIndex: 'unitName',
      key: 'unitName',
      scopedSlots: { customRender: 'unitName' },
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' },
      align: 'center',
      width: 150
    }
  ]
  export default {
    name: 'PropertyChargruleForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      const validateToNextPhone = (rule, value, callback)=> {
        if (value && isMobile(value)) {
          callback();
        } else {
          callback('请输入正确的联系人电话！');
        }
      }
      return {
        dictOptions: [],
        model:{
          buildingName: '',
          completedDate: '',
          useTo: '',
          buildingArea: '',
          communityUnitList: [],
          haveLift: '1',
          buildingAdmin: '',
          adminPhone: '',
          adminAvatar: ''
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          buildingName: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }],
          communityUnitList: [{ required: true, message: '请输入单元数量', trigger: 'change' }],
          useTo: [{ required: true, message: '请选择房屋用途', trigger: 'change' }],
          buildingAdmin: [{ required: true, message: '请输入楼栋管理员', trigger: 'blur' }],
          adminPhone: [
            { required: true, message: '请输入管理员联系电话', trigger: 'blur' },
            { validator: validateToNextPhone }
          ],
          adminAvatar: [{ required: true, message: '请上传管理员头像', trigger: 'blur' }]
        },
        url: {
          add: "/property-community/building/communityBuilding/add",
          edit: "/property-community/building/communityBuilding/edit",
          queryById: "/property-community/building/communityBuilding/queryById"
        },
        columns: columns
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.initDictData()
    },
    methods: {
      initDictData() {
        //优先从缓存中读取字典配置
        if(getDictItemsFromCache('house_purpose')){
          this.dictOptions = getDictItemsFromCache('house_purpose');
          return
        }
        // //根据字典Code, 初始化字典数组
        ajaxGetDictItems('house_purpose', null).then((res) => {
          if (res.success) {
            this.dictOptions = res.result;
          }
        })
      },
      ruleNumberInput(event) {
        let rateValue = event.target.value.replace(/[^\d]/g,"");//清除"数字"和"."和"-"以外的字符
        this.model['empowerDays'] = rateValue
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        console.log(record)
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      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;
            })
          }
         
        })
      },
      addUnit() {
        this.model.communityUnitList.push({
          randomId: new Date().getTime().toString() + Math.floor(Math.random() * 100),
          key: this.model.communityUnitList.length + 1,
          unitName: ''
        })
      },
      onDeleteUnit(record) {
        this.model.communityUnitList = this.model.communityUnitList.filter(item=>item.randomId !== record.randomId)
      }
    }
  }
</script>