<template>
  <view>
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="保养工单缺陷"
      @clickLeft="back"
    ></uni-nav-bar>
    <view class="page-bottom-padding">
      <CellInfo label="设备名称" :value="equiName"></CellInfo>
      <CellInfo label="设备编码" :value="equiCode"></CellInfo>
      <CellInfo label="巡点检事项" :value="content"></CellInfo>
      <CellTip title="紧急程度"></CellTip>
      <Cell cellType="more" title="维修工单名称">
        <view class="cell-tip-right" slot="more">
          <input
            type="text"
            placeholder="请输入维修工单名称"
            v-model="form.repairName"
            style="font-size: 28rpx; text-align: right"
          />
        </view>
      </Cell>
      <Cell cellType="more" title="执行部门">
        <view class="cell-tip-right" slot="more">
          <view class="" @click="selectDept('pickerDept', 1)">
            <text>{{ form.executeDeptName }}</text>
            <text class="iconfont icon-youjiantou"></text>
          </view>
        </view>
      </Cell>
      <Cell cellType="more" title="执行人">
        <view class="cell-tip-right" slot="more">
          <view class="" @click="selectDept('pickerUser', 2)">
            <text>{{ form.executeUserName }}</text>
            <text class="iconfont icon-youjiantou"></text>
          </view>
        </view>
      </Cell>
      <Cell cellType="more" title="期望完成时间" @click="showCalendar">
        <view class="cell-tip-right" slot="more">
          <uni-datetime-picker v-model="form.expectDoneTime" @change="confirm"
            >{{ showTime }}
          </uni-datetime-picker>
          <!-- <uni-datetime-picker type="datetime" v-model="datetimesingle" @change="changeLog" /> -->
          <!-- <view class="span">{{expectCompleteTime}}<text class="iconfont icon-youjiantou"></text> </view> -->
        </view>
      </Cell>
      <Cell cellType="more" title="紧急程度">
        <view class="cell-tip-right" slot="more" v-if="pageType !== 'details'">
          <picker
            @change="bindPickerChange"
            :value="degreeIndex"
            :range="degreeList"
            range-key="value"
          >
            <view class="span"
              >{{ degreeList[degreeIndex].value
              }}<text class="iconfont icon-youjiantou"></text
            ></view>
          </picker>
        </view>
        <view class="cell-tip-right" slot="more" v-else>
          <view class="span"
            >{{ degree }}<text class="iconfont icon-youjiantou"></text
          ></view>
        </view>
      </Cell>
      <CellTip title="缺陷描述与意见">
        <!-- <view class="cell-tip-right btn-span" v-if="pageType !== 'details'">
					引用
				</view> -->
      </CellTip>
      <view class="remark">
        <view
          class="title"
          v-if="remark_list.length == 0 && pageType !== 'details'"
        >
          <label>点击下面的加号，添加缺陷描述与意见</label>
        </view>
        <view v-for="(item, index) in remark_list" :key="index">
          <view class="reason-list">
            <label>缺陷{{ index + 1 }}描述：</label>
            <input v-model="item.description" placeholder="请输入" />
          </view>
          <view class="reason-list">
            <label>处理{{ index + 1 }}意见：</label>
            <input v-model="item.opinion" placeholder="请输入" />
          </view>
        </view>
        <u-upload
          v-if="pageType === 'details'"
          :fileList="fileList1"
          name="1"
          multiple
          :maxCount="fileList1.length"
          :previewImage="true"
          :deletable="false"
          width="98"
          height="98"
        >
        </u-upload>
        <view class="option-title" v-if="pageType !== 'details'">
          <!-- 	<view class="border-title" @click="add_opinion">
						<label class="iconfont icon-jiahao"></label>
					</view> -->
          <u-upload
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="3"
            width="98"
            height="98"
            style="margin: 0 30rpx 0"
          ></u-upload>
        </view>
      </view>
      <!-- 选择设备 -->
      <template>
        <CellTip title="选择备件">
          <view
            class="cell-tip-right btn-span"
            @click="goSparepart"
            v-if="pageType !== 'details'"
          >
            选择备品备件
          </view>
        </CellTip>
        <view
          class="content-number border-bottom"
          v-for="(item, index) in sparepartList"
          :key="index"
        >
          <view class="content">
            <view class="">
              <text>{{ item.code }}/</text>
              <text class="font-grey">{{ item.name }}</text>
              <!-- <text class="btn-span"
								:class="item.status.id == '1' ? 'btn-warning': 'btn-primary'">{{item.status.name}}</text> -->
            </view>
          </view>
          <view class=""> x{{ item.num }} </view>
        </view>
        <view class="list-none" v-if="sparepartList.length === 0">
          <u-empty mode="data"></u-empty>
        </view>
      </template>

      <!-- 查看详情 -->
      <template v-if="pageType === 'details'">
        <CellTip title="处理结果"> </CellTip>
        <Cell title="已解决/未解决转报修"></Cell>
      </template>
    </view>

    <view class="footer" v-if="pageType !== 'details'">
      <text @click="updateparam(3)">已消缺</text>
      <text @click="updateparam(2)">报修</text>
    </view>
    <!-- <u-calendar :show="calendarShow" mode="single" :closeOnClickOverlay="true" @confirm="confirm"
			@close="calendarShow = false">
		</u-calendar> -->
    <uni-data-picker
      ref="pickerDeptName"
      @change="handleChange($event, 1)"
      :localdata="treeList"
      :map="{ text: 'name', value: 'code' }"
      v-show="pickerDeptShow"
      @popupclosed="pickerDeptShow = false"
    >
    </uni-data-picker>
    <uni-data-picker
      ref="pickerUserName"
      @change="handleChange($event, 2)"
      :localdata="userList"
      :map="{ text: 'name', value: 'id' }"
      v-show="pickerUserShow"
      @popupclosed="pickerUserShow = false"
    >
    </uni-data-picker>
    <!-- <uni-popup ref="popup">
			<view class="popupInfo">
				<uni-data-picker :localdata="treeList" :map="{text:'name','value':'code'}"></uni-data-picker>
			</view>
		</uni-popup> -->
  </view>
