<template>
  <view class="safe-area-inset-bottom white">
    <view class="search">
      <u-search :height="66" :inputStyle="{height:'66rpx'}" @custom="keyword=''" :show-action="false"
                placeholder="请输入您想要的商品" v-model="keyword" @input="getDrugList"></u-search>
    </view>
    <scroll-view scroll-y="true" style="padding-bottom: 200rpx">
      <!-- 西药 -->
      <block v-if="type==3">
        <view class="b-r-8 p-32" v-for="(item,i) in setList" :key="item.id">
          <view class="flex-row mb40">
            <u-image width="128rpx" height="144rpx" border-radius="8" :src="item.image">
              <u-loading slot="loading"></u-loading>
            </u-image>
            <view class="m-l-24 flex-1">
              <view>
                <d-text :text="item.drug_name" className="fs-3 content-c"></d-text>
              </view>
              <d-text :text="'规格：'+item.specification" className="fs-24 tips-c mtb12"
                      style="margin-left: 5rpx;"></d-text>
              <view class="flex-row flex-jus-sp flex-ali-center ">
                <view class="flex-row flex-1">
                  <d-text :text="'库存：剩余'" className="fs-24 tips-c"></d-text>
                  <d-text :text="item.stock" className="colorG fz24"></d-text>
                  <d-text text="件" className="fs-24 tips-c"></d-text>
                </view>
                <view class="price">
                  ¥{{ parseFloat(item.price).toFixed(2) }}
                </view>
              </view>
            </view>
          </view>
          <view class="m-t08 flex-row flex-jus-sp flex-ali-center">
            <view class="flex-row flex-1 flex-jus-sp ">
              <block v-if="!item.is_add">
                <view class="flex-row flex-ali-center btnBox">
                  <u-icon name="plus" color="#6ACDBB" size="26"></u-icon>
                  <d-text :text="'未添加'" className="fs-24 ml14" color="#6ACDBB"></d-text>
                </view>

                <view class="m-l-32">
                  <u-button :custom-style="{ backgroundColor:'#6ACDBB',color:'#fff' }" shape="circle"
                            size="mini" @click="handleAdd(item, i)">
                    添加商品
                  </u-button>
                </view>
              </block>
<!--              <view v-else class="flex-row flex-ali-center btnBox">-->
<!--                <d-text :text="`已添加(${item.number})周期`" className="fs-24 ml14" color="#6ACDBB"></d-text>-->
<!--              </view>-->
              <d-number-box v-else v-model="item.number" :min="0" :max="item.stock"
                            :asyncChange="true">
                <view slot="minus" class="minus flex-row flex-jus-center flex-ali-center"
                      :style="{backgroundColor:`rgba(249, 250, 251,${item.number>0?1:0.6})`}"
                      @click="clickHandler('minus',item,item.number)">
                  <u-icon name="minus" size="22" :color="item.number>0?'#000':'#A7ABB0'"></u-icon>
                </view>
                <view slot="input" style="width: 80rpx;"
                      class="input flex-row flex-jus-center flex-ali-center">
                  <d-text :text="item.number" className="fs-3 content-c"></d-text>
                </view>
              </d-number-box>
            </view>
          </view>
        </view>
      </block>

      <view class="flex-row flex-jus-center box"
            v-if="!loading&&((type===2||type===3)&&list[0].length===0||type===1&&setList.length===0)">
        <d-empty :text="keyword?'换个名称试试':current===1?'去收藏药品吧！':'暂无药品'" mode="search"></d-empty>
      </view>
    </scroll-view>

    <view class="btn" v-if="shownum">
      <u-button :throttle-time="0" :custom-style="{ backgroundColor:'#6ACDBB',color:'#fff' }" shape="circle"
                @click="toBack" :loading="loading">
        添加到处方
      </u-button>
    </view>

    <!-- 添加西药详情 -->
    <add-set-usage :info="info" @close="show=false"
                   @add="index!==-1&&$set(list,index,$event);index=-1;show=false;type===1?drugList(current):$go(1, 4);recipe={}"
                   :type="type" v-if="type>0&&show" :idx='idx' :recipe="recipe" :is_set="!!recipe['pId']">
    </add-set-usage>
  </view>
</template>

<script>
import mixin from './mixin/mixin.js';
import addSetUsage from './components/add-setUsage.vue'
import {servicePageList,} from '@/api/servicePackage.js'

