<template>
  <view class="list_body">
    <view class="box" v-if="showPicker"></view>
    <mx-date-picker
      :show="showPicker"
      :type="type"
      :value="timeValue"
      :show-tips="true"
      :begin-text="'开始'"
      :end-text="'截至'"
      :show-seconds="true"
      @confirm="onSelected"
      @cancel="onSelected"
    />
    <view class="head">
      <image src="../../static/4.png" mode="aspectFit"></image>
      <!-- <text>报修信息表<image src="../../static/pen.svg" mode=""></image></text> -->
    </view>
    <form @submit="formSubmit" @reset="formReset">
      <view class="content">
        <!-- 宿舍楼栋 -->
        <view class="headline-2">
          <text class="uni-list-cell-left-2">宿舍楼栋：</text>
          <view class="uni-list-cell">
            <picker
              class="uni-input-1"
              mode="multiSelector"
              :value="roomIndex"
              :range="room_List"
              @change="bindPickerChange_room"
              @columnchange="handleNum"
            >
              <view class="uni-input" v-if="dormNumber">
                {{ dormNumber }}
              </view>
              <image src="../../static/down.svg" class="uni-list-cell_image"></image>
            </picker>
          </view>
        </view>
        <!-- <hr> -->
        <!-- <view class="line"></view> -->
        <!-- 故障分类 -->
        <view class="headline-2">
          <text class="uni-list-cell-left">故障分类：</text>
          <picker @change="bindPickerChange($event, List)" :value="index" :range="List" :range-key="'faultName'">
            <view class="uni-list-cell-os">
              <view class="uni-list-cell-db">
                <template v-if="List != null" v-model="index">
                  <view class="uni-input-1">
                    {{ pickerData.faultName == undefined ? '' : pickerData.faultName }}
                    <image src="../../static/down.svg" mode=""></image>
                  </view>
                </template>
              </view>
            </view>
          </picker>
        </view>
        <!-- 预约时间 -->
        <view class="headline-2">
          <text class="uni-list-cell-left">预约时间：</text>
          <view style="line-height: 35px" @click="onShowDatePicker('datetime')" class="uni-list-cell-db-2">
            <text style="margin-left: 254rpx">{{ timeValue }}</text>
            <image src="../../static/down.svg" mode="" class="timeimg"></image>
          </view>
        </view>
        <view class="headline-2">
          <text class="uni-list-cell-left">联系电话：</text>
          <view class="uni-list-cell-db-2">
            <input type="number" maxlength="11" class="uni-input-2" v-model="formData.phone" />
          </view>
        </view>
        <!-- 故障原因 -->
        <view class="os-headline-2">
          <text class="os-list-cell-left-2">故障原因：</text>
          <view class="os-list-cell-db-2">
            <!-- <input class="os-input-2" type="text" maxlength=50 v-model="formData.os" /> -->
            <textarea
              @input="sumfrontnum"
              maxlength="50"
              class="os-input-2"
              placeholder="工单描述,50字以内"
              placeholder-style="font-size:24rpx"
            ></textarea>
          </view>
          <view>
            <text class="num">{{ fontnum }}/50</text>
          </view>
        </view>
        <!-- 照片 -->
        <view class="photo">
          <view class="photo-title">上传图片（最多上传3张）：</view>
          <view class="upload-image-view">
            <uni-file-picker
              limit="3"
              :value="imageValue"
              fileMediatype="image"
              :image-styles="imageStyles"
              mode="grid"
              @select="select"
              @delete="handleDelete"
            ></uni-file-picker>
          </view>
        </view>
        <!-- 备注 -->

        <button type="default" class="up" @click="getList">立即提交</button>
      </view>
    </form>
  </view>
</template>

