<template>
  <view class="u-flex content">
    <view class="categary">
      <view class="u-flex u-col-center">
        <view
          :class="['txt', {'active': classifyId === item.id }]"
          v-for="item in classify"
          :key="item.id"
          @click="changeClassify(item)"
        >{{item.label}}</view>
      </view>
    </view>

    <view class="search">
      <u-search
        :clearabled="true"
        :action-style="searchStyle"
        bg-color="#fff"
        v-model="keyword"
        @custom="searchParts"
        @search="searchParts"
      ></u-search>
    </view>

    <view class="warp u-flex">
      <view class="brand u-flex" v-if="brand.length > 0">
        <view class="label-content u-flex">
          <scroll-view
            style="width:100%;white-space: nowrap;"
            scroll-x="true"
            class="u-flex"
            :scroll-into-view="scrollId"
          >
            <view
              :id="`brand${item.id}`"
              :class="['label-title', { selected: item.id == brandId }]"
              v-for="(item, index) in brand"
              :key="index"
              @click="selectBrand(item, index)"
            >{{ item.label }}</view>
          </scroll-view>
        </view>
        <view class="more u-flex" @click="handleClick">
          <view class="more-text">更多</view>
          <u-icon class="input-icon" color="#2272FF" name="arrow-right"></u-icon>
        </view>
      </view>

      <view class="model u-flex" v-if="showMore !== true && model.length > 0">
        <view class="label-content u-flex">
          <scroll-view
            style="width:100%;white-space: nowrap;"
            scroll-x="true"
            class="u-flex"
            :scroll-into-view="scrollModelId"
          >
            <view
              :id="`model${item.id}`"
              :class="['label-title', { selected: item.id == modelId }]"
              v-for="(item, index) in model"
              :key="index"
              @click="selectModel(item, index)"
            >{{ item.label }}</view>
          </scroll-view>
        </view>
        <view class="more u-flex" @click="showMore = true">
          <u-icon class="input-icon" color="#666" name="arrow-down"></u-icon>
        </view>
      </view>

      <view class="allModel u-flex" v-if="showMore === true && model.length > 0">
        <view class="label-content u-flex">
          <scroll-view
            style="width:100%;height: 320rpx;"
            scroll-y="true"
            class="u-flex"
            :scroll-into-view="scrollModelId"
          >
            <view
              :id="`model${item.id}`"
              :class="['label-title', { selected: item.id == modelId }]"
              v-for="(item, index) in model"
              :key="index"
              @click="selectModel(item, index)"
            >{{ item.label }}</view>
          </scroll-view>
        </view>
        <view class="more u-flex" @click="showMore = false">
          <u-icon class="input-icon" color="#666" name="arrow-up"></u-icon>
        </view>
      </view>

      <view class="lists">
        <view class="mask" v-if="showMore === true" @click="showMore = false"></view>
        <scroll-view
          style="height:100%;"
          :scroll-top="scrollTop"
          scroll-y="true"
          class="scroll-Y"
          @scrolltolower="loadMore"
        >
          <select-parts
            v-for="(item, index) in lists"
            :key="index"
            :info="item"
            :show-checked="false"
            :maxShow="false"
            @numChange="numChange($event, item, index)"
            @apply="apply(item, index)"
          ></select-parts>
          <view class="load-more">
            <u-loadmore :status="loadStatus" @loadmore="loadMore" :load-text="loadText" />
          </view>
        </scroll-view>
      </view>
    </view>

    <view class="bar" v-show="partNum > 0">
      <submit-bar
        :partNum="partNum"
        :num="num"
        :btnStatus="partNum > 0"
        :show-checked="false"
        submit-txt="确定"
        @submit="submit"
      />
    </view>
  </view>
</template>

