<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>
    <view v-if="type==1">
      <u-tabs :list="tabs" :is-scroll="false" :current="current"
              @change="loading = true;current=$event;drugList($event)" bar-width="20" active-color="#6ACDBB"
              inactive-color="#6C7380">
      </u-tabs>
    </view>
    <scroll-view scroll-y="true" style="padding-bottom: 200rpx">
      <!-- 西药 -->
      <block v-if="type==1">
        <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" v-if="!item.is_collect"
                      @click.prevent="hoarding(item.id,0)">
                  <u-icon name="plus" color="#6ACDBB" size="26"></u-icon>
                  <d-text :text="'常用药'" className="fs-24 ml14" color="#6ACDBB"></d-text>
                </view>
                <view v-else class="flex-row flex-ali-center btnBox del"
                      @click.prevent="hoarding(item.id,1)">
                  <u-icon name="minus-circle" color="#FC3636" size="30"></u-icon>
                  <d-text :text="'移除'" className="fs-24 ml14" color="#FC3636"></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>
              <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>
                <view slot="plus" class="plus flex-row flex-jus-center flex-ali-center"
                      :style="{backgroundColor:`rgba(41,121,255,${item.number>=item.stock?0.6:1})`}"
                      @click="clickHandler('plus',item,item.number)">
                  <u-icon name="plus" size="22" color="#fff"></u-icon>
                </view>
              </d-number-box>
            </view>
          </view>
        </view>
      </block>

      <!-- 中药 颗粒 -->
      <block v-if="type==2||type==3">
        <u-checkbox-group shape="circle" icon-size="35" size="44">
          <view v-for="(item, i) in list[0]" :key="item.id"
                class="flex-row flex-jus-sp white p-32 flex-ali-center" style="width: 100vw;">
            <u-checkbox :value="item.checked" @change="changeCheckbox(item,0)" :name="item.id">
            </u-checkbox>
            <view class="flex-col flex-1">
              <view class="flex-row flex-jus-sp flex-ali-center">
                <d-text :text="item.drug_name||item.name" className="content-c fs-3"></d-text>
                <view class="flex-row flex-ali-end" v-if="item.price">
                  <d-text
                      :text="item.price.split('.').length>0?'￥':'￥'+item.price"
                      className="fs-24 error-c">
                  </d-text>
                  <block v-if="item.price.split('.').length>0">
                    <d-text :text="item.price.split('.')[0]" className="fs-3 error-c"
                            :bold="true">
                    </d-text>
                    <d-text text="." className="fs-24 error-c"></d-text>
                    <d-text :text="item.price.split('.')[1]"
                            className="fs-24 error-c"></d-text>
                  </block>
                </view>
              </view>
              <d-text :text="'单位：克'"></d-text>
            </view>
          </view>
        </u-checkbox-group>
        <view class="bottom flex-row flex-jus-sp flex-ali-center" style="border-bottom: 2rpx solid #F2F3F5;">
          <d-text :text="`已选（${getSelect}）`" className="fs-32 content-c" @click="affirmShow=true"></d-text>
          <u-button :throttle-time="0"
                    :custom-style="{heigth:'86rpx',width:'478rpx',backgroundColor:'#6ACDBB',color:'#fff'}"
                    shape="circle" @click="show=true;info=getList;" :disabled="!getSelect">
            下一步
          </u-button>
        </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']?true:false">
    </add-set-usage>

    <!-- 中药 颗粒 -->
    <u-popup v-model="affirmShow" mode="bottom" :closeable="true" @close="$emit('close')" close-icon-pos='top-right'
             :safe-area-inset-bottom="true" :mask-close-able="false">
      <view class="flex-row flex-jus-center flex-ali-center m-t-3">
        <d-text text="已选择" className="fs-32 tips-c"></d-text>
      </view>
      <view class="m-t-4 p-row-52 flex-col">
        <view class="bottom-border p-col-32 flex-row flex-jus-sp flex-ali-center"
              v-for="(item,index) in getList" :key="index">
          <d-text :text="item.drug_name" className="fs-32 content-c"></d-text>
          <d-text text="移除" className="fs-32 primary-c" @click="setChecked(item.id)"></d-text>
        </view>
      </view>
      <view class="m-t-4 m-b-16">
        <u-button :throttle-time="0"
                  :custom-style="{heigth:'86rpx',width:'646rpx',backgroundColor:'#6ACDBB',color:'#fff'}"
                  shape="circle" @click="affirmShow=false" :disabled="!getSelect">
          确定
        </u-button>
      </view>
    </u-popup>
  </view>
</template>

