<template>
  <div class="AddBuildingBox">
    <PageHeader :title="userid ? '编辑车位' : '添加车位'"></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="130px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="区域" prop="areaId">
                <el-select v-model="form.areaId" placeholder="请选择" clearable>
                  <el-option v-for="dict in areaList" :key="dict.value" :label="`${dict.areaName}(${dict.areaCode})`" :value="dict.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="车位编号" prop="parkingCode">
                <el-input v-model.trim="form.parkingCode" placeholder="请输入车位编号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="11">
              <el-form-item label="车位面积" prop="parkingArea">
                <el-input v-model.number="form.parkingArea" placeholder="请输入车位面积" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="所属楼层" prop="parkingFloor">
                <el-input v-model.number="form.parkingFloor" placeholder="请输入所属楼层" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="车位类型" prop="type">
                <el-select v-model="form.type">
                  <el-option v-for="dict in com_parking_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="车位状态" prop="parkingStatus">
                <el-select v-model="form.parkingStatus" placeholder="请选择" clearable>
                  <el-option v-for="dict in com_parking_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="持有人类型" prop="contactType">
                <el-radio-group v-model="form.contactType">
                  <el-radio :value="1">业主</el-radio>
                  <el-radio :value="0">非业主</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.contactType === 0">
            <el-col :span="10">
              <el-form-item label="联系人名称" prop="contactName">
                <el-input v-model.trim="form.contactName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="联系人电话" prop="contactPhone">
                <el-input v-model.trim="form.contactPhone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else>
            <el-col :span="24">
              <el-form-item label="持有人" prop="residentId">
                <Holder :isMultiple="false" :userid="form.residentId ?? ''" ref="HolderRef" @change="handleChange">
                  <template #default>
                    <div class="residentBox" @click="choiceResidentFun">
                      <div class="defaultbox" v-if="form.residentId == null || form.residentId === ''">
                        <span>请选择</span>
                        <el-icon><Search /></el-icon>
                      </div>
                      <div v-else class="overflow-auto overflow-hidden w-full text-ellipsis text-nowrap">
                        <span>姓名：{{ form?.residentName }}</span>
                      </div>
                    </div>
                  </template>
                </Holder>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="5" v-model.trim="form.remark" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <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 Holder from '@/components/Holder/index.vue';
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { addParking, getParking, updateParking } from '@/api/system/parking';
import { listArea } from '@/api/system/carArea';
import { validator } from '@/utils/Reg';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_parking_type } = toRefs<any>(proxy?.useDict('com_parking_type'));
const { com_parking_status } = toRefs<any>(proxy?.useDict('com_parking_status'));

const router = useRouter();
const route = useRoute();

const formRef = ref();
const form = ref({
  id: null,
  areaId: null, // 区域id
  parkingArea: null, // 车位面积
  parkingFloor: null, // 车位楼层
  type: '0', // 车位类型
  residentId: '', // 住户id
  residentName: '', // 住户名
  parkingStatus: '', // 车位状态
  remark: '', // 备注
  parkingCode: '', // 车位编码

  contactName: '', // 联系人名称
  contactPhone: '', // 联系人手机
  contactType: 1 //  联系人类型 0 非业主 1 业主
});
const rules = ref({
  areaId: [{ required: true, message: '请选择车位区域', trigger: 'blur' }],
  type: [{ required: true, message: '请选择车位类型', trigger: 'blur' }],
  parkingCode: [{ required: true, message: '请输入车位编号', trigger: 'blur' }],
  residentId: [{ required: false, message: '请选择持有人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!validator(value, 'phone')) {
          callback(new Error('请输入正确的手机号码'));
        } else {
          callback();
        }
      }
    }
  ],
  contactName: [{ required: true, message: '请输入联系人名称', trigger: 'blur' }]
});

const userid = ref(null);
const HolderRef = ref<typeof Holder>(null);

if (route.query.id) {
  userid.value = route.query.id;
  getParking(userid.value).then((res) => {
    form.value = {
      ...form.value,
      ...res.data
    };
    // 有联系人姓名，电话 就是非业主
    if (form.value.contactName && form.value.contactPhone) {
      form.value.contactType = 0;
    }
  });
}
// ! 获取区域==================================================================================
const areaList = ref([]);
const getAreaList = async () => {
  const res = await listArea({
    pageSize: 99999,
    pageNum: 1
  });
  areaList.value = res.rows;
};
getAreaList();

const holderInfo = ref(null);
function choiceResidentFun() {
  if (form.value.residentId) {
    HolderRef.value.open([...form.value.residentId]);
  } else {
    HolderRef.value.open([]);
  }
}
function handleChange(pop) {
  holderInfo.value = null;
  holderInfo.value = pop;
  console.log(pop);
  form.value.residentId = '';
  form.value.residentName = '';
  if (pop !== null) {
    form.value.residentId = holderInfo.value.id;
    form.value.residentName = holderInfo.value.name;
  }
}

// !== 提交 =============================================================================
// 提交
const submitForm = () => {
  console.log(form.value);
  formRef.value?.validate(async (valid: boolean) => {
    console.log(valid);
    if (valid) {
      if (userid.value) {
        updateParking(form.value).then(() => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        addParking(form.value).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;
  }

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

    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
.residentBox {
  width: 385px;
  height: 35px;
  line-height: 35px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 10px;
  .defaultbox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  cursor: pointer;
  &:hover {
    background-color: #f4f8ff;
  }
}
</style>
