<template>
  <view class="main">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      right-icon="scan"
      title="申请报修"
      @clickLeft="back"
      @clickRight="HandlScanCode"
    >
    </uni-nav-bar>
    <view>
      <!-- <CellTip title="基本信息" /> -->
      <!-- <Cell cellType="more" title="选择设备">
				<view class="cell-tip-right" slot="more">
					<input type="text" :placeholder="repairList.length!==0?'已选设备':'请选择设备'" disabled @click="handleClick"
						style="font-size: 28rpx;text-align: right;" placeholder-style="color:#999">
				</view>
			</Cell> -->
      <Cell cellType="more" title="设备编号" @click="handleClick">
        <view class="cell-tip-right" slot="more">
          <!-- <input  type="text" placeholder="请输入" v-model="form.equiCode"
						placeholder-style="color:#999" style="font-size: 28rpx; text-align: right" /> -->
          {{ form.equiCode || '请输入' }}
        </view>
      </Cell>
      <Cell cellType="more" title="设备名称">
        <view class="cell-tip-right" slot="more">
          {{ form.equiName }}
        </view>
      </Cell>
      <Cell cellType="more" title="设备型号">
        <view class="cell-tip-right" slot="more">
          {{ form.equiModel }}
        </view>
      </Cell>
      <Cell cellType="more" title="设备位置">
        <view class="cell-tip-right" slot="more">
          {{ form.equiLocation }}
        </view>
      </Cell>
    </view>

    <view class="bxjlbh-wrap">
      <view class="item">
        <view class="label"> 报修记录编号 </view>
        <view class="value-wrap text">
          {{ form.repairsCode }}
        </view>
      </view>
      <view class="item">
        <view class="label"> 接收人 </view>
        <view class="value-wrap">
          <scroll-view
            class="jsr-wrap"
            scroll-x="true"
            v-if="form.receiveUserList.length > 0"
          >
            <view
              class="jsr-item"
              v-for="item in form.receiveUserList"
              :key="item.userId"
            >
              <view class="jsr-item-wrap">
                <view class="labels">
                  {{ item.trueName }}
                </view>
                <u-icon
                  name="minus-circle-fill"
                  @click="deletJsr(item)"
                ></u-icon>
              </view>
            </view>
          </scroll-view>
          <view class="jsr" v-else> 请选择接收人 </view>
          <view class="addjsr" @click="handlselectUser">
            <u-icon name="plus"></u-icon>
          </view>
        </view>
      </view>
      <view class="item">
        <view class="label"> 期望完成时间 </view>
        <view class="value-wrap">
          <uni-datetime-picker
            type="datetime"
            class="picker"
            v-model="form.expectedTime"
            @change="confirm"
          >
            {{ showTime }}
          </uni-datetime-picker>
        </view>
      </view>
    </view>
    <view class="gzms-wrap">
      <view class="title"> 故障描述 </view>
      <u--textarea
        v-model="form.repairsDescription"
        class="border"
        maxlength="500"
        placeholder="请输入内容"
        count
      ></u--textarea>
    </view>
    <view class="sc-wrap">
      <view class="title"> 相关照片 </view>
      <uni-file-picker
        :limit="4"
        v-model="FileImgList"
        fileMediatype="image"
        mode="grid"
        @select="handlImageSelect"
        @delete="handlImagDeletee"
      />
    </view>
    <selectUser ref="select_user" @submit="cbSelectUser"></selectUser>
    <view class="footer">
      <text @click="updateparam">报修</text>
    </view>
  </view>
</template>

