<template>
  <div v-loading="loading"
       element-loading-text="保存中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)"
       style="height:100%;">
    <div class="page_addDialysisConsumables">
      <van-sticky>
        <div class="addDialysisConsumablesTitle">
          <span><i class="iconfont icon-zuojiantou jiantou" @click="$router.go(-1)"></i>返回</span>
          <span class="titleName">添加耗材出库</span>
          <span>{{this.$route.query.name}}</span>
        </div>
      </van-sticky>
      <div class="addDialysisConsumablesMain">
        <van-sidebar v-model="activeKey">
          <van-sidebar-item v-for="(item,index) in list" :key="index" :title="item.good_type_name" :dot="list[index].allCount > 0"/>
        </van-sidebar>
        <div style="flex:1;overflow-y: auto;background:#fff;">
          <div class="page_consumables" v-if="list[activeKey].good_info.length > 0">
            <div class="consumablesCell" v-for="(item,index) in list[activeKey].good_info" :key="index">
              <div class="consumablesCellTop">
                <span style="width:70%;">{{item.good_specification_name}}</span>
                <van-stepper min="-1000000" v-model="item.count" theme="round" button-size="22" disable-input  />
              </div>
              <div class="consumablesCellTop" style="margin-bottom:10px;" v-if="item.stock_attribute == 2 || item.stock_attribute == 3">
                <div>商品编码:</div><el-input v-model="item.commdity_code" style="flex:1;"></el-input>
              </div>
            </div>
          </div>

          <div class="noDateTxt" v-if="list[activeKey].good_info.length == 0">暂无商品信息</div>
        </div>
      </div>
      <div class="determine" @click="comfirm"><div>确定</div></div>
    </div>

     <van-popup v-model="infor_visibility" class="advicePopup" get-container="#today_panel">
          <infor-sub-menu
          :visibility="infor_visibility"
          v-on:menu-cancle-three="menuCancleFour"
          v-on:menu-comfirm-three="menuComfirmFour"
          >
         </infor-sub-menu>
     </van-popup>
  </div>
</template>

