<template>
	<view class="container">
		<VNavigationBar background-color="#fff" title="配件申请" :addWares="true" @addNewWares="addNewWaresFun"
			title-color="#333"></VNavigationBar>
		<view class="search">
			<view class="searchBox">
				<input class="searchInput" v-model="searchName" placeholder="查询配件名称"
					placeholder-style="font-size: 28rpx" type="text">
				<text @click="onRefresherrefresh">搜索</text>
			</view>
		</view>
		<view class="tabs">
			<view v-for="(item, index) in tabs" @click="chooseTab(item.value)" :key="index"
				:class="{'active': item.value === activeId}" class="tab-item">
				{{ item.name }}
			</view>
		</view>
		<view class="listBox">
			<view class="list">
				<scroll-view style="height: 100%" scroll-y="true" class="itemContent" @scrolltolower="onReachBottomCus"
					refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered">
					<view v-for="(item, index) in repairList" :key="index" class="listItem">
						<view class="repairName">{{ item.name }}</view>
						<view class="repairBottom">
							<text class="repairDesc">单位：
								<text class="repairUnit">{{ item.unitText }}</text>
							</text>
							<view class="repairBtns">
								<u-icon name="minus-circle-fill" size="24" @click="delNum(item)"></u-icon>
								<text class="repairNum">{{ item.num }}</text>
								<u-icon color="#0174F6" name="plus-circle-fill" size="24"
									@click="addNum(item)"></u-icon>
							</view>
						</view>
					</view>
          <view style="text-align: center" v-if="repairList.length==0">
            <image class=""  src="@/static/images/nothing.png" ></image>
          </view>
				</scroll-view>
			</view>
		</view>
		<view class="footer">
			<text class="label" @click="openChoosed">共选择：</text>
			<text class="repairNum" @click="openChoosed">{{ repairCount }}个配件</text>
			<view class="submit" v-if="ticketId" @click="submit">确认申请</view>
			<view class="submit" v-if="!ticketId" @click="addTwi">确认添加</view>
			<view class="submit" v-if="ticketId" @click="openUpload">拍照上传</view>
		</view>
    <!-- 普通弹窗---打开已选配件 -->
    <uni-popup ref="waresPopup" background-color="#fff" :mask-click="false">
      <view class="popup-content" style="padding: 15px;">
        <view class="dl-avatar-box" style="height: 400px;overflow-y: scroll">
          <view v-for="(item, index) in selectedRepairList" :key="index" class="listItem">
            <view class="repairName">{{ item.name }}</view>
            <view class="repairBottom">
              <text class="repairDesc">单位：
                <text class="repairUnit">{{ item.unitText }}</text>
              </text>
              <view class="repairBtns">
                <u-icon name="minus-circle-fill" size="24" @click="delNum(item)"></u-icon>
                <text class="repairNum">{{ item.num }}</text>
                <u-icon color="#0174F6" name="plus-circle-fill" size="24"
                        @click="addNum(item)"></u-icon>
              </view>
            </view>
          </view>
          <view style="text-align: center" v-if="selectedRepairList.length==0">
            <image class=""  src="@/static/images/nothing.png" ></image>
          </view>
        </view>
        <button type="primary" @click="closeWaresPopup">关闭</button>
      </view>
    </uni-popup>
		<!-- 普通弹窗---拍照上传 -->
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content" style="padding: 15px;">
				<view class="dl-avatar-box">
					<uni-file-picker :value="fileList" :sizeType="sizeType" @select="afterRead" @delete="deleteFile"
						limit="9" title="请上传配件申请单照片（最多选择9张图片）"></uni-file-picker>
				</view>
				<button type="primary" @click="$refs.popup.close()">保存</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import VNavigationBar from "@/components/VNavigationBar.vue";
	import request from '@/utils/request';
	import {
		getDictTextByCodeAndValue,
		createUniqueCodeByHead
	} from "@/utils/utils";
	import {
		getUserInfo
	} from "@/utils/auth";
	import upload from "@/utils/upload";
	import config from "@/config";
  import {data} from "uview-ui/libs/mixin/mixin";
	export default {
		components: {
			VNavigationBar
		},
		data() {
			return {
				tabs: [{
					name: '全部',
					value: ''
				}],
				//所有配件
				repairList: [],
				//已选的配件
				selectedRepairList: [],
				//搜索的配件名称
				searchName: '',
				//选中的分类ID
				activeId: '',
				//工单ID
				ticketId: null,
				pageNo: 1,
				pageSize: 10,
				total: 0,
				//下来刷新状态
				isTriggered: false,
				userInfo: null,
				fileList: [],
				sizeType: ['compressed'],
        twId: null
			};
		},
		computed: {
			repairCount() {
				return this.selectedRepairList.reduce((val, item) => {
					return item.num + val
				}, 0)
			}
		},
		onLoad(data) {
			this.userInfo = getUserInfo()
			this.ticketId = data.ticketId
      this.twId = data.twId
      this.ifHouse = data.ifHouse
		},
		onShow() {
			this.init()
		},
		methods: {
      closeWaresPopup(){
        this.$refs.waresPopup.close()
        //刷新数据列表
        this.chooseTab("")
      },
		  /**
       * 打开已选择的配件弹出框
       */
      openChoosed(){
        if(this.selectedRepairList.length==0){
          return
        }
        this.$refs.waresPopup.open("bottom")
      },
      addTwi(){
        if (!this.selectedRepairList || this.selectedRepairList.length === 0){
          uni.showToast({
            title: '请选择配件！',
            icon: 'none'
          })
          return
        }
        let dataObj = {
          id: this.twId
        }
        dataObj.items = [...this.selectedRepairList.map(item => {
          return {
            id: item.id,
            count: item.num,
            name: item.name
          }
        })]
        if(this.ifHouse){
          //仓管
          dataObj.ifHouseAdd = true
        }else{
          //服务顾问
          dataObj.ifHouseAdd = false
        }
        request({
          url: "/admin-api/repair/twi/addTwi",
          method: 'post',
          data: dataObj
        }).then(res => {
          uni.showToast({
            title: '提交成功！',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 700)
        })
      },
			openUpload() {
				this.$refs.popup.open("bottom")
			},
			afterRead(file) {
				for (let i = 0; i < file.tempFilePaths.length; i++) {
					upload({
						url: '/admin-api/infra/file/upload',
						filePath: file.tempFilePaths[i]
					}).then((res) => {
						this.fileList.push({
							url: config.baseImageUrl + res.data
						})
						console.log(this.fileList)
					})
				}
			},

			deleteFile(file, index) {
				this.fileList.splice(index, 1);
			},
			/**
			 * 上滑加载数据
			 */
			onReachBottomCus() {
				//判断 如果页码*页容量大于等于总条数，提示该页数据加载完毕
				if (this.pageNo * this.pageSize >= this.total) {
					uni.$u.toast('没有更多数据了')
					return
				}
				//页码+1,调用获取数据的方法获取第二页数据
				this.pageNo++
				//此处调用自己获取数据列表的方法
				this.pageList()
			},
			/**
			 * 下拉刷新数据
			 */
			onRefresherrefresh() {
				this.isTriggered = true
				this.pageNo = 1
				this.total = 0
				this.repairList = []
				this.pageList()
			},
			init() {
				this.tabs = []
				//加载所有tab
				request({
					url: '/admin-api/repair/wares/getAllTypeList',
					method: 'get'
				}).then((res) => {
					console.log(res)
					if (res.code == 200 && res.data.length > 0) {
						res.data.map((item) => {
							if (item.id) {
								this.tabs.push({
									name: item.name,
									value: item.id
								})
							}
						})
					}
				})
				//分页加载所有配件
				this.pageList()
				// // 接口返回
				// const result = [{name: '炫驰全合成机油S7 4L/ALL', num: 0, unit: '桶', id: 1},
				//   {name: '炫驰全合成机油S7 4L/ALL', num: 0, unit: '桶', id: 2},
				//   {name: '炫驰全合成机油S7 4L/ALL', num: 0, unit: '桶', id: 3},
				//   {name: '炫驰全合成机油S7 4L/ALL', num: 0, unit: '桶', id: 4},
				//   {name: '炫驰全合成机油S7 4L/ALL', num: 0, unit: '桶', id: 5}]
				// // 初始化数据
				// this.repairList = result.map(m => {
				//   if (this.selectedRepairList && this.selectedRepairList.length > 0) {
				//     const find = this.selectedRepairList.find(f => f.id === m.id)
				//     if (find) {
				//       m.num = find.num
				//     }
				//   }
				//   return m
				// })
			},
			/**
			 * 分页加载所有配件
			 */
			pageList() {
			  let that = this
				let paramsObj = {
					pageNo: this.pageNo,
					pageSize: this.pageSize
				}
				if ("" != this.activeId) {
					paramsObj.type = this.activeId
				}
				if ("" != this.searchName) {
					paramsObj.name = this.searchName
				}
				request({
					url: '/admin-api/repair/wares/page',
					method: 'get',
					params: paramsObj
				}).then((res) => {
					console.log(res)
					if (res.code == 200 && res.data.records.length > 0) {
						let thisDataList = res.data.records
						// 初始化数据
						thisDataList = thisDataList.map(m => {
							if (that.selectedRepairList && that.selectedRepairList.length > 0) {
								const find = that.selectedRepairList.find(f => f.id === m.id)
								if (find) {
									m.num = find.num
								} else {
									m.num = 0
								}
							} else {
								m.num = 0
							}
							return m
						})
            console.log(thisDataList,"thisDataList")
						//判断 如果获取的数据的页码不是第一页，就让之前赋值获取过的数组数据 concat连接 刚获取的第n页数据
						if (that.pageNo != 1) {
              that.repairList = that.repairList.concat(thisDataList)
						} else {
              that.repairList = thisDataList
						}
						//将获取的总条数赋值
            that.total = res.data.total
            that.isTriggered = false
					}else{
            that.isTriggered = false
          }
				})
			},
			addNum(repair) {
				this.$set(repair, 'num', repair.num + 1)
				const find = this.selectedRepairList.find(f => f.id === repair.id)
				if (find) {
					find.num = repair.num
				} else {
					this.selectedRepairList.push(JSON.parse(JSON.stringify(repair)))
				}
				console.log('repair', repair)
			},
			delNum(repair) {
				if (repair.num <= 0) {
					return
				}
				this.$set(repair, 'num', repair.num - 1)
				const findIndex = this.selectedRepairList.findIndex(f => f.id === repair.id)
				if (findIndex > -1 && repair.num <= 0) {
					this.selectedRepairList.splice(findIndex, 1)
				} else if (repair.num > 0) {
					this.$set(this.selectedRepairList[findIndex], 'num', repair.num)
				}
			},
			submit() {
				let orderNo = createUniqueCodeByHead("LLSQ")
				let dataObj = {
					no: orderNo,
					ticketId: this.ticketId,
					type: "01",
					repairId: this.userInfo.id,
					repairName: this.userInfo.nickname,
				}
				if (this.selectedRepairList.length === 0 && this.fileList.length === 0) {
					uni.showToast({
						title: '请选择配件！',
						icon: 'none'
					})
					return
				} else {
					if (this.selectedRepairList.length > 0) {
						let itemList = []
						this.selectedRepairList.map((item) => {
							itemList.push({
								waresId: item.id,
								waresName: item.name,
								waresCount: item.num,
								//未领料---不需要给
								waresStatus: ""
							})
						})
						dataObj.items = itemList
					}
          if (this.fileList.length > 0){
            dataObj.images = this.fileList.map(item => {
              console.log(item)
              return item.path.replace(config.baseImageUrl, '')
            }).join(",")
          }
				}
        request({
          url: '/admin-api/repair/tw/update',
          method: 'POST',
          data:dataObj
        }).then((res) => {
          console.log(res)
          if (res.code == 200) {
            uni.showToast({
              title: '提交成功！',
              icon: 'none'
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 700)
          }else{
            uni.showToast({
              title: '提交失败！',
              icon: 'none'
            })
          }
        })
				// if(this.selectedRepairList.length>0){
				//   let itemList = []
				//   this.selectedRepairList.map((item)=>{
				//     itemList.push({
				//       waresId:item.id,
				//       waresName:item.name,
				//       waresCount:item.num,
				//       //未领料
				//       waresStatus:"02"
				//     })
				//   })
				//   dataObj.items = itemList
				// }else{
				//   uni.showToast({
				//     title: '请选择配件！',
				//     icon: 'none'
				//   })
				//   return
				// }
				// request({
				//   url: '/admin-api/repair/tw/newApplyOrder',
				//   method: 'POST',
				//   data:dataObj
				// }).then((res) => {
				//   console.log(res)
				//   if (res.code == 200) {
				//     uni.showToast({
				//       title: '提交成功！',
				//       icon: 'none'
				//     })
				//     setTimeout(() => {
				//       uni.navigateBack()
				//     }, 700)
				//   }else{
				//     uni.showToast({
				//       title: '提交失败！',
				//       icon: 'none'
				//     })
				//   }
				// })
			},
			/**
			 * 切换tab选中
			 * @param value
			 */
			chooseTab(value) {
				this.activeId = value
				this.onRefresherrefresh()
			},
			/**
			 * 添加新的配件
			 */
			addNewWaresFun() {
				uni.navigateTo({
					url: '/pages-repair/apply/newWare'
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100%;
		background-color: #F3F5F7;
		display: flex;
		flex-direction: column;
	}

	.search {
		padding: 0 40rpx;
		background-color: #fff;

		&>.searchBox {
			height: 84rpx;
			background: #F3F5F7;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			margin: 0 auto;
			padding: 0 30rpx;
			font-size: 28rpx;
			color: #0174F6;

			display: flex;
			align-items: center;
		}

		.searchInput {
			flex: 1;
			width: 0;
			color: #333;
		}
	}

	.tabs {
		background-color: #fff;
		padding: 30rpx 40rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		column-gap: 30rpx;
		overflow: auto;
		width: 100%;

		.tab-item {
			flex-shrink: 0;
			padding: 16rpx 30rpx;
			font-size: 28rpx;
			color: #113A68;
			background: #F2F2F7;
			border-radius: 30rpx 30rpx 30rpx 30rpx;

			&.active {
				background: #0174F6;
				color: #fff;
			}

		}
	}

	.listBox {
		padding: 30rpx 32rpx;
		flex: 1;
		height: 0;

		.list {
			background-color: #fff;
			padding: 0 30rpx;
			height: 99%;
		}

		.listItem {
			padding: 30rpx 0;
			border-bottom: 2rpx solid #DDDDDD;

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

			.repairName {
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
			}

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

			.repairDesc {
				font-size: 28rpx;
				color: #858BA0;
			}

			.repairUnit {
				color: #333333;
			}

			.repairBtns {
				display: flex;
				align-items: center;
				column-gap: 10rpx;
			}
		}
	}

	.footer {
		padding: 14rpx 32rpx;
		background-color: #fff;
		display: flex;
		align-items: center;

		.repairNum {
			flex: 1;
			width: 0;
			margin-right: 10rpx;
		}

		.submit {
			width: 208rpx;
			height: 72rpx;
			background: #0174F6;
			border-radius: 38rpx 38rpx 38rpx 38rpx;
			text-align: center;
			line-height: 72rpx;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
  .listItem {
    padding: 30rpx 0;
    border-bottom: 2rpx solid #DDDDDD;

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

    .repairName {
      font-size: 32rpx;
      color: #333333;
      margin-bottom: 20rpx;
    }

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

    .repairDesc {
      font-size: 28rpx;
      color: #858BA0;
    }

    .repairUnit {
      color: #333333;
    }

    .repairBtns {
      display: flex;
      align-items: center;
      column-gap: 10rpx;
    }
  }
</style>