<script>
import CellTip from '@/components/CellTip.vue'
import Cell from '@/components/Cell.vue'
import { postJ, get } from '@/utils/api.js'
import { getRuleNo } from '@/utils/utils.js'
import selectUser from '../selectUser/index.vue'
import dayjs from 'dayjs'
export default {
  components: {
    CellTip,
    Cell,
    selectUser
  },
  data () {
    return {
      form: {
        // 设备id
        equiId: '',
        // 设备编码
        equiCode: '',
        // 设备名称
        equiName: '',
        // 设备型号
        equiModel: '',
        // 设备位置
        equiLocation: '',
        // 期望完成时间
        expectedTime: '',
        // 报修记录编号
        repairsCode: '',
        // 故障描述
        repairsDescription: '',
        // 上传图片
        repairsImg: [],
        // 接收人
        receiveUserList: [],
        // 工单id
        workCenterId: ''
      },
      // 选择的图片
      FileImgList: [],
      showTime: '请选择期望完成时间',
      // 条码数据
      qrContent: null,
      barType: '',
      // 设备详情
      equipmentInfo: ''
    }
  },
  onShow () {
    // if (this.$store.state.repair.selectEqui.length > 0) {
    // 	let data = this.$store.state.repair.selectEqui[0]
    // 	this.setEquipment(data)
    // }
    let _this = this
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', function (data) {
      _this.cbScancodedate(data)
    })

    // 手动选择设备
    uni.$off('selectEqui')
    uni.$on('selectEqui', async function (data) {
      console.log(data)
      if (data.length > 0) {
        await _this.getEquipmentInfo(data[0].id)
        _this.setEquipment()
      }
    })
  },

  onHide () {
    uni.$off('scancodedate')
  },
  onUnload () {
    uni.$off('scancodedate')
  },
  onLoad (data) {
    let workOrderId = data.workOrderId
    if (workOrderId) {
      this.form.maintainWorkOrderId = +workOrderId
    }
    if (data?.workOrderCode) {
      this.form.sourceCode = data.workOrderCode
    }
    if (data.source) {
      //1:手动创建;2:工单反工;3:告警通知;4:保养工单;5:巡点检工单  不传默认1
      const enums = {
        1: 'MANUAL_OPERATION',
        2: 'WORK_ORDER',
        3: 'ALTERING',
        4: 'MAINTAIN',
        5: 'CHECK_OBO'
      }
      this.form.source = enums[data.source]
    }
    if (data) {
      this.form.equiId = data.equiId
      this.form.equiCode = data.equiCode
      this.form.equiName = data.equiName
      this.form.equiModel = data.equiModel
      this.form.equiLocation = Boolean(data.equiLocation)
        ? data.equiLocation
        : ''
    }
    this.setRepairsCode()
  },
  methods: {
    confirm (e) {
      this.showTime = dayjs(e).format('YYYY-MM-DD HH:mm:ss')
    },
    // 选择设备
    handleClick () {
      uni.navigateTo({
        url: '../select_repair/index'
      })
    },
    // 生成报修记录编号
    setRepairsCode () {
      this.form.repairsCode = getRuleNo('B')
    },
    // 设置设备信息
    setEquipment () {
      let data = this.equipmentInfo
      this.form.equiId = data.id
      this.form.equiCode = data.assetCode
      this.form.equiName = data.assetName
      this.form.equiModel = data.information.modelType || ''
      this.form.equiLocation = this.initDetailLocation(
        `${data.factoryName}/${data.workshopName}/${data.lineName}/${data.detailLocation}`
      )
    },
    // 设备位置
    initDetailLocation (val) {
      console.log(val)
      let list = String(val)
        .split('/')
        .filter(n => {
          return n !== 'null'
        })
      return list.join('/')
    },
    // 报修
    async updateparam () {
      if (!this.form.equiCode) {
        uni.showToast({
          title: '设备编号不能为空',
          icon: 'none'
        })
        return
      } else if (!this.form.expectedTime) {
        uni.showToast({
          title: '期望完成时间不能为空',
          icon: 'none'
        })
        return
      }
      uni.showLoading({
        title: '加载中'
      })
      let param = JSON.parse(JSON.stringify(this.form))

      param.receiveUserList = param.receiveUserList.map(n => {
        return {
          receiveUserId: n.userId,
          receiveUserName: n.trueName,
          deptName: n.deptName
        }
      })
      let repairsImg = param.repairsImg.map(n => {
        return n.url
      })
      param.repairsImg = repairsImg.join(',')
      param.expectedTime = this.showTime
      postJ(this.apiUrl + '/repair/info/saveOrEdit', param).then(res => {
        if (res.success) {
          uni.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            this.back()
          }, 2000)
        }
      })
    },

    // 选择图片
    async handlImageSelect (e) {
      let element = e.tempFiles[0]
      let url = await this.uploadFiles(element.path)
      console.log(url)
      if (url) {
        element.url = url
        this.form.repairsImg.push(element)
      }
    },
    // 图片删除
    handlImagDeletee (e) {
      let index = this.form.repairsImg.findIndex(n => {
        return n.uuid == e.tempFile.uuid
      })
      if (index !== -1) {
        this.form.repairsImg.splice(index, 1)
      }
    },
    // 文件上传
    uploadFiles (tempFilePaths) {
      let that = this
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.apiUrl + '/data/doc/add', //后端用于处理图片并返回图片地址的接口
          filePath: tempFilePaths,
          name: 'file',
          header: that.header,
          formData: {
            module: '申请报修'
          },
          success: res => {
            let data = JSON.parse(res.data) //返回的是字符串，需要转成对象格式
            resolve(data.data.accessUrl)
          },
          fail: err => {
            reject(null)
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }
        })
      })
    },
    // 打开用户选择
    handlselectUser () {
      this.$refs.select_user.open()
    },
    cbSelectUser (val) {
      let result = this.form.receiveUserList.find(el => {
        return el.userId == val.userId
      })
      if (!result) {
        this.form.receiveUserList.push(val)
      }

      this.$refs.select_user.close()
    },
    // 删除接收人
    deletJsr (item) {
      let s = this.form.receiveUserList.findIndex(n => {
        return n.userId == item.userId
      })
      if (s !== -1) {
        this.form.receiveUserList.splice(s, 1)
      }
    },
    formatTime (format) {
      var args = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        'h+': this.getHours(),
        'm+': this.getMinutes(),
        's+': this.getSeconds()
      }
      if (/(y+)/.test(format))
        format = format.replace(
          RegExp.$1,
          (this.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (var i in args) {
        var n = args[i]
        if (new RegExp('(' + i + ')').test(format))
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1 ? n : ('00' + n).substr(('' + n).length)
          )
      }
      return format
    },
    // 相机扫码
    HandlScanCode () {
      let _this = this
      uni.scanCode({
        success: function (res) {
          _this.Scancodedate(res.result)
        }
      })
    },
    // 扫码枪扫码
    cbScancodedate (data) {
      this.Scancodedate(data.code)
    },
    Scancodedate (code) {
      this.qrContent = code.trim()
      //this.qrContent = '005/w01000001120041/锤锤专用02-不拆包-批量/规格01//成型/成型工序@_@0'
      this.barType = this.setBarType(this.qrContent)
      this.getData()
    },
    // 根据条码请求设备数据
    getData () {
      let par = {
        barType: this.barType,
        qrContent: this.qrContent
      }
      postJ(this.apiUrl + '/scan/getAssetInfo', par).then(res => {
        this.equipmentInfo = res.data
        this.setEquipment()
      })
    },
    // 设置barType
    setBarType (val) {
      let index = val.indexOf('@_@')
      let result = 0
      if (index !== -1) {
        let item = val.substr(index + 3, 1)
        if (item) {
          result = Number(item)
        }
      }
      return result
    },
    // 请求设备详情
    getEquipmentInfo (id) {
      let par = {
        id
      }
      return get(this.apiUrl + '/asset/detail', par).then(res => {
        this.equipmentInfo = res.data
      })
    }
  }
}
</script>