</template>
<script>
import { get, postJ, post } from '@/utils/api.js'
import { degreeList } from '@/utils/common.js'
import { upload } from '@/utils/upload_serve.js'
import Cell from '@/components/Cell.vue'
import CellTip from '@/components/CellTip.vue'
import CellInfo from '@/components/CellInfo.vue'
import SparepartForm from './SparepartForm.vue'
export default {
  components: {
    Cell,
    CellInfo,
    CellTip,
    SparepartForm
  },
  data () {
    return {
      form: {
        repairName: '',
        executeDeptName: '请选择执行部门',
        executeDeptCode: '',
        executeUserId: '',
        executeUserName: '请选择执行人',
        expectDoneTime: Date.now(),
        content: '',
        urgent: 1,
        equiList: []
        // repairAmountSum:1
      },
      pickerDeptShow: false,
      pickerUserShow: false,
      pageId: '',
      parentsId: '',
      worksheetInfo: null,
      equiName: '',
      equiCode: '',
      content: '',
      remark_list: [
        {
          description: '',
          opinion: ''
        }
      ],
      fileList1: [],
      opinion: '',
      degree: '',
      expectCompleteTime: '',
      showTime: '请选择期望完成时间',
      sparepartList: [],
      pageType: '',
      degreeList: degreeList,
      degreeIndex: 0,
      calendarShow: false,
      treeList: [],
      userList: []
    }
  },
  onLoad (option) {
    this.equiName = option.equiName
    this.pageId = option.id
    this.bizEquiId = option.bizEquiId
    this.ruleItemId = option.ruleItemId
    this.equiCode = option.equiCode
    this.cycleValue = option.cycleValue
    this.cycleType = this.getEnumeration(option.cycleType)
    this.content = `${this.cycleValue}${this.cycleType}${this.cycleValue}次`
    this.getInfo()
    //详情页面 不可编辑
    // if (this.pageType === 'details') {
    // 	this.getFlawInfo();
    // }
  },
  onShow () {
    this.sparepartList = this.$store.state.maintenance.sparepart
      ? this.$store.state.maintenance.sparepart
      : []

    if (this.worksheetInfo) {
      // this.form.equiList = this.worksheetInfo.equiList.filter(item => item.id == this.bizEquiId)
      // this.form.equiList.forEach(item => {
      // 	delete
      // 	delete item.ruleItems
      // })
      // this.form.equiList[0].sparepart = this.sparepartList.map(item => {
      // 	return {
      // 		bizEquiId: this.bizEquiId,
      // 		code: item.code,
      // 		model: item.model,
      // 		name: item.name,
      // 		num: item.num,
      // 		unit: item.unit
      // 	}
      // })
      // this.getInfo();
    }
  },
  methods: {
    selectDept (name, type) {
      if (type === 2) {
        if (!this.form.executeDeptCode) {
          uni.showToast({
            title: '请选择执行部门',
            icon: 'none'
          })
          return
        }
        if (this.userList.length === 0) {
          uni.showToast({
            title: `${this.form.executeDeptName}没有执行人`,
            icon: 'none'
          })
          return
        }
      }
      this[`${name}Show`] = true
      this.$refs[`${name}Name`].show()
    },
    handleChange (e, type) {
      let data = e.detail.value[e.detail.value.length - 1]
      if (type === 1) {
        // 获取最后一个节点部门
        let data = e.detail.value[e.detail.value.length - 1]
        this.form.executeDeptCode = data.value
        this.form.executeDeptName = data.text
        this.getUserInfo()
      } else {
        this.form.executeUserId = data.value
        this.form.executeUserName = data.text
        // console.log(e)
      }
    },
    getUserInfo () {
      postJ(this.apiUrl + '/main/user/users', {
        deptCode: this.form.executeDeptCode
      }).then(res => {
        if (res.success) {
          this.userList = res.data
        }
        // console.log(this.userList)
      })
    },
    getEnumeration (type) {
      switch (type) {
        case 'HOUR':
          return '小时'
        case 'DAY':
          return '天'
        case 'WEEK':
          return '周'
        case 'MONTH':
          return '月'
        case 'YEAR':
          return '年'
        default:
          console.log(type)
          break
      }
    },
    // 获取部门
    getDeptTree () {
      get(this.apiUrl + '/main/org/dept/effectiveTree').then(res => {
        if (res.success) {
          this.treeList = res.data
        }
      })
    },
    //获取信息
    getInfo () {
      get(this.apiUrl + '/maintain/order/getDetail/' + this.pageId).then(
        res => {
          let worksheetInfo = res.data
          this.worksheetInfo = worksheetInfo
          let arr = this.worksheetInfo.equiList.filter(
            item => item.id == this.bizEquiId
          )
          this.sparepartList = arr && arr.length !== 0 ? arr[0].spareParts : []
          this.getDeptTree()
          // let details = worksheetInfo.details;
          // let isDom = null;
          // let isDetails = null;
          // for (let i = 0; i < details.length; i++) {
          // 	let contentDetails = details[i].contentDetails;
          // 	isDom = contentDetails.find(item => {
          // 		return item.id == this.pageId
          // 	})
          // 	//找到了该事项
          // 	if (isDom) {
          // 		//该设备
          // 		isDetails = details[i];
          // 		break;
          // 	}
          // }
          // // console.log(isDetails, isDom)
          // // this.content = isDom.content;
          // // this.equipmentName = isDetails.name;
          // // this.equipmentNo = isDetails.code;

          // this.sparepartList = isDom.outWorkSheetDetailList || [];
        }
      )
    },
    //获取报修信息
    getFlawInfo () {
      get(
        this.apiWebUrl + '/api/maintain/worksheet/getFlawInfo?id=' + this.pageId
      ).then(res => {
        console.log(res)
        let data = res.data
        let detail = data.detail[0]
        //this.opinion = detail.faultDescription;
        this.remark_list = data.descriptionopinion

        this.fileList1 = data.image.map(e => {
          //组件图片可展示
          this.$set(e, 'isImage', true)
          return e
        })
        this.expectCompleteTime = data.expectedCompletionTime

        this.degree = data.status.name
      })
    },
    confirm (e) {
      console.log(e)
      this.expectCompleteTime = e
      this.showTime = e
      // this.calendarShow = false
    },
    //选择紧急程度
    bindPickerChange (e) {
      // console.log(e)
      this.degreeIndex = e.detail.value
      this.form.urgent = this.degreeList[this.degreeIndex].id
    },
    showCalendar () {
      if (this.pageType == 'details') return
      // this.calendarShow = !this.calendarShow
      // console.log(this.calendarShow)
    },
    //报修提交- 修改事项状态 、上传报修信息
    updateparam (status) {
      if (status === 2) {
        if (!this.form.repairName) {
          uni.showToast({
            title: '请输入维修工单名称',
            icon: 'none'
          })
          return
        }
        if (!this.form.executeDeptCode) {
          uni.showToast({
            title: '请选择执行部门',
            icon: 'none'
          })
          return
        }
        if (!this.form.executeUserId) {
          uni.showToast({
            title: '请选择执行人',
            icon: 'none'
          })
          return
        }
        if (!this.form.expectDoneTime) {
          uni.showToast({
            title: '请选择期望完成时间',
            icon: 'none'
          })
          return
        }
        this.form.content =
          this.remark_list && this.remark_list.length !== 0
            ? this.remark_list[0].description
            : ''
        this.form.equiList = this.worksheetInfo.equiList.filter(
          item => item.id == this.bizEquiId
        )
        this.form.equiList.forEach(item => {
          // console.log(item.sparepart)
          // item.sparepart.forEach(el => {
          // 	delete el.id
          // })
          delete item.id
          delete item.ruleItems
        })

        this.form.equiList[0].spareParts = this.sparepartList.map(item => {
          return {
            bizEquiId: this.bizEquiId,
            code: item.code,
            model: item.model,
            name: item.name,
            num: item.num,
            unit: item.unit
          }
        })

        uni.showLoading({
          title: '加载中'
        })
        postJ(this.apiUrl + '/repair/info/saveOrEdit', this.form).then(res => {
          // console.log(res)

          if (res.success) {
            this.updateStatus(0)
            // uni.showToast({
            // 	title: "操作成功",
            // 	icon: "none"
            // })
            // this.back()
          }
        })
      } else {
        this.updateStatus(1)
      }
      // let PromiseArr = [changeStatus];
      // //修改事项状态
      // const changeStatus = postJ(this.apiUrl + "/repair/info/saveOrEdit", {
      // 	data
      // });
      // if (status == 2) {

      // 	//处理图片json数据
      // 	let image = this.fileList1.map(el => {
      // 		return {
      // 			"accessUrl": el.accessUrl,
      // 			"docId": el.docId,
      // 			"name": el.name,
      // 			"size": el.size,
      // 			"type": el.type.id,
      // 			"url": el.url
      // 		}
      // 	})

      // 	let data = {
      // 		"assetsList": [{
      // 			"assetsName": this.equipmentName,
      // 			"assetsSn": this.equipmentNo,
      // 			//描述
      // 			//"faultDescription": this.faultDescription,
      // 			//意见
      // 			//"opinion": this.opinion,
      // 			//"owner": "",
      // 			"place": this.equipmentPlace
      // 		}],
      // 		"descriptionopinion": this.remark_list,
      // 		"expectedCompletionTime": this.expectCompleteTime,
      // 		"image": image,
      // 		//事项id
      // 		"relateId": this.pageId,
      // 		//工单code
      // 		"spotInspectionWorkOrderSn": this.worksheetInfo.code,
      // 		"status": {
      // 			"id": this.degreeList[this.degreeIndex].id,
      // 			"name": this.degreeList[this.degreeIndex].value
      // 		}
      // 	}

      // 	console.log(data)

      // 	//报修- 消缺
      // 	const repairs = postJ(this.apiUrl + "/feature/patrol/sheetwork/repairs", data);
      // 	PromiseArr.unshift(repairs);
      // }

      // Promise.all(PromiseArr).then(res => {
      // 	uni.showToast({
      // 		title: '操作成功'
      // 	})
      // 	this.back()
      // }).catch(err => {
      // 	uni.showToast({
      // 		title: '操作失败',
      // 		icon: 'none'
      // 	})
      // })
    },
    updateStatus (status) {
      postJ(this.apiUrl + '/rule/item/editStatus', {
        ruleItemId: this.ruleItemId,
        status
      }).then(res => {
        // console.log(res)
        uni.hideLoading()
        if (res.success) {
          uni.showToast({
            title: '操作成功'
          })
          // this.getInfo();
          this.back()
        }
      })
    },
    // 删除图片
    deletePic (event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    //添加描述
    add_opinion () {
      if (this.remark_list.length === 1) return
      this.remark_list.push({
        description: '',
        opinion: ''
      })
      //descriptionopinion
    },
    //文件上传
    uploadFile (img) {
      return new Promise((resolve, reject) => {
        upload(
          {
            img
          },
          this.apiUrl + '/data/doc/add',
          '缺陷'
        ).then(res => {
          //直接通过uni.chooseImage获取地址传给后端
          let resData = JSON.parse(res.data)
          console.log('上传后')
          console.log(resData)
          if (resData.success) {
            // uni.showToast({
            // 	title: "上传成功",
            // 	icon: 'none',
            // 	duration: 2000
            // })
            resolve(resData.data)
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 2000
            })
            reject(res)
          }
        })
      })
    },
    // 新增图片
    async afterRead (event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map(item => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFile(lists[i].url)
        console.log('上传后result:' + result)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: 'success',
            accessUrl: result.accessUrl,
            docId: result.docId,
            name: result.name,
            size: result.size,
            type: result.type,
            url: result.url
          })
        )
        fileListLen++
      }
      console.log(this.fileList1)
    },

    //选择备件
    goSparepart () {
      uni.navigateTo({
        url: '../sparepart/sparepart?id=' + this.pageId
      })
    }
  }
}
</script>