<script>
import mixin from './mixin/mixin.js';
import addSetUsage from './components/add-setUsage.vue'
import {
  westList,
  chineseList,
  searchChinese,
  searchWest,
  westCommon,
  chineseCommon,
  westCollection,
  westUncollect,
  granularList,
} from '@/api/all.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 = [];
      this.type == 1 && (arr = this.wests)
      this.type == 2 && (arr = this.chineses)
      this.type == 3 && (arr = this.granular)
      // console.log(arr, 'this.granular')
      list = list.map((item) => {
        let it = arr.find(it => it['id'] == item.id) || {}
        const obj = {
          ...item,
          ...it,
          is_add: it['id'] ? true : false,
          stock: item['stock'] - (it['number'] || 0)
        }
        return obj
      });
      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 = op['type'] || 0;
    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(current = 0) {
      this.list[this.current] = []
      let res = {}
      if (current == 0) {
        // 西药列表
        this.type == 1 && (res = await westList({
          name: this.keyword,
          store_id: uni.getStorageSync('store_id') || '11001'
        }))
        // 中药列表
        this.type == 2 && (res = await chineseList({
          name: this.keyword,
          store_id: uni.getStorageSync('store_id') || '11001'
        }))
        this.type == 3 && (res = await granularList({
          name: this.keyword,
          store_id: uni.getStorageSync('store_id') || '11001'
        }))
      } else {
        // 常用药-西药
        this.type == 1 && (res = await westCommon({
          name: this.keyword,
          store_id: uni.getStorageSync('store_id') || '11001'
        }))
        // 常用药-中药
        this.type == 2 && (res = await chineseCommon({
          store_id: uni.getStorageSync('store_id') || '11001'
        }))
      }
      if (res.errcode == 0) {
        if (this.type == 2) {
          this.list[this.current] = res.data
          for (var i = 0; i < this.list[this.current].length; i++) {
            let id = this.list[this.current][i]['id']
            let chinese = this.chineses[this.idx]['item'].find(it => it['id'] == id) || {}
            if (id == chinese['id']) {
              this.list[this.current][i] = chinese
            }
          }
        }
        if (this.type == 3) {
          this.list[this.current] = res.data
          for (var i = 0; i < this.list[this.current].length; i++) {
            let id = this.list[this.current][i]['id']
            let granular = this.granular[this.idx]['item'].find(it => it['id'] == id) || {}
            if (id == granular['id']) {
              this.list[this.current][i] = granular
            }
          }
        }

        if (this.type == 1) {
          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 : [])
        }
        this.$nextTick(() => {
          this.loading = false
          uni.hideLoading()
        })
      } else {
        this.loading = false
        this.$toast(res.msg)
      }
    },
    clickHandler(type, data, number) {
      // TODO 这里有Bug
      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 index = that.wests.findIndex(it => it['id'] == item['id'])
              // 定义变量type，根据tabsActive的值决定数组操作的类型
              let type = that.type;
              switch (type) {
                case 1:
                  index = that.wests.findIndex(it => it['id'] == item['id'])
                  break;
                case 2:
                  index = that.chineses.findIndex(it => it['id'] == item['id'])
                  break;
                case 3:
                  index = that.granular.findIndex(it => it['id'] == item['id'])
                  break;
              }
              console.log(index, 'sssssssssss')
              // 如果index有效，则执行删除和存储操作
              if (index >= 0) {
                // 根据type的值，从对应的数组中删除指定索引的元素
                type == 1 && that.wests.splice(index, 1);
                type == 2 && that.chineses.splice(index, 1);
                type == 3 && that.granular.splice(index, 1);
                // 定义变量key用于存储缓存键名
                let key = null
                // 根据type和缓存标志决定key的值
                if (type == 1) {
                  key = uni.getStorageSync('add') ? 'addWests' : 'wests'
                }
                if (type == 2) {
                  key = uni.getStorageSync('add') ? 'addChineses' : 'chineses'
                }
                if (type == 3) {
                  key = uni.getStorageSync('add') ? 'addGranular' : 'granular'
                }
                // 将修改后的数组存储到缓存中，如果数组为空则存储默认值
                uni.setStorageSync(key, type == 1 ? this.wests : type == 2 ? this.chineses.length == 0 ? [{
                  item: [],
                  obj: {}
                }] : this.chineses : this.granular.length == 0 ? [{
                  item: [],
                  obj: {}
                }] : this.granular)
                // 调用getDrug方法，可能用于更新药物数据
                that.getDrug()
              } else {
                // 如果index无效，清空所有数组和相关缓存
                this.wests = []
                this.chineses = []
                this.granular = []
                uni.removeStorageSync(uni.getStorageSync('add') ? 'addWests' : 'wests')
                // 日志输出，可能用于调试
                console.log(1);
                // 同样，设置缓存，存储空的数组结构
                uni.setStorageSync(uni.getStorageSync('add') ? 'addChineses' : 'chineses', [{
                  item: [],
                  obj: {}
                }])
                uni.setStorageSync(uni.getStorageSync('add') ? 'addGranular' : 'granular', [{
                  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>