<style scoped lang="scss">
.jsr {
  color: #999999;
  font-size: 32rpx;
}

.equiDetails {
  .list {
    border-bottom: none;
  }
}

.btn-status {
  padding: 0 20rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: $uni-font-size-base;

  .icon-shangchuanzhaopian {
    font-size: 60rpx;
    color: $uni-text-color-grey;
  }
}

.select-right {
  float: right;
}

.no_data {
  margin-top: 120rpx;

  .center {
    text-align: center;
    color: #555;
    font-size: $uni-font-size-base;
  }
}

.sparePartsList {
  .title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-top: 20rpx;
  }

  .list {
    // padding: 10rpx 20rpx;
    color: $uni-text-color-grey;
    font-size: $uni-font-size-base;
    line-height: 1.5;

    .list-cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5rpx 20rpx;
    }

    .font-sm {
      font-size: $uni-font-size-sm;
    }

    .font-text {
      color: $uni-text-color;
    }
  }
}

//底部按钮
.footer {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  text-align: center;
  position: fixed;

  // text {
  // 	width: 100%;
  // 	background-color: $j-primary-green;
  // 	font-size: 34rpx;
  // 	color: #FFFFFF;
  // 	line-height: 100rpx;
  // }

  text {
    width: 100%;
    background-color: $j-primary-green;
    font-size: 34rpx;
    color: #ffffff;
    line-height: 100rpx;
  }
}

.p100 {
  padding-bottom: 100rpx;
}

.equi-right {
  // float: right;
  position: absolute;
  background-color: $j-primary-green;
  // font-size: 34rpx;
  width: 140rpx;
  text-align: center;
  padding: 10rpx 0;
  border-radius: 5px;
  color: #ffffff;
  right: 20rpx;
}

.bxjlbh-wrap {
  padding: 0 20rpx;
  margin-top: 20rpx;

  .item {
    height: 60rpx;
    display: flex;
    border: 1px solid #d7d7d7;

    & + .item {
      margin-top: 20rpx;
    }

    .label {
      width: 200rpx;
      height: 100%;
      line-height: 60rpx;
      text-align: center;
      background: #d7d7d7;
      font-size: 32rpx;
      color: rgb(62, 62, 62);
    }

    .value-wrap {
      flex: 1;
      display: flex;
      align-items: center;
      padding-left: 10px;
      position: relative;

      &.text {
        background: #f2f2f2;
        font-size: 32rpx;
      }

      .picker {
        width: 100%;
        color: rgb(153, 153, 153);
        font-size: 32rpx;
      }
    }
  }
}

.gzms-wrap {
  padding: 0 15px;
  margin-top: 15px;

  .title {
    margin-bottom: 7px;
    font-size: 32rpx;
  }

  .textarea {
    border: 1px solid #d8d8d8;
    width: 100%;
    box-sizing: border-box;
    height: 400px;
  }
}

.sc-wrap {
  .title {
    margin-bottom: 7px;
    font-size: 32rpx;
  }

  padding: 0 15px;
  margin-top: 15px;
}

.pop-bar {
  min-height: 100px;
  background: #ffffff;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
}

.jsr-wrap {
  white-space: nowrap;
  width: 400rpx;

  .jsr-item {
    display: inline-block;

    .jsr-item-wrap {
      display: flex;

      .labels {
        display: inline-block;
        font-size: 28rpx;
        color: #3e3e3e;
        background: #d7d7d7;
        padding: 5rpx 10rpx;
      }
    }

    & + .jsr-item {
      margin-left: 20rpx;
    }
  }
}

.addjsr {
  position: absolute;
  top: 0;
  right: 0;
  width: 70rpx;
  height: 100%;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main {
  padding-bottom: 130rpx;
}

.border {
  border: 1px solid #eee;
}
</style>
