<template><!--药品发药页面-->
  <div class="main-contain new-main-contain">
    <div class="position">
      <!--      <bread-crumb :crumbs='crumbs'></bread-crumb>-->
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div
      class="app-container"
      style="display: flex; flex: 1; padding: 10px 20px 0px 20px"
    >
      <div class="mainLeft">
        <div>
          <div class="list">
            <el-date-picker
              style="width: 300px"
              v-model="start_time"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :change="testsss()"
            >
            </el-date-picker>
          </div>

          <div class="list">
            <el-radio-group v-model="state">
              <el-radio :label="1">待发药</el-radio>
              <el-radio :label="2">已发药</el-radio>
            </el-radio-group>
          </div>
          <div class="list">
            <el-input
              size="small"
              style="width: 239px"
              v-model="keywords"
              class="filter-item"
              placeholder="请输入药品名称"
            />
            <el-button
              size="small"
              class="filter-item"
              type="primary"
              @click="searchAction"
              >搜索
            </el-button>
          </div>

          <el-table
            v-if="state == 1"
            :height="tableHeight"
            :data="tableData"
            border
            style="width: 100%"
            highlight-current-row
            ref="singleTable"
            @current-change="handleCurrentChange"
          >
            <el-table-column prop="name" label="名称" width="100">
               <template slot-scope="scope">
                {{scope.row.drug_name}}
              </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格" width="100">
              <template slot-scope="scope">
                {{scope.row.dose}}{{scope.row.dose_unit}}*{{scope.row.min_number}}{{scope.row.min_unit}}/{{scope.row.max_unit}}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100">
               <template slot-scope="scope">
                {{getWarehoseInfo(scope.row.drug_warehouse_info,scope.row.max_unit,scope.row.min_unit,scope.row.min_number)}}
              </template>
            </el-table-column>
          </el-table>

          <el-table
            v-if="state == 2"
            :height="tableHeight"
            :data="tableData"
            border
            style="width: 100%"
            highlight-current-row
            @current-change="handleSelectionChangeOne"
            ref="singleTable"
          >
            <el-table-column prop="name" label="名称" width="100">
               <template slot-scope="scope">
                {{scope.row.drug_name}}
              </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格" width="100">
              <template slot-scope="scope">
                {{scope.row.dose}}{{scope.row.dose_unit}}*{{scope.row.min_number}}{{scope.row.min_unit}}/{{scope.row.max_unit}}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100">
               <template slot-scope="scope">
                {{getWarehoseInfo(scope.row.drug_warehouse_info,scope.row.max_unit,scope.row.min_unit,scope.row.min_number)}}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="mainRight">
        <div class="titlelist">
          <el-button type="primary" @click="dispense" v-if="state == 1">发药</el-button>
          <el-button type="primary" @click="toPrint">打印</el-button>
          <el-button type="primary" @click="toSetting">设置</el-button>
        </div>
        <el-divider></el-divider>
        <div>
          <el-table
            :height="tableHeight"
            :data="tableData_list"
            border
            style="width: 1328px"
            @selection-change="handleSelectionChange"
             v-if="state == 1"
          >
            >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" label="序号" width="120" align="center">
              <template slot-scope="scope">
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="患者名称" width="180" align="center">
                <template slot-scope="scope">
                 {{getPatientName(scope.row.patient_id)}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="单次用量" width="170" align="center">
               <template  slot-scope="scope">
                 {{scope.row.single_dose}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="用法" width="160" align="center">
               <template  slot-scope="scope">
                 {{scope.row.delivery_way}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="频率" width="160" align="center">
                <template  slot-scope="scope">
                 {{scope.row.execution_frequency}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="天数" width="160" align="center">
               <template  slot-scope="scope">
                 {{scope.row.day}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="总量" width="160" align="center">
                <template  slot-scope="scope">
                 {{scope.row.prescribing_number}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="数据来源" width="162" align="center">
                <template  slot-scope="scope">
                 <span v-if="scope.row.type == 1">血透</span>
                 <span v-if="scope.row.type == 2">HIS</span>
               </template>
            </el-table-column>
          </el-table>


            <el-table
            :height="tableHeight"
            :data="tableList"
            border
            style="width: 1328px"
            v-if="state == 2"
          >
            >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" label="序号" width="120" align="center">
              <template slot-scope="scope">
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="患者名称" width="180" align="center">
                <template slot-scope="scope">
                 {{getPatientName(scope.row.patient_id)}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="单次用量" width="170" align="center">
               <template  slot-scope="scope">
                 {{scope.row.single_dose}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="用法" width="160" align="center">
               <template  slot-scope="scope">
                 {{scope.row.delivery_way}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="频率" width="160" align="center">
                <template  slot-scope="scope">
                 {{scope.row.execution_frequency}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="天数" width="160" align="center">
               <template  slot-scope="scope">
                 {{scope.row.day}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="总量" width="160" align="center">
                <template  slot-scope="scope">
                 {{scope.row.prescribing_number}}
               </template>
            </el-table-column>
            <el-table-column prop="name" label="数据来源" width="162" align="center">
                <template  slot-scope="scope">
                 <span v-if="scope.row.type == 1">血透</span>
                 <span v-if="scope.row.type == 2">HIS</span>
               </template>
            </el-table-column>
          </el-table>


        </div>
        <div style="margin-top">领料人：
          <el-select v-model="admin_user_id" placeholder="请选择">
            <el-option
              v-for="item in doctorList"
              :key="item.admin_user_id"
              :label="item.user_name"
              :value="item.admin_user_id">
            </el-option>
           </el-select>
        </div>
      </div>

      <el-dialog
        title="设置"
        :visible.sync="dialogVisible"
        width="30%">
        <span>请选择药品是否要通过药房管理出库</span>
        <span>
          <el-radio v-model="is_open" label="1">是</el-radio>
          <el-radio v-model="is_open" label="2">否</el-radio>
        </span>
        <span>
          若选择为是，则通过药房发药的药品都会在发药之后进行出库，否则按原来的方式进行出库管理
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="SaveSetting">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <drug-print
      ref="drugprint"
      :visibility="isVisibility"
      :propsTable="propsTable"
      :state="state"
    >
    </drug-print>
  </div>
</template>

<script>
import drugPrint from "./print/drugPrint.vue";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import { getTodayAdviceList,getPharmacyBaseDrug,updatePharmacyBaseDrug,SaveSetting,getPharmacyConfig,getUserdDrugList } from "@/api/his/advice";
// import {
//   waitingdrug,
//   issueddrugs,
//   getpharmacycontent
// } from "@/api/pharmacy"
const moment = require('moment')
export default {
  components: {
    BreadCrumb,
    drugPrint,
  },
  data() {
    return {
      crumbs: [
        { path: false, name: "药品发药" },
        { path: "/Pharmacy/DrugDispensing", name: "药品发药" },
      ],
      tableHeight: 400,
      datepick: "",
      state: 1,
      waitmount: 0,
      alreadmount: 0,
      tableData: [],
      tableData_list: [],
      tableList:[],
      multipleSelection: [],
      start_time:moment(new Date()).add('year',0).format("YYYY-MM-DD"),
      patientList:[],
      keywords:"",
      dialogVisible:false,
      is_open:"2",
      isVisibility:"",
      propsTable:"",
      doctorList:[],
      admin_user_id:this.$store.getters.xt_user.user.id,
    };
  },

  methods: {
    testsss(){
      console.log("time",this.start_time);
    },
    //初始化
    init(){

    },
     searchAction() {
      this.getlist();
    },
    // 跳转打印页面
    toPrint() {
      // this.$router.push({ path: "/Pharmacy/print/patientPrint" });
      this.$refs.drugprint.show();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChangeOne(val){
      this.tableList = []
      this.getUserlist(val.id)
    },
    // 药品发药
    dispense() {
      var blood_ids = []
      var his_ids = []
      var bloodStr = ""
      var hisStr = ""
      for(let i=0;i<this.tableData.length;i++){
        if(this.tableData[i].type == 1){
          blood_ids.push(this.tableData[i].id)
        }
        if(this.tableData[i].type == 2){
          his_ids.push(this.tableData[i].id)
        }
      }
      bloodStr = blood_ids.join(",")
      hisStr =  his_ids.join(",")
      var params = {
        bloodStr:bloodStr,
        hisStr:hisStr,
        admin_user_id:this.admin_user_id,
      }
      this.$confirm("确定是否对该药品进行发药?", "患者发药", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning",
      }).then(() => {
        updatePharmacyBaseDrug(params).then(response=>{
           if(response.data.state == 1){
           var msg = response.data.data.msg
           var medical =  response.data.data.medical
           if(msg === 1){
             this.$message.success("发药成功!")
           }
           if(msg == 2 || msg ===3){
             this.$message.error("库存不足")
           }
         }
        })
      }).catch(() => {});
    },

    // 药品退药
    endispense() {
      var params = {};
      this.$confirm("确定是否对该药品进行退药?", "患者退药", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning",
      })
        .then(() => {})
        .catch(() => {});
    },

    getlist(){
      var params = {
        start_time:this.start_time,
        keywords:this.keywords,
      }
      getTodayAdviceList(params).then(response=>{
         if(response.data.state == 1){
           var list =  response.data.data.list
           this.$refs.singleTable.setCurrentRow(list[0])
           this.tableData = list
           var doctorlist = response.data.data.doctorlist
           this.doctorList = doctorlist
         }
      })
    },
   getWarehoseInfo(arr, max_unit, min_unit, min_number) {
      var total = 0;
      var max_str = "";
      var min_str = "";
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          total += parseInt(arr[i].stock_max_number+ arr[i].stock_min_number);
        }
      }
      if (total < min_number) {
        min_str = total + min_unit;
      }
      if (total == 0) {
        min_str = "";
        max_str = "";
      }
      if (total >= min_number) {
        if (parseInt(total / min_number) != 0) {
          max_str = parseInt(total / min_number) + max_unit;
        }
        if (total % min_number != 0) {
          min_str = (total % min_number) + min_unit;
        }
      }
      return max_str + min_str;
    },

    handleCurrentChange(row) {
      this.getPharmacyBaseDrug(row.id)
    },
    getPharmacyBaseDrug(drug_id){
      var params = {
        start_time:this.start_time,
        drug_id:drug_id,
      }
      getPharmacyBaseDrug(params).then(response=>{
        if(response.data.state == 1){
           var advicelist = response.data.data.advicelist
           for(let i=0;i<advicelist.length;i++){
             advicelist[i].type = 1
             advicelist[i].day = " "
             this.tableData_list.push(advicelist[i])
           }
           var hisAdviceList = response.data.data.hisAdviceList
           for(let i=0;i<hisAdviceList.length;i++){
             hisAdviceList[i].type = 2
             this.tableData_list.push(hisAdviceList[i])
           }
           var patient = response.data.data.patient
           this.patientList = patient
        }
      })
    },
    getPatientName(id){
       var name = ""
       for(let i=0;i<this.patientList.length;i++){
          if(id == this.patientList[i].id){
             name = this.patientList[i].name
          }
       }
       return name
    },
    toSetting(){
      getPharmacyConfig().then(response=>{
        if(response.data.state == 1){
           this.dialogVisible = true
           var config = response.data.data.config
           this.is_open = config.is_open.toString()
        }
      })
    },
    SaveSetting(){
      var params = {
        is_open:parseInt(this.is_open),
      }
     SaveSetting(params).then(response=>{
       if(response.data.state == 1){
         var config = response.data.data.config
         this.$message.success("保存成功!")
         this.dialogVisible = false
       }
     })
    },
    getUserlist(drug_id){
       var params = {
        start_time:this.start_time,
        drug_id:drug_id,
      }
      getUserdDrugList(params).then(response=>{
       if(response.data.state == 1){
           var advicelist = response.data.data.advicelist
           for(let i=0;i<advicelist.length;i++){
             advicelist[i].type = 1
             advicelist[i].day = " "
             this.tableList.push(advicelist[i])
           }
           var hisAdviceList = response.data.data.hisAdviceList
           for(let i=0;i<hisAdviceList.length;i++){
             hisAdviceList[i].type = 2
             this.tableList.push(hisAdviceList[i])
           }
           var patient = response.data.data.patient
           this.patientList = patient
        }
      })
    }
  },
  created() {
    this.init();
    this.getlist()
  },
};
</script>

<style rel="stylesheet/css" lang="scss" scoped>
.new-main-contain {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.app-container {
  height: 100%;
}
.mainLeft {
  width: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-radio {
    margin-right: 75px;
  }

  .list {
    margin: 10px 0;
  }
}
.mainRight {
  margin-left: 10px;
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  .titlelist {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
