<template>
  <div class="AddBuildingBox">
    <PageHeader></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="房屋" prop="houseId">
                <el-cascader @change="handleChange" v-model="userHousePath" :options="treeData" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="业主姓名" prop="rentalName">
                <el-input maxlength="20" v-model.trim="form.rentalName" placeholder="请输入业主姓名" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="11">
              <el-form-item label="租赁状态" prop="rentalStatus">
                <el-select v-model="form.rentalStatus" placeholder="请选择">
                  <el-option v-for="(item, index) in com_rental_status" :key="index" :label="item.label" :value="Number(item.value)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <!--              <el-form-item label="房屋用途" prop="houseUse">-->
              <!--                <el-select v-model.trim="form.houseUse" placeholder="请选择">-->
              <!--                  <el-option v-for="(item, index) in houseUseTypeList" :key="index" :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="rent">
                <el-input maxlength="8" v-model.number.trim="form.rent" placeholder="请输入租金">
                  <template #suffix>￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="租赁方式" prop="rentalType">
                <el-radio-group v-model="form.rentalType">
                  <el-radio v-for="item in com_rental_method" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="11">
              <el-form-item label="房屋朝向" prop="type">
                <el-select v-model="form.houseFace" placeholder="请选择">
                  <el-option v-for="(item, index) in houseFormat" :key="index" :label="item" :value="item" />
                </el-select>
              </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 #suffix> ㎡ </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="房屋楼层" prop="floorNo">
                <el-input-number :max="1000" v-model.number.trim="form.floorNo" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="入住时间" prop="inTime">
                <el-date-picker
                  value-format="YYYY-MM-DD"
                  tag-effect="dark"
                  tag-type="primary"
                  v-model="form.inTime"
                  type="date"
                  placeholder="选择入住时间"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="房屋设施" prop="type">
                <div class="houseDevicesBox" v-if="houseFacilities.length > 0">
                  <div
                    v-for="item in houseFacilities"
                    :key="item.id"
                    @click="handleClick(item.id)"
                    class="houseDevices_Item"
                    :class="{
                      active: houseDevicesList.includes(item.id)
                    }"
                  >
                    <span class="checked">√</span>
                    <span class="ml-2">{{ item.name }}</span>
                  </div>
                </div>
                <span v-else style="color: gray"> 无</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传房屋照片">
                <el-upload
                  ref="uploadRef"
                  accept=".png, .jpg"
                  v-model:file-list="fileList"
                  class="avatar-uploader"
                  :action="uploadUrl"
                  name="files"
                  :multiple="true"
                  :auto-upload="false"
                  list-type="picture-card"
                  :limit="9"
                  :on-exceed="handleExceed"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :on-change="handleChangeFile"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">jpg/png 文件格式</div>
                  </template>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </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.supInfo" placeholder="请输入补充房屋信息" />
          </el-form-item>
          <el-row>
            <el-col :span="11">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model.number.trim="form.phone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="微信" prop="vx">
                <el-input maxlength="11" v-model.trim="form.vx" placeholder="请输入微信号码" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <!--              <el-form-item label="邮箱" prop="email">-->
              <!--                <el-input v-model.trim="form.email" 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 { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { CascaderValue, UploadFiles, UploadInstance, UploadProps, UploadUserFile } from 'element-plus';

import { hasFormData, splitStringUrl } from '@/utils/house';
import { addHouseRental, getHouseOwnUser, getHouseRental, updateHouseRental, uploadHouseImage } from '@/api/system/houseRental';
import { validator } from '@/utils/Reg';
import { useHouseStore } from '@/store/modules/house';
import { listHouseFacilities } from '@/api/system/HouseFacilities';
import { Plus } from '@element-plus/icons-vue';
import { listHouseUseType_add_house } from '@/api/system/houseUse';

const houseStore = useHouseStore();

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/houseRental/uploadImages';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_rental_method } = toRefs<any>(proxy?.useDict('com_rental_method'));
const { com_rental_status } = toRefs<any>(proxy?.useDict('com_rental_status'));
// const { com_house_use } = toRefs<any>(proxy?.useDict('com_house_use'));&╬╬╥

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

const formRef = ref();
// 房屋朝向
const houseFormat = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
const form = ref({
  id: null,
  houseId: null,
  rentalName: '', // 租户姓名
  rent: null, // 租金
  houseFace: '', // 房屋朝向
  rentalType: '0', //  整租合租
  phone: null, //手机号
  houseArea: 0, // 房屋面积
  floorNo: 1, //楼层号
  inTime: '', //入住时间
  facilities: '', //房屋设施
  houseImageUrl: '', //房屋图片
  supInfo: '', //补充租房信息
  vx: '', //微信
  houseUse: '', //房屋用途
  rentalStatus: 1, //租赁状态
  buildingId: null, //楼栋id
  unitNoId: null, //单元id
  email: '' //邮箱
});
const userHousePath = ref<CascaderValue>([]);
const rules = ref({
  houseId: [{ required: true, message: '请选择房屋', trigger: 'blur' }],
  rentalName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (_: any, val: string | number) => validator(val, 'phone'),
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: (_: any, val: string | number) => {
        if (val === '') {
          return true;
        }
        return validator(val, 'email');
      },
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ],
  rent: [
    {
      required: false,
      message: '请输入正确的租金',
      trigger: 'blur'
    },
    {
      validator: (_: any, val: string | number, callback: (arg0?: Error) => void) => {
        if (val === '' || val === null) {
          return callback();
        }
        if (validator(val, 'money')) {
          return callback();
        }
        return callback(new Error('请输入正确的租金'));
      }
    }
  ],
  houseArea: [
    {
      required: false,
      message: '请输入房屋面积',
      trigger: 'blur'
    },
    {
      validator: (_: any, value: string | number, callback: (arg0?: Error) => void) => {
        if (value === '' || value === null || value === 0) {
          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 userid = ref(null);
const treeData = ref(null);
const houseFacilities = ref([]);
// !==  楼栋房屋  =============================================================================╬
async function getTreeData() {
  const resList = await listHouseFacilities();
  houseFacilities.value = resList.rows
    .map((item) => {
      if (item.status !== '1') return item;
      return false;
    })
    .filter((item) => item !== false);

  treeData.value = await houseStore.getCurrentVilageTreeHouse();
  if (route.query.id) {
    userid.value = route.query.id;
    getHouseRental(userid.value).then((res) => {
      form.value = {
        ...form.value,
        ...res.data
      };
      if (form.value.facilities) houseDevicesList.value = form.value.facilities.split(',').filter((item) => item);
      if (form.value.houseImageUrl) fileList.value = splitStringUrl(form.value.houseImageUrl);
      handleChange([form.value.buildingId, form.value.unitNoId, form.value.houseId]);
    });
  }
}
getTreeData();

const houseUseTypeList = ref([]);
function getHouseUseType() {
  listHouseUseType_add_house().then((res) => {
    houseUseTypeList.value = res.data;
  });
}
getHouseUseType();

// 获取房屋
function handleChange(val: CascaderValue) {
  userHousePath.value = val;
  form.value.houseId = val[2];
  form.value.rentalName = '';
  if (val[2]) {
    getHouseOwnUser(val[2]).then((res) => {
      if (res.msg.trim()) {
        form.value.rentalName = res.msg.trim();
      } else {
        form.value.rentalName = '';
      }
    });
  }
}
// !== 上传文件 =============================================================================
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
// 上传文件成功
const uploadRef = ref<UploadInstance>();
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.data && response.data.error.length > 0) {
    ElMessage.error('图片上传失败，请稍后再试');
  }
};

const blockedExts = ['.exe', '.bat', '.cmd', '.msi'];
const handleChangeFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  const ext = uploadFile.name.toLowerCase().slice(uploadFile.name.lastIndexOf('.'));
  if (blockedExts.includes(ext)) {
    ElMessage.warning(`禁止上传 ${ext} 文件`);
    uploadRef.value.handleRemove(uploadFile);
    return;
  }
  fileList.value = uploadFiles;
};
const handleExceed = () => {
  ElMessage.warning('最多上传9张图片');
};
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = '';
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handleRemove: UploadProps['onRemove'] = (_, uploadFiles) => {
  fileList.value = uploadFiles;
};

// !== 家电 =============================================================================

// 家电
const houseDevicesList = ref([]);
function handleClick(index: number) {
  if (houseDevicesList.value.includes(index)) {
    houseDevicesList.value = houseDevicesList.value.filter((item) => item !== index);
  } else {
    houseDevicesList.value.push(index);
  }
}

// !== 提交 =============================================================================

// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 处理家电
      form.value.facilities = houseDevicesList.value.join(',');
      let str = '';
      // 判断有无图片
      if (fileList.value.length > 0) {
        const formData = new FormData();
        fileList.value.forEach((item) => {
          //  只处理 新增的图片
          if (item.raw && item.raw instanceof File) {
            formData.append('files', item.raw);
          } else {
            str += item.url + ',';
          }
        });
        if (!hasFormData(formData)) return sendForm(str);
        uploadHouseImage(formData)
          .then((res) => {
            if (res.data.success.length > 0) {
              const successList = res.data.success;
              successList.forEach((item) => {
                str += item.url + ',';
              });
              form.value.houseImageUrl = str;
            }
            if (res.data.error.length > 0) {
              const str = res.data.error.join(',');
              res.data.error.forEach((item) => {
                fileList.value = fileList.value.filter((file) => file.name !== item);
              });
              ElMessage.error('图片：' + str + ' 上传失败！');
            }
            sendForm(str);
          })
          .catch((err) => {
            if (err && err.data && err.data.error.length > 0) {
              const str = err.data.error.join(',');
              err.data.error.forEach((item: string) => {
                fileList.value = fileList.value.filter((file) => file.name !== item);
              });
              ElMessage.error('图片：' + str + ' 上传失败!,请重新上传');
            }
          });
        return;
      } else {
        sendForm(str);
      }
    }
  });
};
const sendForm = (val: string) => {
  form.value.houseImageUrl = val;
  // edit or add
  if (userid.value) {
    updateHouseRental(form.value).then(() => {
      ElMessage.success('编辑成功');
      cancelForm();
    });
  } else {
    addHouseRental({
      ...form.value
    }).then(() => {
      ElMessage.success('添加成功');
      cancelForm();
    });
  }
};
// 推出
const cancelForm = () => {
  router.back();
};
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}
.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;
    .houseDevicesBox {
      display: grid;
      margin-bottom: 20px;
      gap: 10px 20px;
      grid-template-columns: repeat(6, 1fr);
      grid-template-rows: repeat(2, 1fr);
      .houseDevices_Item {
        width: 95px;
        height: 35px;
        background-color: #ccc;
        border-radius: 5px;
        text-align: center;
        line-height: 35px;
        cursor: pointer;
        &.active {
          background-color: rgb(232, 241, 255);
          color: #267cff;
        }
      }
    }
    &: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;
    }
  }
}
</style>
