<template>
  <view class="container">
    <view class="form-container">
      <view class="form-item" @click="showRoom = true">
        <text class="label">选择地址</text>
        <view class="value-with-arrow">
          <text>{{ address }}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
      <view class="form-item" @click="showCate = true">
        <text class="label">报修类型</text>
        <view class="value-with-arrow">
          <text>{{ category || '请选择' }}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
      <view class="form-item" @click="showTime = true">
        <text class="label">预约时间</text>
        <view class="value-with-arrow">
          <text>{{ time || '请选择' }}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
      <view class="form-item">
        <text class="label">联系方式</text>
        <input v-model="phone" placeholder="请输入手机号" style="text-align: right"/>
      </view>

      <view class="form-item-column">
        <text class="label">问题描述</text>
        <textarea class="textarea" v-model="description" placeholder="请详细描述您遇到的问题"
                  placeholder-class="placeholder"/>
      </view>
      <view class="form-item-column">
        <text class="label">上传图片 (可选)</text>
        <view class="image-uploader">
          <view class="image-list">
            <view class="image-item" v-for="(image, index) in imageList" :key="index">
              <image :src="image" mode="aspectFill" @click="previewImage(index)"></image>
              <view class="delete-icon" @click="deleteImage(index)">x</view>
            </view>
            <view class="add-btn" @click="chooseImage" v-if="imageList.length < 3">+</view>
          </view>
        </view>
      </view>
    </view>

    <view class="button-container">
      <button class="submit-button" @click="submit">提交报修</button>
    </view>
    <u-picker :show="showRoom" :columns="[roomList]" keyName="title" @confirm="selectRoom"
              @cancel="showRoom = false"/>
    <u-picker :show="showCate" :columns="[categoryList]" keyName="dictDataCode" @confirm="selectCate"
              @cancel="showCate = false"/>
    <u-datetime-picker
      :show="showTime"
      v-model="timeValue"
      mode="datetime"
      @confirm="timeConfirm"
      @cancel="showTime = false"
    ></u-datetime-picker>
  </view>
</template>

<script>
import {userRoomListReq} from "@/api/room";
import {addRepair} from "@/api/repair";
import {chooseImg} from "@/util";
import {userInfoReq} from "@/api/user";
import {dictDataReq} from "@/api/common";

export default {
  data() {
    return {
      address: '',
      time: '',
      timeValue: Number(new Date()),
      description: '',
      imageList: [],
      roomList: [],
      currentRoom: null,
      showRoom: false,
      showTime: false,
      showCate: false,
      phone: '',
      category: '',
      categoryList: []
    }
  },
  methods: {
    async getRoomList() {
      const {data} = await userRoomListReq()
      this.roomList = data.map(item => {
        item.title = ''
        if (item.villageName) item.title += item.villageName
        if (item.buildingName) item.title += `-${item.buildingName}`
        if (item.unitName) item.title += `-${item.unitName}`
        if (item.roomNumber) item.title += `-${item.roomNumber}`
        return item
      })
      if (this.roomList.length) {
        this.currentRoom = this.roomList[0]
        this.address = this.currentRoom.title
      }
    },
    async getCate(){
      const {data} = await dictDataReq({dictId: '1436'})
      this.categoryList = data
      this.category = this.categoryList[0].dictDataCode
    },
    timeConfirm(e) {
      this.showTime = false
      const date = new Date(e.value)
      this.time = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    async chooseImage() {
      uni.showLoading({
        title: '上传中...',
      })
      const res = await chooseImg(9 - this.imageList.length)
      res.forEach(item => {
        this.imageList.push(item.path)
      })
      uni.hideLoading()
    },
    previewImage(index) {
      uni.previewImage({
        urls: this.imageList,
        current: index
      });
    },
    deleteImage(index) {
      this.imageList.splice(index, 1);
    },
    selectRoom({value}) {
      this.currentRoom = value[0]
      this.address = this.currentRoom.title
      this.showRoom = false
    },
    selectCate({value}) {
      this.category = value[0].dictDataCode
      this.showCate = false
    },
    async submit() {
      if (!this.description) {
        uni.showToast({title: '请输入问题描述', icon: 'none'});
        return;
      }
      if (!this.phone) {
        uni.showToast({title: '请输入联系方式', icon: 'none'});
        return;
      }
      if (!this.currentRoom) {
        uni.showToast({title: '请选择地址', icon: 'none'});
        return;
      }
      if (!this.time) {
        uni.showToast({title: '请选择预约时间', icon: 'none'});
        return;
      }
      uni.showToast({title: '提交成功', icon: 'success'});
      await addRepair({
        roomCode: this.currentRoom.baseRoomRoomCode,
        description: this.description,
        appointmentTime: this.time,
        phone: this.phone,
        category: this.category,
        images: this.imageList.length ? JSON.stringify(this.imageList) : null
      })
      setTimeout(() => uni.navigateBack(), 1500);
    },
    async getUserData() {
      const {data} = await userInfoReq()
      this.phone = data.phone
    },
  },
  onShow() {
    this.getRoomList()
    this.getUserData()
    this.getCate()
  },
}
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;
}

.form-item, .form-item-column {
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 28rpx;

  &:last-child {
    border-bottom: none;
  }
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item-column {
  display: flex;
  flex-direction: column;

  .label {
    margin-bottom: 20rpx;
  }
}

.label {
  color: #333;
}

.value-with-arrow {
  display: flex;
  align-items: center;
  color: #333;

  uni-icons {
    margin-left: 10rpx;
  }
}

.textarea {
  width: 100%;
  height: 200rpx;
  font-size: 28rpx;
}

.placeholder {
  color: #999;
}

.image-uploader {
  .image-list {
    display: flex;
    flex-wrap: wrap;
  }

  .image-item {
    position: relative;
    width: 150rpx;
    height: 150rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;

    image {
      width: 100%;
      height: 100%;
      border-radius: 10rpx;
    }

    .delete-icon {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      width: 30rpx;
      height: 30rpx;
      background: red;
      color: white;
      border-radius: 50%;
      text-align: center;
      line-height: 30rpx;
      font-size: 20rpx;
    }
  }

  .add-btn {
    width: 150rpx;
    height: 150rpx;
    border: 1px dashed #ccc;
    border-radius: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 60rpx;
    color: #ccc;
  }
}

.button-container {
  margin-top: 40rpx;
}

.submit-button {
  background-color: #007aff;
  color: #fff;
  border-radius: 50rpx;
}
</style>