<script>
import {Toast} from 'vant'
import consumables from './components/consumables'
import {createDialysisBeforePrepare, editDialysisBeforePrepare, getStockInGoodInfo,saveMobileInformation} from '@/api/dialysis'
import { config } from 'process'
import InforSubMenu from '../dialog/subMenu/InforSubMenu.vue'
export default {
  props: {
    isEdit: 0
  },
  components: {
    consumables,
    InforSubMenu
  },
  data () {
    return {
      activeKey: 0,
      value: 0,
      list: [
        {
          good_user: [],
          good_type_id: 0,
          good_type_name: '',
          good_info: [
            {
              good_type_id: 0,
              good_id: 0,
              good_specification_name: '',
              count: 0
            }
          ]
        }
      ],
      sub_list: [],
      good_type: [],
      query: {
        patient_id: this.$route.query.patient_id,
        record_time: this.$route.query.record_time
      },
      loading: false,
      good_code: '',
      prescription: {},
      active: 0,
      infor_visibility:false,
      active: 0,
      showDisAbled:false,
      projectList:[],
    }
  },
  created () {
    this.getStockInGoodInfo()
  },
  methods: {
    menuCancleFour(){
        this.infor_visibility = false
      },
      menuComfirmFour:function(start_time,remark){
        var params = {
          patient_id:this.$route.query.patient_id,
          record_date:this.$route.query.date,
          start_time:start_time,
          module:11,
          remark:remark,
        }
        // console.log("params2222222",params)
        saveMobileInformation(params).then(response=>{
          if(response.data.state == 1){
            this.infor_visibility = false
            Toast.success('申请成功')
          }
        })
     },
    comfirm () {
      this.loading = true
      let uploadArr = []
      let newUploadArr = []

      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].good_info) {
          for (let a = 0; a < this.list[i].good_info.length; a++) {
            if (this.list[i].good_info[a].id > 0) {
              uploadArr = uploadArr.concat(this.list[i].good_info[a])
            }

            if (this.list[i].good_info[a].count > 0 && this.list[i].good_info[a].id == 0) {
              newUploadArr = newUploadArr.concat(this.list[i].good_info[a])
            }
          }
        }
      }
      for (let i = 0; i < uploadArr.length; i++) {
        uploadArr[i].count = uploadArr[i].count.toString()
      }

      for (let i = 0; i < newUploadArr.length; i++) {
        newUploadArr[i].count = newUploadArr[i].count.toString()
      }

      if (newUploadArr.length > 0) {
        var obj = {}
        newUploadArr = newUploadArr.reduce((cur, next) => {
          // eslint-disable-next-line no-unused-expressions
          obj[next.good_id] ? '' : obj[next.good_id] = true && cur.push(next)
          return cur
        }, []) // 设置cur默认类型为数组，并且初始值为空的数组
      }

      if (uploadArr.length > 0) {
        var obj = {}
        uploadArr = uploadArr.reduce((cur, next) => {
          obj[next.good_id] ? '' : obj[next.good_id] = true && cur.push(next)
          return cur
        }, []) // 设置cur默认类型为数组，并且初始值为空的数组
      }

      if (this.$route.query.is_edit == 1) { // 创建
        let params = {
          patient_id: this.$route.query.patient_id,
          record_time: this.$route.query.record_time,
          active: this.$route.query.active
        }
        for (let i = 0; i < uploadArr.length; i++) {
          newUploadArr.push(uploadArr[i])
        }
        const data = {
          'goods': newUploadArr,
          'update_goods': uploadArr
        }

        createDialysisBeforePrepare(params.patient_id, params.record_time, data, params.active).then(rs => {
          var res = rs.data
          if (res.state == 1) {
            var msg = res.data.message
            var good_name = res.data.good_name
            var specification_name = res.data.specification_name
            if (specification_name != '' && msg == 1) {
              var str = good_name + '*' + specification_name + '无库存,请入库'
              this.loading = false
              this.$toast(str)
            } else {
              this.loading = false
              this.$router.go(-1)
            }
          } else {
            if(res.code == 600000008){
              Toast(res.msg)
              this.infor_visibility = true
            }
            this.loading = false
          
            Toast('库存不足')
          }
        })
      } else { // 编辑
        let params = {
          patient_id: this.$route.query.patient_id,
          record_time: this.$route.query.record_time,
          active: this.$route.query.active
        }
        for (let i = 0; i < newUploadArr.length; i++) {
          uploadArr.push(newUploadArr[i])
        }
        newUploadArr = []
        const data = {
          'goods': uploadArr,
          'new_goods': newUploadArr
        }

        editDialysisBeforePrepare(params.patient_id, params.record_time, data).then(rs => {
          var res = rs.data
          if (res.state == 1) {
            var msg = res.data.message
            var good_name = res.data.good_name
            var specification_name = res.data.specification_name
            if (specification_name != '' && msg == 1) {
              var str = good_name + '*' + specification_name + '无库存,请入库'
              this.loading = false
              this.$toast(str)
            } else {
              this.loading = false
              this.$router.go(-1)
            }
          } else {
             if(res.code == 600000008){
                this.infor_visibility = true
             }
            this.loading = false

            Toast('库存不足')
          }
        })
      }
    },
    getStockInGoodInfo: function () {
      getStockInGoodInfo(this.query).then(rs => {
        var res = rs.data
        if (res.state == 1) {
          this.list = []
          let good_types = res.data.good_type
          let stock_ins = res.data.good_info
          let good_user = res.data.good_user
          let last_good_user = res.data.last_good_user
          let project = res.data.project
          // console.log("project------------",project)
          this.projectList = project
          let out_info = res.data.outInfo
          // console.log('out_info23323232323', out_info)
          var arr = project

          let configs = res.data.configs
          // console.log('configs222222wo', configs)
          if (project != undefined && project.length > 0) {
            for (let i = 0; i < arr.length; i++) {
              arr[i].total = 0
              arr[i].child = []
              for (let j = 0; j < project.length; j++) {
                if (arr[i].project_id == project[j].project_id) {
                  arr[i].child.push(project[j])
                }
              }
            }
          }

          if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].child != undefined && arr[i].child.length > 0) {
                for (let j = 0; j < arr[i].child.length; j++) {
                  arr[i].total += parseInt(arr[i].child[j].count)
                }
              }
            }
          }
          var newArr = this.unique(arr)
          for (let i = 0; i < newArr.length; i++) {
            newArr[i].count = newArr[i].total
            delete newArr[i].child
          }
          project = newArr

          // console.log('projectwode shijw323232332wo', project)

          if (project.length > 0) {
            for (let i = 0; i < project.length; i++) {
              project[i].old_count = 0
              for (let j = 0; j < out_info.length; j++) {
                if (project[i].project_id == out_info[j].good_id) {
                  project[i].old_count = out_info[j].count
                }
              }
            }
          }

          var good_types_arr = []
          for (let i = 0; i < good_types.length; i++) {
            let obj = {
              good_type_id: good_types[i].id,
              good_type_name: good_types[i].type_name,
              good_info: []
            }
            for (let b = 0; b < stock_ins.length; b++) {
              if (good_types[i].id == stock_ins[b].good_type_id) {
                let obj2 = {
                  id: 0,
                  stock_attribute: good_types[i].stock_attribute,
                  good_type_id: good_types[i].id,
                  good_id: stock_ins[b].id,
                  good_specification_name: stock_ins[b].specification_name,
                  count: 0,
                  commdity_code: stock_ins[b].commdity_code,
                  project_id: 0
                }
                obj.good_info.push(obj2)

                let obj3 = {}
                obj.good_info = obj.good_info.reduce((cur, next) => {
                  obj3[next.good_id] ? '' : obj3[next.good_id] = true && cur.push(next)
                  return cur
                }, [])
              }
            }
            good_types_arr.push(obj)
          }

          if (good_user.length > 0) {
            for (let i = 0; i < good_types_arr.length; i++) {
              let good_infos = good_types_arr[i].good_info
              for (let b = 0; b < good_infos.length; b++) {
                for (let c = 0; c < good_user.length; c++) {

                  if (good_infos[b].good_type_id == good_user[c].good_type_id && good_infos[b].good_id == good_user[c].good_id) {
                    good_infos[b].id = good_user[c].id
                    good_infos[b].count = good_user[c].count
                    good_infos[b].commdity_code = good_user[c].commdity_code
                    good_infos[b]['record_time'] = good_user[c].record_date
                    good_infos[b]['patient_id'] = good_user[c].patient_id
                    good_infos[b]['creater'] = good_user[c].creater
                    good_infos[b]['ctime'] = good_user[c].ctime
                    good_infos[b]['project_id'] = 0
                  }
                }
              }
            }
          } else {
            if (project.length > 0) {
              for (let i = 0; i < good_types_arr.length; i++) {
                let good_infos = good_types_arr[i].good_info
                for (let b = 0; b < good_infos.length; b++) {
                  for (let c = 0; c < project.length; c++) {
                    if (good_infos[b].good_type_id == project[c].good_info.good_type_id && good_infos[b].good_id == project[c].good_info.id) {
                      if (project[c].count - project[c].old_count != 0) {
                        // 改动
                        good_infos[b].count = project[c].count - project[c].old_count
                      } else {
                        good_infos[b].count = project[c].count
                      }
                      good_infos[b].commdity_code = project[c].good_info.commdity_code
                      good_infos[b]['patient_id'] = this.$route.query.patient_id
                      good_infos[b]['record_time'] = project[c].record_date
                      good_infos[b]['project_id'] = project[c].project_id
                    }
                  }
                }
              }
            } else {
              if (last_good_user != null && last_good_user.length > 0) {
                if (configs != undefined && configs.is_open != 1) {
                  for (let i = 0; i < good_types_arr.length; i++) {
                    let good_infos = good_types_arr[i].good_info
                    for (let b = 0; b < good_infos.length; b++) {
                      for (let c = 0; c < last_good_user.length; c++) {
                        if (good_infos[b].good_type_id == last_good_user[c].good_type_id && good_infos[b].good_id == last_good_user[c].good_id) {
                          good_infos[b].count = last_good_user[c].count
                          good_infos[b]['record_time'] = last_good_user[c].record_date
                          good_infos[b]['patient_id'] = last_good_user[c].patient_id
                          good_infos[b]['project_id'] = 0
                        }
                      }
                    }
                  }
                }
              }
            }
          }

          this.list = good_types_arr
          // console.log('恭喜发财', this.list)

          if(this.list!=null && this.projectList!=null && this.projectList.length >0){
            for(let i=0;i<this.list.length;i++){
              for(let j=0;j<this.list[i].good_info.length;j++){
                for(let z=0;z<this.projectList.length;z++){
                   if(this.list[i].good_info[j].good_id == this.projectList[z].project_id){
                    this.list[i].good_info[j].project_id = this.projectList[z].id
                   }
                }
              }
            }
          }

          this.activeKey = 0

          var prescription = res.data.prescription

          this.prescription = prescription
          var dialyzer = []
          var irrigation = []
          var dialysisStrainer = []


          if (this.prescription != null && configs.is_open == 1) {
            // 透析器
            dialyzer = (this.prescription.dialysis_dialyszers).split(',')
            // console.log('dialyzer', dialyzer)
            // 灌流器
            irrigation = (this.prescription.dialysis_irrigation).split(',')
            // console.log('irrigation', irrigation)

            dialysisStrainer = (this.prescription.dialysis_strainer).split(',')
            // console.log('dialysisStrainer-------', dialysisStrainer)
            for (let i = 0; i < this.list.length; i++) {
              for (let j = 0; j < this.list[i].good_info.length; j++) {
                for (let z = 0; z < dialyzer.length; z++) {
                  if (this.list[i].good_info[j].good_specification_name === dialyzer[z]) {
                    if (this.list[i].good_info[j].count == 0) {
                      this.list[i].good_info[j].count = 1
                    }
                    if (this.list[i].good_info[j].count != 0 && this.list[i].good_info[j].record_time == undefined) {
                      this.list[i].good_info[j].count = 1
                    }
                  }
                }

                for (let y = 0; y < irrigation.length; y++) {
                  if (this.list[i].good_info[j].good_specification_name === irrigation[y]) {
                    if (this.list[i].good_info[j].count == 0) {
                      this.list[i].good_info[j].count = 1
                    }
                    if (this.list[i].good_info[j].count != 0 && this.list[i].good_info[j].record_time == undefined) {
                      this.list[i].good_info[j].count = 1
                    }
                  }
                }

                for (let y = 0; y < dialysisStrainer.length; y++) {
                  if (this.list[i].good_info[j].good_specification_name === dialysisStrainer[y]) {
                    if (this.list[i].good_info[j].count == 0) {
                      this.list[i].good_info[j].count = 1
                    }
                    if (this.list[i].good_info[j].count != 0 && this.list[i].good_info[j].record_time == undefined) {
                      this.list[i].good_info[j].count = 1
                    }
                  }
                }
              }
            }
            this.list.map(item => {
              let allCount = 0
              if (item.good_info.length > 0) {
                item.good_info.map(it => [
                  allCount += it.count
                ])
                item.allCount = allCount
              } else {
                item.allCount = 0
              }
            })
          }

        this.list.map(item => {
          let allCount = 0
          if (item.good_info.length > 0) {
            item.good_info.map(it => [
              allCount += it.count
            ])
            item.allCount = allCount
          } else {
            item.allCount = 0
          }
        })
       }
      })


    },
    unique (arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.project_id) && res.set(arr.project_id, 1))
    },

  }
}
</script>