export default {
  components: {
    addSetUsage
  },
  mixins: [mixin],
  data() {
    return {
      loading: true,
      recipe: {},
      affirmShow: false,
      index: -1,
      info: {},
      show: false,
      tabs: [{
        id: 0,
        name: '全部药品'
      }, {
        id: 1,
        name: '我的常用药'
      }],
      list: {
        0: [],
        1: [],
      },
      keyword: '',
      current: 0,
      type: 0,
      searchList: {
        0: [],
        1: [],
      },
      idx: 0,
      shownum: false
    }
  },
  computed: {
    setList() {
      this.getDrug();
      let list = this.list[this.current]?.length > 0 ? this.list[this.current] : [];
      let arr = [];
      arr = this.servicePackage
      console.log(list, 'this.servicePackage')
      console.log(arr, 'this.servicePackage')
      list = list.map((item) => {
        let it = arr.find(it => it['id'] === item.id) || {};
        return {
          ...item,
          ...it,
          is_add: !!it['id'],
          stock: item['stock'] - (it['number'] || 0)
        }
      });
      return list
    },
    getList() {
      return this.list[this.current].filter(item => item.checked).map(item => {
        return {
          ...item,
          grammage: item.grammage || 0
        }
      })
    },
    getSelect() {
      return this.list[this.current].filter(item => item.checked).length
    }
  },
  onLoad(op) {
    this.current = op['current'] || 0;
    this.type = 3;
    this.idx = op['index'] || 0;
    this.recipe = op['recipe'] ? JSON.parse(op['recipe']) : {}
    uni.showLoading({
      title: '加载中...'
    })
    this.drugList();
    this.getDrug();
  },
  methods: {
    toBack() {
      uni.navigateBack(1)
    },
    changeCheckbox(e, cur) {
      this.list[cur] = this.list[cur].map(item => {
        if (item.id === e.id) {
          return {
            ...item,
            checked: !item.checked
          }
        }
        return item
      })
    },
    async hoarding(id, type = 0) {
      let res = {}
      uni.showLoading({
        title: '请稍后...'
      })
      // type == 0 && (res = await westCollection({
      //   id,
      //   store_id: uni.getStorageSync('store_id') || '11001'
      // }))
      // type == 1 && (res = await westUncollect({
      //   id,
      //   store_id: uni.getStorageSync('store_id') || '11001'
      // }))
      if (res.errcode === 0) {
        this.list[this.current] = this.list[this.current].map((it) => {
          return {
            ...it,
            is_collect: id === it['id'] ? !it.is_collect : it.is_collect
          }
        })
        this.$nextTick(() => {
          uni.hideLoading()
        })
      } else {
        this.$toast(res.msg)
      }
    },
    getDrugList() {
      uni.showLoading({
        title: '搜索中...'
      })
      this.loading = true
      uni.$u.debounce(this.drugList, 1000);
    },
    // 药品列表
    async drugList() {
      this.list[this.current] = [];
      let res = {};

      (res = await servicePageList({
        name: this.keyword,
        store_id: uni.getStorageSync('store_id') || '11001'
      }))

      if (res.errcode === 0) {
        let collect = Array.isArray(res.data) ? res.data : res.data.collect || res.data.collected;
        collect = (collect || []).map(item => {
          return {
            ...item,
            is_collect: true
          }
        })
        let no_collect = res.data.no_collect || []
        let uncollect = res.data.uncollect || []
        uncollect = [...uncollect, ...no_collect].map(item => {
          return {
            ...item,
            is_collect: false
          }
        })
        this.list[this.current] = collect.concat(this.current == 0 ? uncollect : [])
        console.log(this.list[this.current], 'sssssssssssssssssssssss')
        this.$nextTick(() => {
          this.loading = false
          uni.hideLoading()
        })
      } else {
        this.loading = false
        this.$toast(res.msg)
      }
    },
    clickHandler(type, data, number) {
      let that = this;
      let item = JSON.parse(JSON.stringify(data));
      item['number'] = number || item['number']
      if (type === 'minus' && item['number'] == 1) {
        uni.showModal({
          title: '提示',
          content: '是否确认从处方中删除该药品',
          success: (res) => {
            if (res.confirm) {
              // 根据item的id找到对应的索引
              let type = that.type;
              let index = that.servicePackage.findIndex(it => it.id === item.id)
              // 如果index有效，则执行删除和存储操作
              if (index >= 0) {
                // 根据type的值，从对应的数组中删除指定索引的元素
                that.servicePackage.splice(index, 1);
                // 定义变量key用于存储缓存键名
                let key = null
                key = uni.getStorageSync('add') ? 'addServicePackage' : 'servicePackage'
                // 将修改后的数组存储到缓存中，如果数组为空则存储默认值
                uni.setStorageSync(key, this.servicePackage)
                // 调用getDrug方法，可能用于更新药物数据
                that.getDrug()
              } else {
                // 如果index无效，清空所有数组和相关缓存
                this.servicePackage = []
                uni.removeStorageSync(uni.getStorageSync('add') ? 'addServicePackage' : 'servicePackage')
                // 同样，设置缓存，存储空的数组结构
                uni.setStorageSync(uni.getStorageSync('add') ? 'addServicePackage' : 'servicePackage', [{
                  item: [],
                  obj: {}
                }])
              }
            }
          }
        });
        this.$set(item, 'number', item['number'])
        return
      }
      item['number'] != 0 && type === 'minus' && item['number']--;
      item['number'] < item.stock && type === 'plus' && item['number']++
      this.setDrug(item);
    },

    // 添加西药
    handleAdd(item, i) {
      // console.log(item, 'item')
      this.show = true
      this.info = {
        ...item
      }
      this.index = i
      this.shownum = true
    },
    setChecked(id) {
      this.list[this.current] = this.list[this.current].map(item => {
        if (item.id == id) {
          item.checked = !item.checked
        }
        return item
      })
    },
  }
}
</script>

