<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.getbuild()
    this.getbuildHigh()
    this.getrooms()
  },

  methods: {
    // 获取学生数据
    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/index/index',
          })
        } 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>

<template>
  <view class="form">
    <view class="form_item flex items-center justify-between">
      <span>宿舍楼栋：</span>
      <span v-if="dormNumber">
        {{ dormNumber }}
      </span>
      <span v-else>请选择</span>

      <picker
        class="picker flex justify-end items-center"
        mode="multiSelector"
        :value="roomIndex"
        :range="room_List"
        @change="bindPickerChange_room"
        @columnchange="handleNum"
      >
        <image src="../../static/down.svg"></image>
      </picker>
    </view>
    <view class="form_item flex items-center justify-between">
      <span>故障分类：</span>
      <span v-if="List != null">
        {{ pickerData.faultName == undefined ? '' : pickerData.faultName }}
      </span>
      <picker
        class="picker flex justify-end items-center"
        @change="bindPickerChange($event, List)"
        :value="index"
        :range="List"
        :range-key="'faultName'"
      >
        <image src="../../static/down.svg"></image>
      </picker>
    </view>
    <view class="form_item flex items-center justify-between">
      <span>预约时间：</span>
      <span>{{ timeValue || '请选择' }}</span>
      <view class="picker flex justify-end items-center" @click="onShowDatePicker('datetime')">
        <image src="../../static/down.svg"></image>
      </view>
    </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="form_item flex items-center justify-between">
      <span>联系电话：</span>
      <input type="number" maxlength="11" class="flex-1" v-model="formData.phone" />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.form {
  width: 100%;
  padding: 20rpx;
  &_item {
    height: 80rpx;
    border-bottom: 1px solid rgba(166, 166, 166, 0.18);
  }
  .picker {
    flex: 1;
    width: 400rpx;
  }
  image {
    max-width: 40rpx;
    max-height: 40rpx;
  }
}
</style>
