<template>
  <view class="container">
    <VNavigationBar background-color="#fff" title="单据处理" title-color="#333" :houseAddNewWares="true" @addNewWaresHouse="addWares"></VNavigationBar>
    <!--    <view class="tabs">-->
    <!--      <view v-for="(item, index) in tabs" :key="index" :class="{'active': item.value === active}" class="tab-item">-->
    <!--        {{ item.name }}-->
    <!--      </view>-->
    <!--    </view>-->
    <view class="body-top">
      <view class="body-top-search">
        <input class="body-top-search-input" v-model="query" placeholder="配件名称"
               placeholder-style="font-size: 28rpx"
               type="text">
        <text @click="handleSearch">搜索</text>
      </view>
    </view>
<!--    <view class="header">-->
<!--      <view  style="float: right; color: #0174F6" @click="addWares">添加配件</view>-->
<!--    </view>-->
    <view class="listBox">
      <view class="list">
        <view v-for="(item, index) in wares" :key="index" class="listItem">
          <view class="repairName">
            <radio @click="chooseItem(item)" v-if="isToBeReviewed" :checked="item.isSelected"/>
            {{ item.waresName }}
          </view>
          <view class="repairBottom">
            <text class="repairDesc">单位：
              <text class="repairUnit">{{ item.wares.unit }}</text>
            </text>
            <text class="repairDesc">申请数量：
              <text class="repairUnit">{{ item.waresCount }}</text>
            </text>
            <view class="repairBtns" v-if="isToBeReviewed">
              <u-icon name="minus-circle-fill" size="24" @click="delNum(item)"></u-icon>
              <text class="repairNum">{{ item.thisNum }}</text>
              <u-icon color="#0174F6" name="plus-circle-fill" size="24" @click="addNum(item)"></u-icon>
            </view>
          </view>
          <view class="repairBottom">
            <text class="repairDesc">库存：
              <text class="repairUnit">{{ item.wares.stock }}</text>
            </text>
            <text class="repairDesc">已领取：
              <text class="repairUnit">{{ item.waresAlreadyCount }}</text>
            </text>

            <view class="repairBtns"><text v-if="item.ifHouseAdd" style="color: red">仓管添加</text></view>
          </view>
        </view>
      </view>
    </view>
    <view class="footer" v-if="isToBeReviewed">
      <text class="label"></text>
      <text class="repairNum"></text>
      <view class="submit" @click="toPart">采购</view>
      <view class="submit" @click="toInWares">入库单</view>
      <view class="submit" @click="submitBefore">{{ isReceive ? '通知领料' : '通知退料' }}</view>
    </view>

    <uni-popup ref="popup" background-color="#fff">
      <view class="popup-content" style="padding: 15px;">
        <view class="dl-avatar-box">
          <uni-section :title="isReceive ? '领料人' : '退料人'" type="line">
            <view class="uni-px-5 uni-pb-5">
              <uni-data-checkbox multiple v-model="chooseStaff" :localdata="staffs"></uni-data-checkbox>
            </view>
          </uni-section>
        </view>
        <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="submit">保存</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import VNavigationBar from "@/components/VNavigationBar.vue";
import request from '@/utils/request';
import {
  getJSONData, setJSONData
} from '@/utils/auth'
import {getDictTextByCodeAndValue, createUniqueCodeByHead} from "@/utils/utils";
import upload from "@/utils/upload";
import config from "@/config";

