<template>
  <div class="UnitBox">
    <div class="Unit_top flex align-center justify-between">
      <div style="text-wrap: nowrap">
        <span class="text-size-16px text-color-black text-widget-bold mr-30px">
          <strong>{{ houseStore.currentBuildingInfo?.buildingName }}</strong>
        </span>
        <span class="mr-15px"
          >楼栋朝向:{{ houseStore.currentBuildingInfo?.buildToward ? `${houseStore.currentBuildingInfo?.buildToward}` : ' --' }}</span
        >
        <span class="mr-15px">楼高:{{ houseStore.currentBuildingInfo?.buildTall ? `${houseStore.currentBuildingInfo?.buildTall}(m)` : ' --' }}</span>
        <span class="mr-15px"
          >楼栋结构:{{ houseStore.currentBuildingInfo?.buildStructure ? `${houseStore.currentBuildingInfo?.buildStructure}` : ' --' }}
        </span>
      </div>
      <div style="text-wrap: nowrap" class="rightActions flex flex-items-center">
        <span class="mr-20px" @click="handleAddUnit" v-has-permi="['unitNo:unitNo:add']">+添加单元</span>
        <span class="mr-20px" @click="handleAddHouse" v-has-permi="['system:house:add']">+增加房屋</span>
        <!-- <span class="mr-20px">收费标准设置</span> -->
        <span @click="deleteAllhouse" v-has-permi="['system:house:remove']">批量删除房屋</span>
        <el-select clearable @clear="handleClearUse" @change="handleChangeUse" v-model="houseUse" placeholder="筛选房屋类型" class="selectbox">
          <el-option v-for="item in houseUseTypeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <div class="searchbox flex flex-items-center">
          <el-input v-model="housename" maxlength="15" class="searchinput" placeholder="请输入房屋号"></el-input>
          <el-button style="margin-left: 10px" type="primary" @click="handleSearchHouse">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </div>
      </div>
    </div>
    <!-- <div class="UnitBody"> -->
    <TableUnit @edit-unit="handleEditUnit" @delete-unit="handleDelete"></TableUnit>
    <!-- </div> -->
    <!-- 添加或修改单元对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="unitNoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单元名称" prop="name">
          <el-input maxlength="6" show-word-limit v-model.trim="form.name" placeholder="请输入单元名称" />
        </el-form-item>
        <el-form-item label="楼栋" prop="buildingId">
          <el-select v-model="form.buildingId" placeholder="请选择">
            <el-option v-for="item in houseStore.currentBuildingInfoList" :key="item.id" :label="item.buildingName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { deleteHouseApi } from '@/api/system/house';
import TableUnit from './components/table.vue';
import { useHouseStore } from '@/store/modules/house';
import { listHouseUseType_add_house } from '@/api/system/houseUse';
import { addUnitNo, delUnitNo, getUnitNo, updateUnitNo } from '@/api/system/houseUnit';
import { validator } from '@/utils/Reg';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const houseStore = useHouseStore();
const router = useRouter();

const housename = ref('');
const houseUse = ref('');
const houseUseTypeList = ref([]);

/**
 * 获取房屋 类型
 */
function init() {
  listHouseUseType_add_house({}).then((res) => {
    houseUseTypeList.value = res.data;
  });
}
init();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const unitNoFormRef = ref();
const buttonLoading = ref(false);
const form = ref({
  id: undefined,
  name: undefined,
  buildingId: undefined,
  villageId: undefined
});

const rules = {
  name: [
    { required: true, message: '单元名称不能为空', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: (error?: Error) => void) => {
        if (!value || value.trim() === '') {
          callback();
          return;
        }
        // 使用 Character 正则验证(只允许字母、数字、中文、下划线、横线)
        const isValid = validator(value, 'Character');
        if (!isValid) {
          callback(new Error('只能输入中文、字母、数字、下划线和横线'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  buildingId: [{ required: true, message: '所属楼栋不能为空', trigger: 'blur' }]
};
/** 新增按钮操作 */
const handleAddUnit = () => {
  resetForm();
  dialog.visible = true;
  dialog.title = '添加单元';
};
/** 修改按钮操作 */
const handleEditUnit = async (id: string) => {
  resetForm();
  const res = await getUnitNo(id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改单元';
};
/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  await proxy?.$modal.confirm('是否确认删除该单元？');
  await delUnitNo(id);
  proxy?.$modal.msgSuccess('删除成功');
  // await getList();
  houseStore.updateCureentBuilding();
};

/** 提交按钮 */
const submitForm = () => {
  unitNoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUnitNo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUnitNo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      houseStore.updateCureentBuilding();
    }
  });
};
/** 取消按钮 */
const cancel = () => {
  resetForm();
  dialog.visible = false;
};
/** 表单重置 */
const resetForm = () => {
  form.value = { id: undefined, name: undefined, buildingId: undefined, villageId: undefined };
  unitNoFormRef.value?.resetFields();
};
/**
 * 改变房屋类型
 * @param id
 */
function handleChangeUse(id?: string) {
  houseUse.value = id;
}
function handleClearUse() {
  houseUse.value = '';
  handleSearchHouse();
}
/** 添加房屋 */
function handleAddHouse() {
  router.push({
    path: '/house/addHouse'
  });
}

/**
 * 搜索 房屋
 */
function handleSearchHouse() {
  houseStore.getHouseBybuildingNo(housename.value, houseUse.value);
}
function reset() {
  housename.value = '';
  houseUse.value = '';
  houseStore.getHouseBybuildingNo(housename.value, houseUse.value);
}

async function deleteAllhouse() {
  await proxy?.$modal.confirm('该信息删除后无法恢复，确定要删除吗？');
  const checkhouse = houseStore.checkoutHouses;
  if (checkhouse.length > 0) {
    deleteHouseApi(checkhouse).then(() => {
      houseStore.switchBuilding(houseStore.currentBuildingInfo.id);
      ElMessage.success('批量删除成功');
    });
  } else {
    ElMessage.warning('请选择要删除的房屋');
  }
}
</script>

<style scoped lang="scss">
$primary_color: #1978fe;
.UnitBox {
  flex: 1;
  height: 100%;
  max-width: 100%;
  border-radius: 2px;
  font-size: 14px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;

  .Unit_top {
    padding: 20px;
    height: 60px;
    color: rgba(102, 102, 102, 1);
    .rightActions {
      color: $primary_color;
      height: 35px;
      span {
        cursor: pointer;
      }
      .selectbox {
        width: 150px;
        margin: 0 10px;
        @media (max-width: 1550px) {
          width: 120px;
        }
        @media (max-width: 1400px) {
          width: 80px;
        }
      }
      .searchbox {
        .searchinput {
          width: 250px;
          @media (max-width: 1550px) {
            width: 130px;
          }
          @media (max-width: 1400px) {
            width: 50px;
          }
        }
      }
    }
  }
  .UnitBody {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
    display: flex;
  }
}
</style>
