<template>
  <div class="AddBuildingBox">
    <PageHeader :title="storeRoomId ? '编辑储藏室' : '添加储藏室'"></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="left" ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="楼栋" prop="buildingId">
                <el-select @change="handleChangeBuild" v-model="form.buildingId" placeholder="请选择楼栋">
                  <el-option v-for="item in BuildingLists" :key="item.id" :label="item.buildingName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="单元" prop="unitNoId">
                <el-select v-model="form.unitNoId" placeholder="请选择单元">
                  <el-option v-for="item in units" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="储藏室号" prop="storeroomNo">
                <el-input maxlength="15" v-model.trim="form.storeroomNo" placeholder="请输入储藏室号" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="建筑面积" prop="houseArea">
                <el-input maxlength="8" v-model.trim="form.houseArea" placeholder="请输入建筑面积">
                  <template #append>
                    <span>㎡</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="公摊面积" prop="shareArea">
                <el-input maxlength="8" v-model.trim="form.shareArea" placeholder="请输入公摊面积">
                  <template #append>
                    <span>㎡</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="实用面积" prop="internalArea">
                <el-input maxlength="8" v-model.trim="form.internalArea" placeholder="请输入实用面积">
                  <template #append>
                    <span>㎡</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" maxlength="200" show-word-limit :rows="5" v-model.trim="form.remark" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { getBuildinglists } from '@/api/system/house';
import { addStoreroom, getStoreroom, updateStoreroom } from '@/api/system/storeroom';
import { StoreroomVO } from '@/api/system/storeroom/types';
import { getByBUildingidtoUnitNo } from '@/api/system/houseUnit';
import { validator } from '@/utils/Reg';

const route = useRoute();
const router = useRouter();
const formRef = ref();
const form = ref<StoreroomVO>({
  id: null,
  buildingId: '',
  unitNoId: '',
  unitName: '',
  storeroomNo: '',
  houseArea: null,
  shareArea: null,
  internalArea: null,
  houseId: '',
  status: 0,
  remark: ''
});
const rules = ref({
  buildingId: [{ required: true, message: '请选择楼栋', trigger: 'blur' }],
  unitNoId: [{ required: true, message: '请选择单元', trigger: 'blur' }],
  storeroomNo: [
    { required: true, message: '请输入储藏室号', trigger: 'blur' },
    {
      validator: (_: any, val: string | number, callback: (arg0?: Error) => void) => {
        if (val === '' || val === null || val === undefined) {
          return callback(new Error('请输入储藏室号'));
        }
        return validator(val, 'Character') ? callback() : callback(new Error('请输入中文,字母,数字,-,_等字符'));
      }
    }
  ],
  houseArea: [
    { required: true, message: '请输入建筑面积', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: (arg0?: Error) => void) => {
        if (value === '' || value === null) {
          return callback(new Error('请输入建筑面积'));
        }
        const val = Number(value);
        if (Number.isNaN(val)) {
          return callback(new Error('请输入数字'));
        }
        if (val < 0) {
          return callback(new Error('请输入大于0的数字'));
        }
        return callback();
      }
    }
  ],
  shareArea: [
    { required: false, message: '请输入公摊面积', trigger: 'blur' },
    {
      validator: (_: any, value: string | number, callback: (arg0?: Error) => void) => {
        if (value === '' || value === null) {
          return callback();
        }
        const val = Number(value);
        if (Number.isNaN(val)) {
          return callback(new Error('请输入数字'));
        }
        if (val < 0) {
          return callback(new Error('请输入大于0的数字'));
        }
        return callback();
      }
    }
  ],
  internalArea: [
    { required: false, message: '请输入实用面积', trigger: 'blur' },
    {
      validator: (_: any, value: string | number, callback: (arg0?: Error) => void) => {
        if (value === '' || value === null) {
          return callback();
        }
        const val = Number(value);
        if (Number.isNaN(val)) {
          return callback(new Error('请输入数字'));
        }
        if (val < 0) {
          return callback(new Error('请输入大于0的数字'));
        }
        return callback();
      }
    }
  ]
});

const storeRoomId = ref(null);
const units = ref([]);
const BuildingLists = ref([]);

// 获取储藏室信息
function getStoreRoomInfo(id: string) {
  getStoreroom(id).then((res) => {
    form.value = {
      ...form.value,
      ...res.data,
      houseArea: res.data.houseArea === 0 ? null : res.data.houseArea,
      shareArea: res.data.shareArea === 0 ? null : res.data.shareArea,
      internalArea: res.data.internalArea === 0 ? null : res.data.internalArea
    };
    if (form.value.buildingId) {
      handleChangeBuild(form.value.buildingId, () => {
        form.value.unitNoId = res.data.unitNoId;
      });
    }
    console.log(form.value);
  });
}
// 根据小区id获取楼栋单元
function init() {
  getBuildinglists().then((res) => {
    BuildingLists.value = res.rows;
  });
}
init();
onMounted(() => {
  if (route.query.id) {
    storeRoomId.value = route.query.id;
    getStoreRoomInfo(storeRoomId.value);
  }
});
// 根据楼栋id获取单元
function handleChangeBuild(val: string, callback?: () => void) {
  getByBUildingidtoUnitNo(val).then((res) => {
    units.value = res.data;
    callback && callback();
  });
}
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const data = {
        ...form.value
      };
      if (storeRoomId.value !== null) {
        updateStoreroom(data).then(() => {
          ElMessage.success('修改成功');
          cancelForm();
        });
      } else {
        addStoreroom(data).then(() => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
const cancelForm = () => {
  router.back();
};
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .addBuildingFormBody {
    .formBody {
      width: 1050px;
      margin: 0 auto;

      .el-form-item__content,
      .el-select,
      .el-input {
        width: 440px;
        margin-right: 10px;
      }
      .el-form-item {
        margin-bottom: 20px;
        align-items: center;
      }
      .unitBox {
        .el-input {
          width: 440px;
          margin-right: 10px;
        }
      }
      .el-button {
        width: 80px;
        height: 35px;
        margin-right: 20px;
      }

      .houseTypebox {
        display: flex;
        align-items: center;
        .el-input {
          width: 100px;
          margin-right: 0;
        }
        span {
          margin: 0 20px;
        }
      }
    }
    padding-bottom: 40px;
  }
}
</style>