<script>
import * as TranslateImage from '../../utils/imageZip.js'
import '../../static/upload-imgs.css'
import MxDatePicker from '@/components/mx-datepicker'
export default {
  components: {
    MxDatePicker,
  },
  data() {
    return {
      imageStyles: {
        width: 75,
        height: 75,
        border: {
          color: '#ccc',
          width: 1,
          style: 'dashed',
          radius: '5px',
        },
      },
      imageList: [], //保存图片路径集合
      List: [],
      index: '',
      faultName: null,
      pickerData: '',
      buildId: 1,
      floorId: 1,
      roomId: 1,
      formData: {
        phone: '',
        inputphone: '',
        os: '',
      },
      showPicker: false,
      datetime: '',
      rangetime: '',
      type: 'rangetime',
      timeValue: '',
      imgs: null,
      imageValue: [],
      ceshiData1: [],
      Timer: null,
      room_List: [[], [], []],
      roomIndex: null,
      IdList: [],
      IdList2: [],
      count: 0,
      count2: 0,
      dormNumber: null,
      fontnum: 0,
    }
  },
  onLoad() {
    this.getStudentInformation()
    this.getTime()
    this.getfault()
    this.init()
  },

  methods: {
    async init() {
      await this.getbuild()
      await this.getbuildHigh()
      await this.getrooms()
    },
    // 获取学生数据
    getStudentInformation() {
      let res = uni.getStorageSync('student')
      // console.log(res)
      if (res) {
        this.formData.phone = res.studentPhone
        this.formData.inputphone = res.studentOtherPhone
        this.dormNumber = res.dormNumber
      }
    },
    //统计textarea字数
    sumfrontnum(e) {
      console.log(e)
      this.fontnum = e.detail.value.length
    },
    // 初始化时间
    getTime() {
      let date = new Date(),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
        minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
        second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      month >= 1 && month <= 9 ? (month = '0' + month) : ''
      day >= 0 && day <= 9 ? (day = '0' + day) : ''
      let timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      this.datetime = timer
    },

    // 获取故障类型信息
    async getfault() {
      let res = await this.$myRequest({
        method: 'post',
        url: `/fault/queryAllFaultByStatus`,
      })
      // console.log(res)
      this.$nextTick(() => {
        this.List = res.data
      })
    },

    // 获取宿舍楼栋数据
    async getbuild() {
      let res = await this.$myRequest({
        method: 'post',
        url: `/build/queryAllBuild`,
      })
      // console.log(res)
      let tempList = []
      res.data.forEach((item) => {
        tempList.push(item.buildName)
        console.log('bulidid' + item.buildId)
      })
      this.$nextTick(() => {
        this.$set(this.room_List, 0, tempList)
      })
    },

    // 获取宿舍楼层数据
    async getbuildHigh() {
      let res = await this.$myRequest({
        method: 'post',
        url: `/build/queryAllFloorByBuildID?buildId=${this.buildId}`,
      })
      // console.log(res)
      this.room_List[1] = []
      this.room_List[2] = []
      this.IdList = []
      let tempList = []
      res.data.forEach((item) => {
        tempList.push(item.floorName)
        this.IdList.push(item.floorId)
        console.log('floorid' + item.floorId)
      })
      this.$nextTick(() => {
        this.$set(this.room_List, 1, tempList)
        this.floorId = this.IdList[this.count]
      })
    },

    // 获取宿舍房间数据
    async getrooms() {
      let res = await this.$myRequest({
        method: 'post',
        url: `/build/queryAllRoomByFloorID?floorId=${this.floorId}`,
      })
      // console.log(res)
      this.room_List[2] = []
      this.IdList2 = []
      let tempList = []
      res.data.forEach((item) => {
        tempList.push(item.roomName)
        this.IdList2.push(item.roomId)
        console.log('roomid' + item.roomId)
      })
      this.$nextTick(() => {
        this.$set(this.room_List, 2, tempList)
        this.roomId = this.IdList2[this.count2]
      })
    },

    // 时间选择框
    onShowDatePicker(type) {
      this.type = type
      this.showPicker = true
      this.timeValue = this[type]
    },

    // 时间选择框点击回调
    onSelected(e) {
      this.showPicker = false
      if (e) {
        this[this.type] = e.value
        this.timeValue = e.value
      }
    },

    //故障选择
    bindPickerChange(e, storage) {
      this.index = e.target.value
      this.pickerData = storage[this.index] // 这里就是选中的对象
    },

    // 提交订单
    getList() {
      console.log('ppppp' + this.buildId + '-' + this.floorId + '-' + this.roomId)
      // 处理图片参数数据
      this.imgs = this.ceshiData1.join(';')
      // 电话验证规则
      let phoneVer = /^[1][3,4,5,7,8,9][0-9]{9}$/
      // 简单校验
      if (this.pickerData.faultId == null) {
        uni.showToast({
          icon: 'none',
          title: '请选择故障类型',
          duration: 2000,
        })
        return
      }
      if (this.dormNumber == null) {
        uni.showToast({
          icon: 'none',
          title: '请选择楼栋和宿舍号',
          duration: 2000,
        })
        return
      }

      if (!this.timeValue) {
        uni.showToast({
          icon: 'none',
          title: '请选择预期时间',
          duration: 2000,
        })
        return
      }

      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none',
        })
        return
      } else if (!phoneVer.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的联系电话',
          icon: 'none',
        })
        return
      }

      uni.showLoading({
        title: '提交中',
      })

      if (this.Timer != null) {
        clearTimeout(this.Timer)
      }
      this.Timer = setTimeout(async () => {
        let res = await this.$myRequest({
          method: 'post',
          url: `/order/insertOrder`,
          data: {
            faultId: String(this.pickerData.faultId),
            dormNumber: this.dormNumber,
            orderExpectedTime: this.timeValue,
            studentDormitory: this.buildId + '-' + this.floorId + '-' + this.roomId,
            orderImages: this.imgs,
            orderNote: this.formData.os,
            studentPhone: this.formData.phone,
            otherPhone: this.formData.inputphone,
          },
        })
        // console.log(res)
        if (res.status == 200) {
          uni.showToast({
            title: '提交成功',
          })
          uni.reLaunch({
            url: '/pages/home/home',
          })
        } else {
          uni.showToast({
            title: '提交失败',
            icon: 'error',
          })
        }
      }, 1500)
    },

    // 选择图片压缩并上传
    select(e) {
      // console.log('选择文件：', e)
      e.tempFiles.forEach((item) => {
        TranslateImage.translate(item.path, (res) => {
          if (Number(res.size) > 1000000) {
            this.imageValue = []
            uni.showModal({
              content: `图片过大,请重新上传`,
              showCancel: false,
              success() {},
            })
            return
          }
          uni.showLoading({
            title: '上传中',
          })
          uni.uploadFile({
            url: `/baoxiu/repairApi/order/uploadImage`,
            filePath: res.url,
            name: 'orderImages',
            success: (uploadFileRes) => {
              this.ceshiData1.push(JSON.parse(uploadFileRes.data).data)
              const path = item.path
              this.imageValue.push({
                url: path,
                name: '',
              })
              uni.hideLoading()
            },
            fail: () => {
              uni.hideLoading()
            },
          })
        })
      })
    },

    // 删除图片回调
    handleDelete(e) {
      const num = this.imageValue.findIndex((v) => v.path === e.tempFilePath)
      this.imageValue.splice(num, 1)
      this.ceshiData1.splice(num, 1)
    },

    // 三级联动下拉框回调
    bindPickerChange_room(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.roomIndex = e.detail.value
      this.dormNumber =
        this.room_List[0][this.roomIndex[0]] +
        this.room_List[1][this.roomIndex[1]] +
        this.room_List[2][this.roomIndex[2]]
      console.log('mmmmmm' + this.buildId + '-' + this.floorId + '-' + this.roomId)
    },

    // 三级联动下拉框拖动回调
    handleNum(e) {
      console.log('第' + (e.detail.column + 1) + '列' + '第' + (e.detail.value + 1) + '行')
      if (e.detail.column == 0) {
        console.log('楼栋发生变化，当前为' + (e.detail.value + 1) + '栋')
        // if (e.detail.value < 4) {
        this.buildId = e.detail.value + 1
        // } else {
        // this.buildId = e.detail.value + 5
        // }
        // console.log(this.buildId + '-' + this.floorId + '-' + this.roomId)
      } else if (e.detail.column == 1) {
        // console.log("层数发生变化，当前为"+(e.detail.value+1)+"层")
        this.floorId = this.IdList[e.detail.value]
        this.count = e.detail.value
        // console.log(this.buildId + '-' + this.floorId + '-' + this.roomId)
      } else {
        // console.log("房间数发生变化，当前为"+(e.detail.value+1)+"号")
        this.roomId = this.IdList2[e.detail.value]
        this.count2 = e.detail.value
        console.log('zuizong' + this.buildId + '-' + this.floorId + '-' + this.roomId)
      }
    },
  },

  // 监听属性
  watch: {
    buildId: {
      handler() {
        this.getbuildHigh()
      },
    },
    floorId: {
      handler() {
        this.getrooms()
      },
    },
  },
}
</script>

