<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">
            <el-container>
                <div style="width:250px;">
                    <div style="display:flex;justify-content: space-between;align-items: center;">
                        <div class="tablesTitle">药品名称</div>
                        <el-button type="primary" size="mini" @click="addDrug">新增</el-button>
                    </div>
                    <el-table :data="tableData" 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" type="index" label="序号" width="70">
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="名称" width="90">
                            <template slot-scope="scope">{{ scope.row.drug_name }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="name" label="操作" width="90">
                            <template slot-scope="scope">
                                <el-button size="mini" type="danger" @click="DeleteDrugById(scope.row.id,scope.row.drug_name,scope.$index)">删除</el-button>
                            </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="addRule">新增</el-button>
                        </div>
                    </div>
                    <el-table :data="rullerList" 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="60">
                            <template slot-scope="scope">{{scope.$index+1}}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="rull_name" label="规格名称">
                            <template slot-scope="scope">
                              {{ scope.row.drug_spec }}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="unit" label="单位" width="80">
                            <template slot-scope="scope">
                              {{scope.row.min_unit}}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="price" label="价格" width="80">
                            <template slot-scope="scope">
                              {{ scope.row.price }}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="drug_stock_limit" label="库存警戒" width="90">
                            <template slot-scope="scope">
                              {{ scope.row.drug_stock_limit }}
                            </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="操作" width="180">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" @click="toDetail(scope.row.id)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="DeleteDrugStand(scope.row.id,scope.row.drug_name,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>
       


        <el-dialog
        title="新增药品名称"
        :visible.sync="drugDialogVisible"
        width="50%"
        :before-close="drughandleClose">
        <span>
           <el-form style="width:100%">
              <el-row :span="24">
                <el-col :span="24">
                    <el-form-item label="药品名称:">
                        <el-select v-model="drug_name" filterable placeholder="请选择">
                            <el-option
                            v-for="item in drugName"
                            :key="item.id"
                            :label="item.drug_name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                 </el-col>
             </el-row> 
          </el-form> 
        </span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="drugDialogVisible = false">取 消</el-button>
            <el-button  @click="saveDrugName">保 存</el-button>
            <el-button type="primary" @click="saveDrugNameTwo">保 存 并 继 续 新 增</el-button>
        </span>
        </el-dialog>
        
        
        <el-dialog
        title="新增药品规格"
        :visible.sync="ruleDialogVisible"
        width="75%"
        :before-close="rullerhandleClose">
        <span>
           <el-form style="width:100%" :model="form">
              <el-row :span="24">
                <el-col :span="6">
                    <el-form-item label="规格名称:">
                       <el-select v-model="form.drug_name_id" filterable placeholder="请选择"
                       style="width:150px"
                        @change="changeRuleName">
                            <el-option
                            v-for="item in ruleName"
                            :key="item.id"
                            :label="item.drug_spec"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                 </el-col>
                  <el-col :span="6">
                    <el-form-item label="单位:">
                       <el-select v-model="form.unit" style="width:160px;" placeholder="请选择">
                        <el-option
                          v-for="(item,index) in getDataConfig('hemodialysis','units')"
                          :key="index"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                     </el-select>
                    </el-form-item>
                 </el-col>
                  <el-col :span="6">
                    <el-form-item label="价格:">
                       <el-input v-model="form.price" style="width:150px"></el-input>
                    </el-form-item>
                 </el-col>
                 <el-col :span="6">
                    <el-form-item label="库存警戒:">
                       <el-input v-model="form.drug_stock_limit" style="width:150px"></el-input>
                    </el-form-item>
                 </el-col>
             </el-row> 
          </el-form> 
        </span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="ruleDialogVisible = false">取 消</el-button>
            <el-button  @click="saveRulleName">保 存</el-button>
            <el-button type="primary" @click="saveRulleNameTwo">保 存 并 继 续 新 增</el-button>
        </span>
        </el-dialog>


        <el-dialog
        title="编辑药品规格"
        :visible.sync="editRuleDialogVisible"
        width="75%"
        :before-close="EditRullerhandleClose">
        <span>
           <el-form style="width:100%" :model="form">
              <el-row :span="24">
                <el-col :span="6">
                    <el-form-item label="规格名称:">
                      <el-select v-model="editform.drug_name_id" filterable placeholder="请选择"
                        style="width:150px" 
                        @change="changeRuleNameTwo">
                            <el-option
                            v-for="item in ruleName"
                            :key="item.id"
                            :label="item.drug_spec"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                 </el-col>
                  <el-col :span="6">
                    <el-form-item label="单位:">
                       <el-select v-model="form.unit" style="width:160px;" placeholder="请选择">
                        <el-option
                          v-for="(item,index) in getDataConfig('hemodialysis','units')"
                          :key="index"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                     </el-select>
                    </el-form-item>
                 </el-col>
                  <el-col :span="6">
                    <el-form-item label="价格:">
                       <el-input v-model="form.price" style="width:150px"></el-input>
                    </el-form-item>
                 </el-col>
                 <el-col :span="6">
                    <el-form-item label="库存警戒:">
                       <el-input v-model="form.drug_stock_limit" style="width:150px"></el-input>
                    </el-form-item>
                 </el-col>
             </el-row> 
          </el-form> 
        </span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRuleDialogVisible = false">取 消</el-button>
            <el-button  @click="updatedRulleName" type="primary">保 存</el-button>
        </span>
        </el-dialog>

        <add-medicine ref="addMedicine"></add-medicine>
        <medicine-detail ref="medicineDetail"></medicine-detail>
        <warehousing ref="warehousing"></warehousing>
        <warehouse-out ref="warehouseOut"></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"
import { getAllDrugName,saveDrugName,getdrugNameList,getStandName,getUnitByBaseId,saveRulleName,EditRullerName,updatedRulleName,DeleteDrugById,DeleteDrugStand,saveRadio,getDrugSet,getRullerList }  from "@/api/drug/drug"
 import {getDataConfig } from "@/utils/data";
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: '选项4',
            label: '龙须面'
            }, {
            value: '选项5',
            label: '北京烤鸭'
            }],
            value: '',
            tableData:[],
            dialogVisible:false,
            radio:'2',
            drugDialogVisible:false,
            options:[],
            drugName:[],
            drug_name:"",
            ruleDialogVisible:false,
            ruleName:[],
            rule_name:"",
            name:"",
            form:{
              id:"",
              drug_name_id:"",
              unit:"", 
              price:"",
              drug_stock_limit:"",
              drug_id:"",
            },
            editform:{
              drug_name_id:"",
              drug_id:""
            },
            rullerList:[],
            editRuleDialogVisible:false,
            untis:[]
        }
    },
    methods:{
        setting(){
            this.dialogVisible = true
        },
        openForm(index){
            if(index == 1){
                this.$refs.addMedicine.show();
            }else if(index == 2){
                this.$refs.warehousing.show();
            }else if(index == 3){
                this.$refs.warehouseOut.show();
            }
            
        },
        toDetail(id){
          this.editRuleDialogVisible = true
           const params = {
             id:id
           }
          EditRullerName(params).then(response=>{
            if(response.data.state == 1){
              var rullerdetail =  response.data.data.rullerDetail
              console.log("rullerdetail222",rullerdetail)
              this.form.id = rullerdetail.id
              this.editform.drug_name_id = rullerdetail.drug_name_id
              this.editform.drug_id = rullerdetail.drug_id
              var id = 0
              for(let i=0;i<this.untis.length;i++){
                 if(rullerdetail.min_unit == this.untis[i].name){
                   id = this.untis[i].id
                 }
              }
              this.form.unit = id
              this.form.price = rullerdetail.price
              this.form.drug_stock_limit = rullerdetail.drug_stock_limit
            }
          })
        },
        addDrug(){
          this.drugDialogVisible = true
        },
      
       //获取所有药品名称
        getAllDrugName(){
          getAllDrugName().then(response=>{
             if(response.data.state == 1){
               var drugName  = response.data.data.drugName
              
               this.drugName = drugName

             }
          })  
        },
        handleCurrentChange(val){
          console.log("val===",val)
          this.form.drug_id = val.id
          //获取药品规格名称
          this.getStandName(val.drug_name)
          this.getRullerList(val.id)

        },
       handleClose(){
         this.dialogVisible = false
       },
       drughandleClose(){
         this.drugDialogVisible = false
       },
       rullerhandleClose(){
         this.ruleDialogVisible = false
       },
       EditRullerhandleClose(){
         this.editRuleDialogVisible = false
       },
       saveDrugName(){
           var name = "";
           for(let i=0;i<this.drugName.length;i++){
             if(this.drugName[i].id == this.drug_name){
                name = this.drugName[i].drug_name
             }
           }
           const params = {
              drug_name:name,
              id:this.drug_name,
           }
         saveDrugName(params).then(response=>{
            if(response.data.state == 1){
              var drugname =  response.data.data.drugName
              this.getdrugNameList()
              this.$message.success("保存成功")
              this.drugDialogVisible = false
            }else{
              this.$message.error("药品名称已存在!")
            }
         })   
       },
       saveDrugNameTwo(){
           var name = ""
           for(let i=0;i<this.drugName.length;i++){
             if(this.drugName[i].id == this.drug_name){
                name = this.drugName[i].drug_name
                
             }
           }
           const params = {
              drug_name:name,
               id:this.drug_name
           }
         saveDrugName(params).then(response=>{
            if(response.data.state == 1){
              var drugname =  response.data.data.drugName
              this.$message.success("保存成功")
              this.getdrugNameList()
            }else{
              this.$message.error("药品名称已存在!")
            }
         })     
       },
       //获取所有药品
       getdrugNameList(){
         getdrugNameList().then(response=>{
           if(response.data.state == 1){
              var list =  response.data.data.list
              console.log("lsit",list)
              this.tableData = list
            }
         })    
       },

       addRule(){
          this.ruleDialogVisible = true   
       },


      //获取药品库的规格名称
       getStandName(name){
          const params = {
             name:name
          }
         getStandName(params).then(response=>{
            if(response.data.state == 1){
              var ruleName =  response.data.data.rullerlist
              console.log("ruleName22222",ruleName)
              this.ruleName  = ruleName
            }
         }) 
       },
       changeRuleName(id){
         this.form.drug_name_id = id
         this.getUnitByBaseId(id)
       },
       changeRuleNameTwo(id){
         this.editform.drug_name_id = id
         this.getUnitByBaseId(id)
       },
       getUnitByBaseId(id){
           const params = {
             id:id
           }
         getUnitByBaseId(params).then(response=>{
            if(response.data.state == 1){
              var baseList =  response.data.data.baseList
            
              this.form.unit = baseList.min_unit
              this.form.drug_stock_limit = baseList.drug_stock_limit,
              this.form.price = baseList.retail_price
              
            }
         })
       },
       saveRulleName(){
           if(this.form.drug_name_id == ""){
              this.$message.error("请选择药品规格")
              return
           }
           
           var drug_spec = ""
           var drug_name = ""
           for(let i=0;i<this.ruleName.length;i++){
              if(this.ruleName[i].id == this.form.drug_name_id){   
                drug_spec = this.ruleName[i].drug_spec
                drug_name = this.ruleName[i].drug_name
              }
           }
           
           const params = {
             drug_spec:drug_spec,
             drug_name_id:this.form.drug_name_id,
             drug_id:this.form.drug_id,
             unit:this.form.unit,
             price:this.form.price,
             drug_stock_limit:this.form.drug_stock_limit, 
             drug_name:drug_name
           }
          console.log("params",params)
         
         saveRulleName(params).then(response=>{
            if(response.data.state == 1){
              var standName =  response.data.data.RullerName
              this.$message.success("保存成功")
              this.getRullerList(standName.drug_id)
              this.ruleDialogVisible = false
              this.form.drug_name_id = ""
              this.form.unit = ""
              this.form.price = ""   
              this.form.drug_stock_limit = ""         
            }else{
              this.$message.error("该药品规格名称已存在!")
            }
         })  
       },

       saveRulleNameTwo(){
          if(this.form.drug_name_id == ""){
              this.$message.error("请选择药品规格")
              return
           }
           var drug_spec = ""
           var drug_name = ""
           for(let i=0;i<this.ruleName.length;i++){
              if(this.ruleName[i].id == this.form.drug_name_id){   
                drug_spec = this.ruleName[i].drug_spec
                drug_name = this.ruleName[i].drug_name
              }
           }
           var unit = ""
           for(let i=0;i<this.untis.length;i++){
             if(this.form.unit == this.untis[i].id){
                unit = this.untis[i].name
             }
           }
           const params = {
             drug_spec:drug_spec,
             drug_name_id:this.form.drug_name_id,
             unit:unit,
             price:this.form.price,
             drug_stock_limit:this.form.drug_stock_limit, 
             drug_name:drug_name,
             drug_id:this.form.drug_id,
           }
           
         saveRulleName(params).then(response=>{
            if(response.data.state == 1){
              var RullerName =  response.data.data.RullerName
              this.getRullerList(RullerName.drug_id)
              this.$message.success("保存成功")
              this.form.drug_name_id = ""
              this.form.unit = ""
              this.form.price = ""  
              this.form.drug_stock_limit = ""     
            }else{
              this.$message.error("该药品规格名称已存在!")
            }
         })    
       },

       updatedRulleName(){
           var drug_spec = ""
           var drug_name = ""
           for(let i=0;i<this.ruleName.length;i++){
              if(this.ruleName[i].id == this.editform.drug_name_id){   
                drug_spec = this.ruleName[i].drug_spec
                drug_name = this.ruleName[i].drug_name
              }
           }
           var unit = ""
           for(let i=0;i<this.untis.length;i++){
             if(this.form.unit == this.untis[i].id){
                unit = this.untis[i].name
             }
           }
           const params = {
             id:this.form.id,
             drug_name_id:this.editform.drug_name_id,
             drug_spec:drug_spec,
             unit:unit,
             price:this.form.price,
             drug_stock_limit:this.form.drug_stock_limit, 
             drug_name:drug_name,
             drug_id:this.editform.drug_id
           }
         updatedRulleName(params).then(response=>{
            if(response.data.state == 1){
               var rullername = response.data.data.RullerName
               console.log("rullername",rullername)
               this.$message.success("保存成功")
               this.getRullerList(rullername.drug_id)
               this.editRuleDialogVisible = false
            }else {
               this.$message.error("药品规格名称已存在")
            }
         })
       },

       DeleteDrugById(id,drugname,index){
         this.$confirm('确认删除吗?', '删除', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning'
        })
          .then(() => {
              const params ={
                id:id,
                drug_name:drugname
              }
           
            DeleteDrugById(params).then(response => {
              if (response.data.state == 1) {
                  var msg = response.data.data.msg
                  this.tableData.splice(index,1)
                  this.$message.success("删除成功",msg)
              } else {
                  this.$message.error("该药品名称下有药品规格，不能删除")
              }
            })
          })
          .catch(() => {
          })
       },

       DeleteDrugStand(id,drug_name,index){
          this.$confirm('确认删除吗?', '删除', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning'
        }).then(() => {
            DeleteDrugStand(id,drug_name,index).then(response => {
              if (response.data.state == 1) {
                  var msg = response.data.data.msg
                  this.rullerList.splice(index, 1);
                  this.$message.success("删除成功")
              } else {
                  this.$message.error("该药品信息已经为患者添加自备药不能删除")
              }
            })
          })
          .catch(() => {
          })
       },

         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
            } 
          }) 
        },

        getDrugSet(){
         getDrugSet().then(response=>{
            if(response.data.state == 1){
              var drugset =  response.data.data.drugSet
              this.radio  = drugset.drug_start.toString()
            }
         })
        },
        getRullerList(id){
           const params = {
             id:id
           }
           getRullerList(params).then(response=>{
             if(response.data.state == 1){
              this.rullerList =  response.data.data.rullerlist
             }
           })
        },
      getDataConfig(module, filed_name){
        return getDataConfig(module, filed_name)
      },
    },
    created(){
       //获取药品库所有药品名称
       this.getAllDrugName()
       this.getdrugNameList()

       //获取设置
       this.getDrugSet()
       this.untis =  getDataConfig('hemodialysis','units')
       console.log("this.untis2222",this.untis)
     
    },
    watch: {
     tableData: function() {
      this.$nextTick(function() {
        this.$refs.monthlyPlanTable.setCurrentRow(this.tableData[0])
      })
    }
  },
}
</script>


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