<template>
  <view class="container">
    <VNavigationBar background-color="#fff" title="配件申请" 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">{{ getItemUnit(item.unit) }}</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>
        </scroll-view>
      </view>
    </view>
    <view class="footer">
      <text class="label">共选择：</text>
      <text class="repairNum">{{ repairCount }}个配件</text>
      <view class="submit" @click="submit">确认申请</view>
    </view>
  </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";
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,
    };
  },
  computed: {
    repairCount() {
      return this.selectedRepairList.reduce((val, item) => {
        return item.num + val
      }, 0)
    }
  },
  onLoad(data) {
    this.userInfo = getUserInfo()
    this.ticketId = data.ticketId
    this.init()
  },
  methods: {
    /**
     * 上滑加载数据
     */
    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() {
      //加载所有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)=>{
            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 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 (this.selectedRepairList && this.selectedRepairList.length > 0) {
              const find = this.selectedRepairList.find(f => f.id === m.id)
              if (find) {
                m.num = find.num
              }else{
                m.num = 0
              }
            }else{
              m.num = 0
            }
            return m
          })
          //判断 如果获取的数据的页码不是第一页，就让之前赋值获取过的数组数据 concat连接 刚获取的第n页数据
          if (this.pageNo != 1) {
            this.repairList = this.repairList.concat(thisDataList)
          } else {
            this.repairList = thisDataList
          }
          //将获取的总条数赋值
          this.total = res.data.total
          this.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.nickname,
        repairName:this.userInfo.id,
      }
      request({
        url: '/admin-api/repair/tw/getAllTypeList',
        method: 'get'
      }).then((res) => {
        console.log(res)
        if (res.code == 200 && res.data.length>0) {
          res.data.map((item)=>{
            this.tabs.push({
              name:item.name,
              value:item.id
            })
          })
        }
      })
      console.log('this.selectedRepairList', this.selectedRepairList)
    },
    /**
     * 切换tab选中
     * @param value
     */
    chooseTab(value){
      this.activeId = value
      this.onRefresherrefresh()
    },
    //翻译配件单位
    getItemUnit(unitCode){
      return getDictTextByCodeAndValue("repair_unit",unitCode);
    },
  }
}
</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;
  }
}
</style>