<style lang="scss" scoped>
.list_body {
  height: 100%;
  overflow: hidden;
  background-color: rgba(166, 166, 166, 0.18);
}

.box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 99;
}

.test {
  text-align: center;
  padding: 20rpx 0;
}

button {
  margin: 20rpx;
  font-size: 28rpx;
}

.head {
  height: 550rpx;
  margin-top: -80rpx;
}

.head image {
  width: 100%;
}

.headline-1 {
  font-size: 24rpx;
}

.headline-2 {
  font-size: 24rpx;
  height: 80rpx;
  // margin-top: 0px;
  border-bottom: 2rpx solid rgba(166, 166, 166, 0.18);
}

.content {
  position: relative;
  // width: 720rpx;
  height: 1260rpx;
  margin-top: -152rpx;
  // margin-left: 14rpx;
  // border: 2rpx solid rgba(128, 128, 128, 0.45);
  background-color: rgba(255, 255, 255, 1);
}

.uni-list-cell {
  float: right;
  width: 78%;
  height: 70rpx;
  margin-top: 8rpx;
  // margin-right: 10rpx;
  // border: 2rpx solid gray;
  line-height: 44rpx;
  // border-radius: 16px;
  // background-color: rgba(166, 166, 166, 0.18);
}

.uni-list-cell-os {
  float: right;
  width: 78%;
  height: 70rpx;
  margin-top: 2rpx;
  // margin-right: 10rpx;
  // border: 2rpx solid gray;
  line-height: 44rpx;
  // border-radius: 16px;
  // background-color: rgba(166, 166, 166, 0.18);
}

