<template>
    <div class="main-contain">
        <div class="position">
            <bread-crumb :crumbs="crumbs"></bread-crumb>
            <el-button
                size="small"
                @click="setting"
                class="filter-item"
                style="float:right;"
                type="primary"
                >设置
            </el-button>
        </div>

        <div class="app-container">
            <div class="cell clearfix" style="margin-bottom:0px;">
                <el-date-picker
                v-model="start_time"
                prefix-icon="el-icon-date"
                :editable="false"
                style="width: 160px;margin-right:10px;"
                type="date"
                placeholder="选择日期时间"
                align="right"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                @change="changeStartime"
                ></el-date-picker>
                 <el-autocomplete
                  style="margin:16px 5px"
                  popper-class="my-autocomplete"
                  v-model.trim="search_input"
                  :fetch-suggestions="querySearchAsync"
                  :trigger-on-focus="false"
                  placeholder="病人名字或者透析号"
                  @select="handleSelect"
                >
                  <i class="el-icon-search el-input__icon" slot="suffix"> </i>
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.name }}</div>
                  </template>
                </el-autocomplete>
                <el-button type="primary" @click="toSeachPatient">搜索</el-button>
            </div>
            <el-container>
                <div style="width:160px;">
                    <div class="tablesTitle">患者列表</div>
                    <el-table :data="tablePatient" border style="width: 100%;" height="500" :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}" highlight-current-row
                    @current-change="handleCurrentChange"  ref="monthlyPlanTable"
                    >
                        <el-table-column align="center" prop="dialysis_no" label="透析号" width="70">
                            <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="姓名" width="90">
                            <template slot-scope="scope">{{ scope.row.name }}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <div style="flex:1;margin-left:20px;">
                    <div style="display:flex;justify-content: space-between;align-items: center;">
                        <div class="tablesTitle">自备药列表</div>
                        <div>
                            <el-button type="primary" size="mini" @click="openForm(1)">添加</el-button>
                            <el-button type="primary" size="mini" @click="openForm(2)">入库</el-button>
                            <el-button type="primary" size="mini" @click="openForm(3)">出库</el-button>
                        </div>
                    </div>
                    <el-table :data="tableData" border style="width: 100%;" :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}" highlight-current-row>
                        <el-table-column align="center" prop="dialysis_no" label="药品名称" width="120">
                            <template slot-scope="scope">{{scope.row.drug_name}}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="规格名称">
                            <template slot-scope="scope">{{ scope.row.drug_spec }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="dialysis_no" label="单位" width="60">
                            <template slot-scope="scope">{{scope.row.min_unit}}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="自备数量" width="90">
                            <template slot-scope="scope">
                              {{getTotal(scope.row.patient_id,scope.row.id)}}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="已使用" width="90">
                            <template slot-scope="scope">{{getCountTwo(scope.row.patient_id,scope.row.drug_name,scope.row.drug_spec)}}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="剩余" width="90">
                            <template slot-scope="scope">{{getTotal(scope.row.patient_id,scope.row.id)- getCountTwo(scope.row.patient_id,scope.row.drug_name,scope.row.drug_spec)}}</template>
                        </el-table-column>
                        <!-- <el-table-column align="center" prop="name" label="停用" width="90">
                            <template slot-scope="scope">
                                <el-switch v-model="value1">
                                </el-switch>
                            </template>
                        </el-table-column> -->
                        <el-table-column align="center" prop="name" label="备注">
                            <!-- <template slot-scope="scope">{{ scope.row.remarks }}</template> -->
                            <template slot-scope="scope">
                                {{getRemarks(scope.row.patient_id,scope.row.id)}}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="操作" width="180">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" @click="toDetail(scope.row.drug_name,scope.row.drug_spec,scope.row.patient_id)">明细</el-button>
                                <el-button size="mini" type="danger" @click="DeleteDrugNameById(scope.row.id,scope.row.drug_name,scope.row.patient_id,scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-container>
        </div>

        <el-dialog
        title="设置"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">
            <p style="margin-bottom:20px;">启用“自备药”后，在开透析医嘱时，医生可以选择自备药中的药品，且将自动出库</p>
            <el-radio v-model="radio" label="1">开启</el-radio>
            <el-radio v-model="radio" label="2">不开启</el-radio>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRadio">确 定</el-button>
            </span>
        </el-dialog>
        <add-medicine ref="addMedicine" @getlist="getlist"></add-medicine>
        <medicine-detail ref="medicineDetail"></medicine-detail>
        <warehousing  ref="warehousing" @getlist="getlist"></warehousing>
        <warehouse-out ref="warehouseOut" @getlist="getlist"></warehouse-out>
    </div>
</template>


<script>
import BreadCrumb from "../../components/bread-crumb";
import addMedicine from "./components/addMedicine"
import medicineDetail from "./components/medicineDetail"
import warehousing from "./components/warehousing"
import warehouseOut from "./components/warehouseOut"
const moment = require('moment')
import { PostSearch } from '@/api/patient'
import { getCurrentPatient,saveRadio,getStockList,DeleteDrugNameById,getDrugSet,getPatientDetail} from "@/api/drug/drug"
export default {
    components:{
        BreadCrumb,
        addMedicine,
        medicineDetail,
        warehousing,
        warehouseOut
    },
    data(){
        return{
            crumbs: [
                { path: false, name: "库存管理" },
                { path: false, name: "自备药管理" },
                { path: false, name: "自备药管理" },
            ],
            // options: [{
            // value: '1',
            // label: '上午'
            // }, {
            // value: '2',
            // label: '下午'
            // }, {
            // value: '3',
            // label: '晚上'
            // }],
            value: '',
            tableData:[],
            dialogVisible:false,
            radio:'2',
            tablePatient:[],
            disableBtton:false,
            currentRow: null,
            patient_name:"",
            patient_id:"",
            start_time:moment(new Date()).add('year',0).format("YYYY-MM-DD"),
            search_input:"",
            patient_id:0,
            stockList:[],
            outStocklist:[],
            outList:[]
        }
    },
    methods:{
        setting(){
            this.dialogVisible = true
        },
        handleCurrentChange(val){
          this.currentRow = val
          this.patient_name = val.name
          this.patient_id = val.id
          if(val.name !=""){
            this.disableBtton = true
          }
           
          this.getlist()
        },
        changeStartime(){
           this.getlist()
        },
        handleClose(){
          this.dialogVisible = false
        },
        openForm(index){
            if(index == 1){
              if(this.disableBtton == true){
                 this.$refs.addMedicine.show(this.patient_name,this.patient_id);
              }
              if(this.disableBtton == false){
                 this.$message.error("请选择患者!")
              }          
            }else if(index == 2){
                this.$refs.warehousing.show(this.patient_name,this.patient_id);
            }else if(index == 3){
                this.$refs.warehouseOut.show(this.patient_name,this.patient_id);
            }
            
        },
        toDetail(drugname,drugspec,patientid){
            this.$refs.medicineDetail.show(drugname,drugspec,patientid);
        },

        getCurrentPatient(){
         getCurrentPatient().then(response=>{
            if(response.data.state == 1){
              this.tablePatient = response.data.data.patient
            } 
          })
        },
        searchAction(){
          this.patient_id = 0
          this.getlist()
        },
        saveRadio(){
          const params = {
            radio:this.radio
          }
         saveRadio(params).then(response=>{
            if(response.data.state == 1){
              var drugset = response.data.data.drugSet
              this.$message.success("保存成功")
              this.dialogVisible = false
            } 
          }) 
        },
        getlist(){
            const params = {
               id:this.patient_id,
               start_time:this.start_time,
               keyword:this.search_input,
            }
         
          getStockList(params).then(response=>{
             if(response.data.state == 1){
                var medicalList = response.data.data.medicalList
                console.log("medicalist2222",medicalList)

                this.tableData = medicalList
                var stocklist =  response.data.data.stocklist
                console.log("stocklist",stocklist)
                this.stockList = stocklist
                var outstocklist = response.data.data.outStocklist
                this.outStocklist = outstocklist
                var outList =  response.data.data.outList
                console.log("outList",outList)
                this.outList = outList
              
              }
          })  
        },
        DeleteDrugNameById(id,name,patientid,index){
            console.log("id",id)
            console.log("name",name)
            console.log("patientid",patientid)
            this.$confirm('确认删除吗?', '删除', {
            confirmButtonText: '确 定',
            cancelButtonText: '取 消',
            type: 'warning'
         }).then(() => {
              const params = {
                id:id,
                drugname:name,
                patientid:patientid
              }
           
            DeleteDrugNameById(params).then(response => {
              if (response.data.state == 1) {
                  var msg = response.data.data.msg
                  this.tableData.splice(index, 1);
                  this.$message.success("删除成功")
              } else {
                  this.$message.error("药品已经出库不能删除")
              }
            })
          })
          .catch(() => {
          })
        },
        getCount(patientid,drugname,drugspec){
            var total = 0
           for(let i=0;i<this.outStocklist.length;i++){
              if(patientid == this.outStocklist[i].patient_id && drugname == this.outStocklist[i].drug_name && drugspec == this.outStocklist[i].drug_spec){
                  total = this.outStocklist[i].Count
              }
           }
           return total
        },

        getCountTwo(patientid,drugname,drugspec){
           var total = 0
           for(let i=0;i<this.outList.length;i++){
             if(patientid == this.outList[i].patient_id && drugname == this.outList[i].drug_name && drugspec == this.outList[i].drug_spec){
                  total += this.outList[i].outstore_number
              }
           }
           return total
        },

        getDrugSet(){
         getDrugSet().then(response=>{
            if(response.data.state == 1){
              var drugset =  response.data.data.drugSet
              this.radio  = drugset.drug_start.toString()
            }
         })
        },

        getTotal(patientid,id){
          var total = 0
          for(let i=0;i<this.stockList.length;i++){
             if(patientid == this.stockList[i].patient_id && id == this.stockList[i].medic_id){
                total = this.stockList[i].Total
             }
          }
          return total
        },
        getRemarks(patientid,id){
          var remarks = ""  
           for(let i=0;i<this.stockList.length;i++){
             if(patientid == this.stockList[i].patient_id && id == this.stockList[i].medic_id){
                remarks = this.stockList[i].remarks
             }
          }
          return remarks
        },

        querySearchAsync(keyword, cb) {
          let key = ''
          if (keyword != undefined) {
            key = keyword
          }
          let searchArray = []
          PostSearch(key).then(response => {
            if (response.data.state == 1) {
              searchArray = response.data.data.patient
              console.log("searchArray",searchArray)
           
              cb(searchArray)
            }
          })
          return searchArray
        },
        handleSelect(val){   
          this.search_input = val.name
          for(let i=0;i<this.tablePatient.length;i++){
             if(this.tablePatient[i].id == val.id){
               this.$refs.monthlyPlanTable.setCurrentRow(this.tablePatient[i])
             }
          }
          this.getlist()
          this.getPatientDetail(val.id)
        },

        getPatientDetail(id){
          getPatientDetail(id).then(response=>{
             if(response.data.state == 1){
               var patientDetail =  response.data.data.patientDetail
               console.log("patientDetail",patientDetail)
               var arr = []
               arr.push(patientDetail)
               this.tablePatient = arr
             }
          })
        },
        toSeachPatient(){
          this.getCurrentPatient()
        }
    },
    created(){
      //获取当前机构下的所有患者
      this.getCurrentPatient()
      this.getDrugSet()
    },
    watch: {
     tablePatient: function() {
      this.$nextTick(function() {
        this.$refs.monthlyPlanTable.setCurrentRow(this.tablePatient[0])
      })
    }
  },
}
</script>


<style lang="scss" scoped>
.tablesTitle{
    font-size: 16px;
    color: #000;
    font-weight: bold;
    height: 40px;
    line-height: 40px;
}
</style>