<style scoped lang="scss">
.content-number {
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: $uni-font-size-base;
  color: $uni-text-color;

  .content {
    padding: 10rpx 0;
  }

  text {
    margin-right: 6rpx;
  }
}

.title {
  margin: 20rpx 0;
  font-size: $uni-font-size-base;
  color: $uni-text-color-grey;
  text-align: center;
}

.reason-list {
  padding: 15rpx 20rpx;
  display: flex;
  align-items: center;
  font-size: $uni-font-size-base;
  color: $uni-text-color-grey;

  input {
    font-size: $uni-font-size-base;
    color: $uni-text-color;
  }
}

.option-title {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  text-align: center;

  .border-title {
    width: 94rpx;
    height: 94rpx;
    line-height: 90rpx;
    border: 1rpx solid #c0c0c0;
    border-radius: 15rpx;
    margin: 0 30rpx 30rpx;
  }

  .iconfont {
    font-size: 40rpx;
    color: $uni-text-color-grey;
  }
}

//底部按钮
.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:nth-child(odd) {
    border-top: 1rpx solid $uni-border-color;
    width: 50%;
    background-color: #ffffff;
    font-size: 34rpx;
    color: $j-primary-green;
    line-height: 99rpx;
    height: 98rpx;
  }

  text:nth-child(even) {
    width: 50%;
    background-color: $j-primary-green;
    font-size: 34rpx;
    color: #ffffff;
    line-height: 100rpx;
  }
}

.uni-input-placeholder {
  color: #999;
}

.popupInfo {
  background-color: #fff;
  padding: 40rpx;
  border-radius: 10rpx 10rpx 0 0;
}
</style>