// .uni-list-cell_image {
// 	float: right;
// 	margin-right: 15rpx;
// 	margin-top: -42rpx;
// 	width: 40rpx;
// 	height: 40rpx;
// 	font-size: 40rpx;
// }

.uni-input-1 {
  position: relative;
  margin-left: 254rpx;
  margin-top: 14rpx;
  height: 50rpx;
}

.uni-input-1 image {
  position: absolute;
  right: 10rpx;
  top: 5rpx;
  // float: right;
  // margin-right: 10rpx;
  // // margin-top: -10rpx;
  width: 40rpx;
  height: 40rpx;
  font-size: 40rpx;
}

.uni-list-cell-left {
  float: left;
  margin-top: 26rpx;
  margin-left: 30rpx;

  text {
    color: red;
  }
}

.uni-list-cell-left-2 {
  float: left;
  margin-left: 30rpx;
  margin-top: 26rpx;

  text {
    color: red;
  }
}

.uni-list-cell-db-2 {
  position: relative;
  float: right;
  // margin-right: 10rpx;
  margin-top: 6rpx;
  width: 78%;
  height: 70rpx;
  // border: 2rpx solid gray;
  // border-radius: 16px;
  // background-color: rgba(166, 166, 166, 0.18);
}

.uni-input-2 {
  margin-left: 334rpx;
  margin-top: 16rpx;
  font-size: 24rpx;
}

.uni-input-2 image {
  float: right;
  margin-right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  font-size: 40rpx;
}

.timeimg {
  position: absolute;
  right: 9rpx;
  top: 16rpx;
  width: 40rpx;
  height: 40rpx;
  font-size: 40rpx;
}

.photo {
  height: 340rpx;
  font-size: 24rpx;
}

.photo-title {
  float: left;
  margin-left: 26rpx;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.upload-image-view {
  /* height: 300px; */
}

.image {
  float: left;
  margin-left: 26rpx;
  margin-top: 30rpx;
  height: 396rpx;
  width: 644rpx;
  box-sizing: border-box;
  border-radius: 28rpx;
  background-color: rgba(166, 166, 166, 0.18);
}

.imageText {
  text-align: center;
  border-radius: 28rpx;
  width: 100%;
  height: 100%;
  background-color: rgba(166, 166, 166, 0.18);
}

.imgSrc image {
  width: 646rPX;
  height: 386rpx;
}

.os-headline-2 {
  position: relative;
  float: left;
}

.os-list-cell-left-2 {
  float: left;
  margin-left: 26rpx;
  margin-top: 25rpx;
  font-size: 24rpx;
}

.os-input-2 {
  margin-left: 10rpx;
  margin-top: 12rpx;
  width: 97%;
  font-size: 28rpx;
  line-height: 100%;
}

.os-list-cell-db-2 {
  float: right;
  width: 720rpx;
  height: 200rpx;
  margin-left: -130rpx;
  margin-top: 64rpx;
  border-radius: 16rpx;
  // border: 2rpx solid gray;
  // background-color: rgba(166, 166, 166, 0.18);
}

.os-headline-2 .num {
  position: absolute;
  top: 210rpx;
  right: 20rpx;
  font-size: 24rpx;
}

.up {
  position: absolute;
  bottom: 200rpx;
  left: 18%;
  line-height: 72rpx;
  width: 60%;
  height: 36px;
  background-color: rgba(42, 130, 228, 1);
  color: white;
  font-size: 14px;
  border-radius: 14px;
}

.example-body {
  padding: 10px;
  padding-top: 0;
}

.custom-image-box {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
  color: #333;
}

.time {
  margin-top: 350rpx;
  font-size: 24rpx;
  margin-left: 26rpx;
}

.time-input {
  position: relative;
  margin-top: -44rpx;
  margin-left: 135rpx;
  /* margin-right: 137px; */
  width: 300rpx;
  border: 2rpx solid gray;
}
</style>