<script>
import selectParts from '@/components/select-parts/index'
import submitBar from '@/components/submit-bar/index'
export default {
  components: {
    selectParts,
    submitBar,
  },
  data() {
    return {
      keyword: '',
      show: false,
      showMore: false,
      categary: [],
      classify: [],
      brand: [],
      model: [],
      categaryIndex: 0,
      categoryId: '',
      classifyId: '',
      brandId: 0,
      scrollId: '',
      scrollModelId: '',
      modelId: 0,
      loadStatus: 'loadmore',
      lists: [],
      submitList: [],
      pageSize: 20,
      pageNumber: 1,
      type: '1',
    }
  },
  computed: {
    searchStyle() {
      return {
        color: '#2272FF',
      }
    },
    // 配件数
    partNum() {
      return this.submitList.reduce(
        (counter, item) =>
          !item.disabled && item.quantity > 0 ? (counter += 1) : counter,
        0
      )
    },
    // 总数
    num() {
      return this.submitList.reduce(
        (counter, { disabled, quantity }) =>
          !disabled ? (counter += quantity) : counter,
        0
      )
    },
    loadText() {
      return {
        loadmore: '上拉加载更多',
        loading: '努力加载中',
        nomore: this.pageNumber > 1 ? '没有更多了' : '未找到物料',
      }
    },
  },
  onLoad(e) {
    getApp().trackPage('选择配件页')
    if (e) {
      if (e.type == 1) { // 从订单进入
        this.categoryId = e.categaryId || ''
        this.type = e.type
        this.getClassify()
      } else if (e.type == 2) { // 从物料库进入
        this.type = e.type
        this.getCategaryList()
      }
    }
  },
  onShow() {
    let pages = getCurrentPages()
    let page = pages[pages.length - 1]
    let selectedItem = page.selectedItem
    if (selectedItem) {
      page.selectedItem = null
      this.selectBrand(selectedItem.item, selectedItem.index)
      this.scrollId = `brand${selectedItem.id}`
    }
  },
  methods: {
    // 获取品类
    getCategaryList() {
      this.$u.api.getCategoryList().then((res) => {
        if (res.code === 200) {
          const data = res.data
          if (data.length > 0) {
            this.categoryId = data[0].categoryId
            this.getClassify()
          } else {
            this.getPartsList()
          }
        }
      })
    },
    // 获取一级分类
    getClassify() {
      this.$u.api.getClassify({ id: this.categoryId }).then((res) => {
        if (res.code === 200) {
          const data = res.data
          if (data.length > 0) {
            this.classify = data.map((v) => {
              v.label = v.name
              return v
            })
            this.classifyId = this.classify[0].id
            this.getBrandList()
          } else {
            this.getPartsList()
          }
        }
      })
    },
    // 获取二级分类
    getBrandList(id) {
      this.$u.api.getBrandList({ categoryId: this.categoryId, classifyId: this.classifyId }).then((res) => {
        if (res.code === 200) {
          const data = res.data
          let lists
          if (this.classifyId === 1) {
            lists = data.partnerCompany
          } else {
            lists = data.classify
          }
          let item, index
          this.brand = lists.map((v, i) => {
            if (id && parseInt(id) === v.id) {
              item = v
              index = i
            }
            v.label = v.name
            return v
          })

          if (item && index) {
            this.selectBrand(item, index)
            this.scrollId = `brand${item.id}`
          } else {
            this.brandId = this.brand?.[0]?.id
            this.scrollId = `brand${this.brandId}`
            this.lists = []
            this.getThreeLevel()
          }
        }
      })
    },
    // 获取三级分类
    getThreeLevel() {
      const params = {
        categoryId: this.categoryId, 
        classifyId: this.classifyId,
        partnerCompanyId: '',
        speciesId: ''
      }
      if (this.classifyId === 1) {
        params.partnerCompanyId = this.brandId || ''
      } else {
        params.speciesId = this.brandId || ''
      }

      this.$u.api.getThreeLevel(params).then(res => {
        if (res.code === 200) {
          const data = res.data
          let item, index
          this.model = data.map((v, i) => {
            // if (id && parseInt(id) === v.id) {
            //   item = v
            //   index = i
            // }
            v.label = v.name
            return v
          })
          if (item && index) {
            this.selectModel(item, index)
            this.scrollModelId = `model${item.id}`
          } else {
            this.modelId = this.model?.[0]?.id
            this.scrollModelId = `model${this.modelId}`
            this.lists = []
            this.getPartsList()
          }
        }
      })
    },
    // 获取配件列表
    getPartsList() {
      this.page++
      this.loadStatus = 'loading'
      const params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        categoryId: this.categoryId || '',
        keyword: this.keyword,
        classifyId: this.classifyId,
        brandId: this.modelId || '',
        speciesId: '',
        partnerCompanyId: '',
      }

      if (this.classifyId === 1) {
        params.partnerCompanyId = this.brandId || ''
      } else {
        params.speciesId = this.brandId || ''
      }
      this.$u.api.getPartsList(params).then((res) => {
        if (res.code === 200) {
          const data = res.data
          if (data.length > 0) {
            const lists = data.map((v) => {
              v.quantity = 0
              v.disabled = true
              v.max = 9999
              const images = v.images ? v.images.split(',') : []
              v.images = images[0]
              return v
            })
            this.lists = this.lists.concat(lists)
            this.pageNumber++
            this.loadStatus =
              lists.length < this.pageSize ? 'nomore' : 'loadmore'
          } else {
            this.loadStatus = 'nomore'
          }
        }
      })
    },
    // 搜索配件
    searchParts(val) {
      this.keyword = val
      this.lists = []
      this.pageNumber = 1
      this.getPartsList()
    },
    // 选择品类
    changeClassify(data) {
      this.classifyId = data.id
      this.show = false
      this.brand = []
      this.pageNumber = 1
      this.getBrandList()
    },
    // 点击选择品牌
    selectBrand(item, index) {
      this.scrollId = ''
      this.brandId = item.id
      this.model = []
      this.lists = []
      this.pageNumber = 1
      this.getThreeLevel()
    },
    // 点击选择三级分类
    selectModel(item, index) {
      this.scrollModelId = `model${item.id}`
      this.modelId = item.id
      this.showMore = false
      this.lists = []
      this.pageNumber = 1
      this.getPartsList()
    },
    // 加载更多
    loadMore() {
      if (this.loadStatus !== 'nomore') {
        this.getPartsList()
      }
    },
    // 点击更多
    handleClick() {
      this.$u.route({
        url:
          'pages/order/document-tag' +
          '?categoryId=' +
          this.categoryId +
          '&classifyId=' +
          this.classifyId +
          '&selectedId=' +
          this.brandId,
      })
    },
    // 加入申请
    apply(item, index) {
      this.$set(this.lists[index], 'disabled', false)
      this.$set(this.lists[index], 'quantity', 1)

      // 如果购物车没有该记录，则添加
      const findIndex = this.submitList.findIndex((v) => v.id === item.id)
      if (findIndex === -1) this.submitList.push(item)
    },
    // 改变数量
    numChange(val, item, index) {
      this.$set(this.lists[index], 'quantity', val)
      if (val === 0) this.$set(this.lists[index], 'disabled', true)
      // 如果购物车有该记录，则更新
      const findIndex = this.submitList.findIndex((v) => v.id === item.id)
      this.$set(this.submitList[findIndex], 'quantity', val)
    },
    // 提交
    submit() {
      const lists = this.submitList
        .filter((v) => !v.disabled && v.quantity > 0)
        .map((v) => {
          return {
            part_id: v.skuId,
            name: v.name,
            quantity: v.quantity,
          }
        })
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2] //上一个页面
      prevPage.$vm.updateParts(lists)
      this.$u.route({ type: 'back' })
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  flex-direction: column;
  height: 100vh;
  .search {
    width: 100%;
    padding: 30rpx;
  }
  .categary {
    width: 100%;
    padding: 20rpx 30rpx 0rpx;
    .txt {
      font-size: 36rpx;
      color: #333;
      margin-right: 30rpx;
    }
    .active {
      font-size: 48rpx;
      color: #333;
      font-weight: bold;
      margin-right: 30rpx;
    }
  }

  .warp {
    border-radius: 30rpx 30rpx 0 0;
    width: 100%;
    background: #fff;
    flex-direction: column;
    align-items: center;
    flex: 1;
    overflow: hidden;
    .brand {
      width: 100%;
      padding: 20rpx 30rpx 0rpx 30rpx;
      .label-content {
        flex: 1;
        overflow: hidden;
        padding-right: 20rpx;
        border-right: 2rpx solid #f4f5f7;
        .label-title {
          color: #666;
          padding: 10rpx 0rpx;
          margin-right: 40rpx;
          display: inline-block;
          font-size: 32rpx;
          &.selected {
            color: #2272ff;
            border-bottom: 4rpx solid #2272ff;
            font-size: 36rpx;
            font-weight: bold;
          }
        }
      }
      .more {
        width: 100rpx;
        padding-left: 20rpx;
        .more-text {
          color: #2272ff;
          font-size: 26rpx;
        }
      }
    }
    .model {
      width: 100%;
      padding: 30rpx 30rpx 0 30rpx;
      .label-content {
        flex: 1;
        overflow: hidden;
        padding-right: 20rpx;
        .label-title {
          background: #f4f5f7;
          color: #999;
          padding: 7rpx 30rpx;
          margin-right: 20rpx;
          display: inline-block;
          font-size: 26rpx;
          border-radius: 30rpx;
          &.selected {
            color: #fff;
            background: #2272ff;
          }
        }
      }
      .more {
        padding-left: 20rpx;
      }
    }
    .allModel {
      width: 100%;
      padding: 30rpx 30rpx 0 30rpx;
      flex-flow: column;
      border-radius: 0 0 30rpx 30rpx;
      .label-content {
        flex: 1;
        overflow: hidden;
        width: 100%;
        .label-title {
          background: #f4f5f7;
          color: #999;
          padding: 7rpx 30rpx;
          margin: 0rpx 15rpx 20rpx 0;
          display: inline-block;
          font-size: 26rpx;
          border-radius: 30rpx;
          &.selected {
            color: #fff;
            background: #2272ff;
          }
        }
      }
      .more {
        padding: 20rpx 0;
        width: 100%;
        justify-content: flex-end;
      }
    }
    .lists {
      width: 100%;
      flex: 1;
      overflow-y: auto;
      padding: 30rpx 30rpx 0 30rpx;
      position: relative;
      .mask {
        position: absolute;
        z-index: 9;
        background: #00000082;
        width: 100%;
        left: 0;
        top: 0;
        bottom: 0;
      }
      .load-more {
        padding: 50rpx 0;
      }
    }
  }
  .bar {
    width: 100%;
    border-top: 2rpx solid #f4f5f7;
    padding: 0 20rpx;
    background: #fff;
  }
}
</style>