<style lang="scss">
.search {
  padding: 16rpx 32rpx;
}

.btn {
  width: 710rpx;
  margin: 20rpx auto;
  position: fixed;
  left: 2.2%;
  bottom: 20rpx;
  z-index: 999;
}

.minus {
  width: 64rpx;
  height: 64rpx;
  background-color: #F9FAFB;
  border-top-left-radius: 8rpx;
  border-bottom-left-radius: 8rpx;
}

.plus {
  width: 64rpx;
  height: 64rpx;
  background-color: #2979FF;
  border-top-right-radius: 8rpx;
  border-bottom-right-radius: 8rpx;
}

.input {
  width: 122rpx;
  height: 64rpx;
  background-color: #F3F4F5;
}

.bottom {
  position: fixed;
  width: 100vw;
  box-sizing: border-box;
  bottom: env(safe-area-inset-bottom);
  left: 0;
  background-color: #fff;
  padding: 12rpx 32rpx;

  ::v-deep button {
    z-index: 999;
    background: #6ACDBB;
    color: #FFFFFF;
  }
}

.m-b-16 {
  ::v-deep button {
    z-index: 999;
    background: #6ACDBB;
    color: #FFFFFF;
  }
}

.text {
  width: 122rpx;
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #A7ABB0;
  text-align-last: justify;
}

.price {
  font-size: 32rpx;
  color: #F44437;
  font-weight: bold;
}

.search {
  padding: 16rpx 32rpx;
}

.colorG {
  color: #6ACDBB !important;

}

.fz24 {
  font-size: 24rpx !important;
}

.minus {
  width: 64rpx;
  height: 64rpx;
  background-color: #F9FAFB;
  border-top-left-radius: 8rpx;
  border-bottom-left-radius: 8rpx;
}

.plus {
  width: 64rpx;
  height: 64rpx;
  background-color: #6ACDBB;
  border-top-right-radius: 8rpx;
  border-bottom-right-radius: 8rpx;
}

.input {
  width: 122rpx;
  height: 64rpx;
  background-color: #F3F4F5;
}

.mtb12 {
  margin: 12rpx 0;
}

.bottom {
  position: fixed;
  width: 100vw;
  box-sizing: border-box;
  bottom: env(safe-area-inset-bottom);
  left: 0;
  background-color: #fff;
  padding: 12rpx 32rpx;
}

.text {
  width: 122rpx;
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #A7ABB0;
  text-align-last: justify;
}

.btnBox {
  height: 48rpx;
  line-height: 48rpx;
  padding: 0 20rpx;
  border-radius: 24rpx;
  border: 2rpx solid #6ACDBB;

  &.del {
    border: 2rpx solid #FC3636;
  }
}

.mb40 {
  margin-bottom: 40rpx;
}

.ml14 {
  margin-left: 14rpx;
}
</style>