<style lang="scss" scoped>
  .page_addDialysisConsumables {
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
    background: #fafafa;
    display: flex;
    flex-direction: column;
    padding-bottom: 3.125rem;
  .determine {

    position: fixed;
    left: 0;
    bottom: 0;
    z-index:999;
    font-size: 1rem;
    width: 100%;
    background: #fff;

    height: 3.125rem;
    display: flex;
    justify-content: space-between;
    padding: 0 1rem;
    align-items: center;
    font-size: 1rem;
  >:first-child{
    text-align: center;
    height: 2.5rem;
    width: 100%;
    line-height: 2.5rem;
    background: #409eff;
    color:#fff;
    border-radius: 4px;
  }
  }
  .addDialysisConsumablesTitle {
    background: #fff;
    padding: 0 1.125rem;
    height: 3.125rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 1rem;

  span {
    font-size: .875rem;
  }

  }
  .jiantou {
    font-size: 1rem;
    font-weight: 600;
  // margin-right: 1rem;
  }

  .titleName {
    font-size: 1.125rem;
    font-weight: 600;
  }

  .van-sidebar {
    width: 5rem;
  }

  .van-sidebar-item {
    position: relative;
    display: block;
    box-sizing: border-box;
    padding: 1.25rem .75rem;
    overflow: hidden;
    color: #323233;
    font-size: .875rem;
    line-height: 1.25rem;
    word-wrap: break-word;
    background-color: #f7f8fa;
    cursor: pointer;
    -webkit-user-select: none;
    user-select: none;
  }

  .van-sidebar-item--select::before {
    position: absolute;
    top: 50%;
    left: 0;
    width: .25rem;
    height: 1.875rem !important;
    background-color: #1989fa;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    content: '';
  }
  .van-sidebar-item--select, .van-sidebar-item--select:active{
    color:#1989fa;
  }

  .addDialysisConsumablesMain {
    display: flex;
    padding-bottom: 3.125rem;
    height:100%;
  }
  .noDateTxt{
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-10%,-50%);
    font-size:.875rem;
    color:#999;
  }

  }