export default {
  components: {VNavigationBar},
  data() {
    return {
      //配件申请单id
      twId: '',
      //配件列表
      wares: [],
      //true 领料 ，false  退料
      isReceive: true,
      //父组件传入的数据
      formData: {},
      active: '',
      isToBeReviewed: true,
      query: null,
      selectRows: [],
      fileList: [],
      sizeType: ['compressed'],
      chooseStaff: [],
      staffs: [],
      ticketId: null,
      nowStaffId: null,
    };
  },
  onLoad(data) {
    if (getJSONData("applyWaresForm")) {
      this.formData = getJSONData("applyWaresForm")
      this.isReceive = this.formData.isReceive
      this.twId = this.formData.id
      this.ticketId = this.formData.ticketId
      this.nowStaffId = this.formData.repairId
      // this.init()
    }
    if (data.isToBeReviewed) {
      this.isToBeReviewed = JSON.parse(data.isToBeReviewed)
    }
  },
  onShow(){
    this.init()
  },
  computed: {},
  methods: {
    addWares(){
      //配件申请
      uni.navigateTo({
        url: '/pages-repair/apply/applyForm?twId=' + this.twId+'&ifHouse=true'
      })
    },
    toInWares(){
      uni.navigateTo({
        url: '/pages-order/orderList/orderListByIn?twId=' + this.twId
      })
    },
    async submitBefore(){
      if (!this.selectRows || this.selectRows.length === 0){
        uni.showToast({
          title: '请选择配件！',
          icon: 'none'
        })
        return
      }
      const flag = this.selectRows.filter(item => item.thisNum > 0)
      if (!flag || flag.length === 0) {
        uni.showToast({
          title: '请设置配件数量！',
          icon: 'none'
        })
        return
      }
      request({
        url: '/admin-api/repair/worker/listByTicketId?ticketId=' + this.ticketId,
        method: 'get'
      }).then(res => {
        this.chooseStaff = []
        const data = res.data
        this.staffs = data.map(item => {
          return {
            text: item.userName,
            value: item.userId
          }
        })
        this.chooseStaff.push(this.nowStaffId)
        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);
    },
    chooseItem(item) {
      const index = this.selectRows.findIndex(i => i.id === item.id)
      const parentIndex = this.wares.findIndex(i => i.id === item.id)
      if (index === -1) {
        this.$set(item, 'isSelected', true)
        this.selectRows.push(item)
      } else {
        this.$set(item, 'isSelected', false)
        this.selectRows.splice(index, 1)
      }
      if (parentIndex !== -1) {
        this.$set(this.wares, parentIndex, item)
      }
    },
    handleSearch() {
      this.init()
    },
    /**
     * 初始化配件数据
     */
    init() {
      const params = {
        twId: this.formData.id,
        query: this.query
      }
      request({
        url: '/admin-api/repair/twi/list',
        method: 'get',
        params: params
      }).then((res) => {
        this.wares = res.data
        if (this.isToBeReviewed) {
          this.wares = this.wares.filter(item => item.waresStatus === '1')
          this.wares = this.wares.filter(item => this.isReceive ? (item.waresCount > item.waresAlreadyCount) : (item.waresAlreadyCount > 0))
        }
        this.wares.forEach(item => {
          if (!item.wares.stock) {
            item.wares.stock = 0
          }
          if (this.isReceive) {
            //领料，最大可领取数量为申请数量-已领取数量，同时不能大于库存数量，默认数量就是最大可领取数量
            item.maxNum = parseInt(item.waresCount) - parseInt(item.waresAlreadyCount)
            if (item.maxNum > item.wares.stock) {
              item.maxNum = item.wares.stock
            }
            item.thisNum = item.maxNum
          } else {
            //退料，最大数量为已领取数量，最小数量为0,默认数量为0
            item.maxNum = item.waresAlreadyCount
            item.thisNum = 0
          }
          if (!this.selectRows || this.selectRows.length === 0){
            item.isSelected = false
          }else {
            item.isSelected = this.selectRows.findIndex(i => i.id === item.id) !== -1
          }
        })
      })
    },
    /**
     *
     */
    addNum(repair) {
      if ((repair.thisNum + 1) > repair.maxNum) {
        uni.showToast({
          title: '超过库存数量或最大申请数量！',
          icon: 'none'
        })
        return
      }
      this.$set(repair, 'thisNum', repair.thisNum + 1)
      const findIndex = this.wares.findIndex(f => f.id === repair.id);
      if (findIndex !== -1) {
        this.$set(this.wares, findIndex, repair);
      }
      // const find = this.wares.find(f => f.id == repair.id)
      // if (find) {
      //   find.thisNum = repair.thisNum
      // } else {
      //   this.wares.push(JSON.parse(JSON.stringify(repair)))
      // }
    },
    /**
     * 减
     */
    delNum(repair) {
      if (repair.thisNum == 0) {
        //已经等于0了，没法再减了
        return
      }
      this.$set(repair, 'thisNum', repair.thisNum - 1)
      const findIndex = this.wares.findIndex(f => f.id === repair.id);
      if (findIndex !== -1) {
        this.$set(this.wares, findIndex, repair);
      }
      // const find = this.wares.find(f => f.id == repair.id)
      // if (find) {
      //   find.thisNum = repair.thisNum
      // } else {
      //   this.wares.push(JSON.parse(JSON.stringify(repair)))
      // }
    },
    /**
     * 出库
     */
    submit() {
      this.formData.repairSo = {
        soType: this.isReceive ? '02' : '04',
        soNo: createUniqueCodeByHead(this.isReceive ? 'LL' : 'TL'),
        userId: this.formData.repairId,
        userName: this.formData.repairName,
        soStatus: this.isReceive ? '04' : '07'
      }
      if (!this.selectRows || this.selectRows.length === 0){
        uni.showToast({
          title: '请选择配件！',
          icon: 'none'
        })
        return
      }
      // 过滤一下，thisNum不等0才行
      const flag = this.selectRows.filter(item => item.thisNum > 0)
      if (!flag || flag.length === 0) {
        uni.showToast({
          title: '请设置配件数量！',
          icon: 'none'
        })
        return
      }
      // this.wares = flag
      this.formData.repairSois = [...flag.map(item => {
        return {
          soiType: this.isReceive ? '02' : "04",
          goodsId: item.waresId,
          goodsCount: item.thisNum,
        }
      })]
      if (this.isReceive) {
        this.formData.items = [...flag.map(item => {
          return {
            id: item.id,
          }
        })]
      }
      if (this.fileList && this.fileList.length > 0){
        this.formData.images = this.fileList.map(item => {
          return item.path.replace(config.baseImageUrl, "")
        }).join(",")
      }
      if ((!this.chooseStaff || this.chooseStaff.length === 0)){
        uni.showToast({
          title: `请选择${this.isReceive ? '领' : '退'}料人！`,
          icon: 'none'
        })
        return
      }
      this.formData.repairSo.userIds = this.chooseStaff.join(",")
      this.formData.ids = flag.map(item => item.id)
      request({
        url: '/admin-api/repair/tw/pass',
        method: 'post',
        data: this.formData
      }).then((res) => {
        if (this.isReceive){
          this.$refs.popup.close()
        }
        if (res.code === 200) {
          uni.showToast({
            title: '通知成功！',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 700)
        }
      })
    },

    /**
     * 跳转采购页面
     */
    toPart() {
      const formData = this.formData;
      if (this.selectRows && this.selectRows.length > 0) {
        formData.items = this.selectRows
      } else {
        formData.items = this.wares;
      }
      setJSONData("applyWaresForm", formData)
      uni.navigateTo({
        url: '/pages-warehouse/inOutWarehouse/part'
      })
    }

  }
}
</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;

  .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: 100%;
    overflow: auto;
  }

  .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 {
      width: 65px;
      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;
    margin-left: 20rpx;
  }
}

.body-top {
  //width: 686rpx;
  background: #FFFFFF;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  margin: 30rpx 30rpx 0;

  .body-top-search {
    height: 84rpx;
    background: #F3F5F7;
    border-radius: 12rpx 12rpx 12rpx 12rpx;
    margin: 0 auto;
    padding: 0 30rpx;
    font-size: 28rpx;

    display: flex;
    align-items: center;
    column-gap: 10rpx;

    .body-top-search-input {
      flex: 1;
      width: 0;
    }
  }
}
</style>
