<template>
  <div class="ResidentMainBox p-2 w-full">
    <PageHeader></PageHeader>
    <div class="ResidentMainBody">
      <el-card>
        <template #header>
          <div class="title">基本信息</div>
        </template>
        <div class="addBuildingFormBody">
          <div class="formbox">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="房屋" prop="houseId">
                    <el-cascader @change="handleChange" v-model="userHousepath" :options="treedata" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人" prop="applyName">
                    <el-input v-model.trim="form.applyName" placeholder="请输入申请人" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="装修公司" prop="decorationCompany">
                    <el-input v-model.trim="form.decorationCompany" placeholder="请输入装修公司" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="装修内容" prop="decorationContent">
                    <el-input v-model.trim="form.decorationContent" placeholder="请输入装修内容" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="装修押金(元)" prop="decorationDeposit">
                    <el-input
                      type="number"
                      min="0"
                      step="0.01"
                      placeholder="请输入装修押金，最多保留2位小数"
                      v-model.trim.number="form.decorationDeposit"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="handleBack">返回</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { addDecoration, getDecoration, updateDecoration } from '@/api/system/Decoration';
import { useHouseStore } from '@/store/modules/house';

const houseStore = useHouseStore();
const treedata = ref([]);

const route = useRoute();
const router = useRouter();
const formRef = ref();
const form = ref({
  'id': null,
  'houseId': null,
  'buildingId': null,
  'unitNoId': null,
  'applyName': '',
  'decorationCompany': '',
  'decorationContent': '',
  'decorationDeposit': null
});

/**
 * 通用金额校验器
 * @param value 输入值
 * @param type money金额 / num整数
 * @returns 校验提示信息，空则校验通过
 */
const validator = (value: number | null, type: 'money' | 'num') => {
  // 空值由 required 规则拦截，这里只处理有值的情况
  if (value === null || value === undefined) return '';

  // 转字符串处理小数位数
  const strVal = String(value);
  // 禁止负数
  if (value < 0) return '金额不能为负数';

  if (type === 'money') {
    // 匹配最多两位小数
    const reg = /^\d+(\.\d{1,2})?$/;
    if (!reg.test(strVal)) return '金额仅支持最多两位小数';
    // 限制金额上限（可按需修改）
    if (value > 9999999.99) return '押金金额不能超过9999999.99元';
  } else if (type === 'num') {
    const reg = /^\d+$/;
    if (!reg.test(strVal)) return '只能输入正整数';
  }

  return '';
};
const rules = {
  houseId: [{ required: true, message: '请选择具体房屋', trigger: 'blur' }],
  applyName: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
  decorationDeposit: [
    { required: true, message: '请输入装修押金', trigger: 'blur' },
    {
      validator: (rule, val, callback) => {
        const msg = validator(val, 'money');
        if (msg) callback(new Error(msg));
        else callback();
      },
      trigger: ['blur', 'change']
    }
  ],
  decorationContent: [{ required: true, message: '请输入装修内容', trigger: 'blur' }]
};
const userid = ref();

// 获取房屋
const userHousepath = ref([]);
function handleChange(val: (string | number)[]) {
  if (val.length >= 3) {
    form.value.houseId = val.at(2) as number;
  } else {
    form.value.houseId = null;
  }
}

//  ! 投诉 ====================================================================================================
function getTree() {
  houseStore.getCurrentVilageTreeHouse().then((res) => {
    treedata.value = res;
    if (route.query.id) {
      userid.value = route.query.id;
      init();
    }
  });
}
getTree();
// TODO
function init() {
  getDecoration(userid.value).then((res) => {
    form.value = {
      ...form.value,
      ...res.data
    };
    userHousepath.value = [form.value.buildingId, form.value.unitNoId, form.value.houseId];
  });
}

// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (userid.value) {
        updateDecoration(form.value).then(() => {
          ElMessage.success('编辑成功');
          handleBack();
        });
      } else {
        addDecoration(form.value).then(() => {
          ElMessage.success('添加成功');
          handleBack();
        });
      }
    }
  });
};

//  返回
function handleBack() {
  router.push({
    path: '/repair/decoration'
  });
}
</script>

<style scoped lang="scss">
.ResidentMainBox {
  display: flex;
  flex-direction: column;
  .ResidentMainBody {
    margin-top: 20px;
    flex: 1;

    .formbox {
      width: 1000px;
      margin: 0 auto;
    }
    &:deep(div.el-step__head.is-process) {
      & > div.el-step__line {
        width: 0;
        border: 1px dashed gray;
        background: transparent;
      }
    }
    &:deep(.el-step.is-vertical .el-step__line) {
      top: 20px;
    }
    &:deep(div.el-step__head.is-finish) {
      & > div.el-step__line {
        width: 0;
        border: 1px solid var(--el-color-primary);
        background: transparent;
      }
    }
  }
}
</style>