</style>

<style lang="scss">
  .page_addDialysisConsumables {

  .van-stepper--round .van-stepper__minus {
    color: #258ffc;
    background-color: #fff;
    border: 1px solid #258ffc;
  }

  .van-stepper--round .van-stepper__plus {
    color: #fff;
    background-color: #258ffc;
  }

  .van-stepper__input {
    box-sizing: border-box;
    width: 1.875rem;
    height: 1.75rem;
    margin: 0 2px;
    padding: 0;
    color: #323233;
    font-size: .875rem;
    line-height: normal;
    text-align: center;
    vertical-align: middle;
    background-color: #f2f3f5;
    border: 0;
    border-width: 1px 0;
    border-radius: 0;
    -webkit-appearance: none;
  }
  .van-info--dot{
    background-color: #258ffc;
    padding:.25rem;
    height:.5625rem;
    width: .5625rem;
  }

  }

  .page_consumables {
    width: 100%;

  .consumablesCell {
    font-size: 1rem;
    padding: 0 1rem;
  // height: 1.66rem;
    border-bottom: 1px solid #e5e5e5;
    color:#323233 !important;
  }
  .consumablesCellTop{
    display: flex;
    align-items: center;
    justify-content: space-between;
    height:2.5rem;
  >div{
    width:6.25rem
  }
  }

  > div:last-child {
    border: none;
  }

  }
</style>
