<template>
  <div class="page_drugs">
    <div style="display:flex;justify-content: space-between;width:100%;margin-bottom:20px;">
      <div class="cell clearfix" style="margin-bottom:0;">
        <el-input style="width: 180px;margin-right:10px;" @keyup.enter.native='searchAction' v-model.trim="search_input"
                  class="filter-item" v-model="keywords"/>
        <el-button style="margin-right:10px;" class="filter-item" type="primary" icon="el-icon-search"
                   @click="searchAction">搜索
        </el-button>
        <!-- <label class="title"><span class="name">是否启用</span> : </label>
        <el-select v-model="is_use" style="width:140px;margin-right:10px;" placeholder="请选择" @change="changeUser">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select> -->
       <label class="title"><span class="name">生产厂商</span> : </label>
        <el-select v-model="manufacturer" style="width:140px;margin-right:10px;" placeholder="请选择" @change="changeManufacture">
          <el-option
            v-for="item in manufacturers"
            :key="item.id"
            :label="item.manufacturer_name"
            :value="item.id">
          </el-option>
        </el-select>
        <label class="title"><span class="name">是否收费</span> : </label>
        <el-select v-model="is_charge" style="width:140px;margin-right:10px;" placeholder="请选择" @change="changeCharge">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!-- <span style="color: #909399;font-size:14px;">是否注射类别 : &nbsp;</span>
        <el-select v-model="is_inject" style="width:140px;margin-right:10px;" placeholder="请选择" @change="changeInject">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select> -->

        <span style="color: #909399;font-size:14px;">备案 : &nbsp;</span>
        <el-select v-model="is_record" style="width:140px;margin-right:10px;" placeholder="请选择" @change="changeRecord">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div>
        <el-button type="primary" @click="openForm(0)">新增</el-button>
        <el-button type="primary" @click="BatchDelete()">批量备案</el-button>
      </div>
    </div>
    <el-table :data="list" border style="width: 100%" :row-style="{ color: '#303133' }"
              :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)', color: '#606266'}"
             @selection-change="handleSelectionChange">
       <el-table-column
          align="center"
          type="selection"
          width="55"
       ></el-table-column>        
      <el-table-column type="index" label="序号" width="60px" align="center"></el-table-column>

      <el-table-column prop="date" label="药品名称" align="center" width="100">
        <template slot-scope="scope">
          <div>{{scope.row.drug_name}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="规格" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.drug_spec}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="最大单位" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.max_unit}}</div>
        </template>
      </el-table-column>
      <el-table-column label="最小单位" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.min_unit}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="进货价" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.last_price}}</div>
        </template>
      </el-table-column>
      <el-table-column label="零售价" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.retail_price}}</div>
        </template>
      </el-table-column>
       <el-table-column prop="date" label="医保编码" width="100" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.medical_insurance_number}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="药品本位码" width="100" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.code}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="生产厂商" align="center" width="100">
        <template slot-scope="scope">
          <div>{{getName(scope.row.manufacturer)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="经销商" align="center" width="100">
        <template slot-scope="scope">
          <div>{{getDealer(scope.row.dealer)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="备案日期" align="center" width="100">
        <template slot-scope="scope">
          <span>{{getTime(scope.row.record_date)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="药品备注" align="center" width="100">
        <template slot-scope="scope">
          <div>{{scope.row.drug_remark}}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="60" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.drug_status.indexOf('停用') == -1 ? '启用':'停用' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="250" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button @click="openForm(scope.row.id)" type="primary" size="small">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteDurg(scope.row.id,scope.$index)">删除</el-button>
        <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="toReturn(scope.row.id,scope.row.is_mark)">
          <span v-if="scope.row.is_mark == 0">备案</span>
          <span v-if="scope.row.is_mark == 1">撤消</span>
        </el-button>
        </template>
      </el-table-column>
    </el-table>
    <self-payment ref='selfPayment'></self-payment>
    <add-drugs ref='addDrugs'
               :titles="title"
               :formValue="formValue"
               :isCreated="isCreated"
               :manufacturers="manufacturers"
               v-on:dialog-comfirm="goodInfoDialogComfirm"
               v-on:dialog-cancle="goodInfoDialogCancle"

    ></add-drugs>
    <!-- <maintain ref='maintain'></maintain> -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      background
      align="right"
      style="margin-top:20px;"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

  </div>
</template>

<script>
  import axios from 'axios'
  import selfPayment from './selfPayment'
  import maintain from './maintain'
  import addDrugs from './addDrugs'
  import { GetAllManufacturer } from '@/api/stock'
  import { getDataConfig } from "@/utils/data";
  import { uParseTime } from '@/utils/tools'
  import {
    createBaseDrugLib,
    createDrugUnitSafeguard,
    createMedicineInsurancePercent,
    editBaseDrugLib,
    getBaseDrugLib,
    getBaseDrugLibList,
    deleteDurg
  } from '@/api/data'
 import {GetAllConfig } from "@/api/stock";
  export default {
    components: {
      selfPayment,
      maintain,
      addDrugs
    },
    data() {
      return {
        page: 0,
        limit: 10,
        keywords: '',
        is_use: '',
        is_charge: '',
        manufacturer:'',
        is_record:"",
        is_inject: '',
        list: [],
    
        isCreated: 1,
        manufacturers: [],
        title: '',
        formValue: {
          drug_name: '',//药品名称
          pinyin: '',//拼音
          wubi: '',//五笔输入法
          drug_alias: '',//药品别名
          drug_alias_pinyin: '',//别名拼音
          drug_alias_wubi: '',//别名五笔
          drug_category: '',//药品类别
          drug_spec: '',//药品规格
          drug_type: '',//药品类型
          drug_stock_limit: '',//库存警戒
          drug_origin_place: '',//产地
          drug_dosage_form: '',//药品剂型
          medical_insurance_level: '',//医保等级
          max_unit: '',//最大单位
          min_unit: '',//最小单位
          unit_matrixing: '',//单位换算
          retail_price: '',//零售价
          last_price: '',//上次进价
          drug_control: '',//开药控制
          number: '',//批准文号
          drug_classify: '',//药物分类
          drug_dose: '',//药品剂量
          drug_dose_unit: '',
          medical_insurance_number: '',//医保编号
          manufacturer: '', //生产产商
          pharmacology_category: '',//药理分类
          statistics_category: '',//统计分类
          code: '',//本位码
          is_special_diseases: '',//是否特病目录
          is_record: '',//是否备案
          agent: '',// 代理商
          drug_status: '',// 状态
          limit_remark: '',//限制说明
          delivery_way: '',//默认给药途径
          execution_frequency: '',//默认执行频率
          single_dose: '',//默认单次用量
          prescribing_number: '',//默认开药数量
          label: '',//标签
          sort: '',//收费项目排序
          is_use_doctor_advice: '',//是否常用医嘱
          is_default: '',//是否默认
          is_charge_predict: '',//是否收费预估项
          is_statistics_work: '',//是否统计工作量
          is_charge_use: '',//是否收费常用项
          drug_code: ''

        },
        tempFormValue: {
          drug_name: '',//药品名称
          pinyin: '',//拼音
          wubi: '',//五笔输入法
          drug_alias: '',//药品别名
          drug_alias_pinyin: '',//别名拼音
          drug_alias_wubi: '',//别名五笔
          drug_category: '',//药品类别
          drug_spec: '',//药品规格
          drug_type: '',//药品类型
          drug_stock_limit: '',//库存警戒
          drug_origin_place: '',//产地
          drug_dosage_form: '',//药品剂型
          medical_insurance_level: '',//医保等级
          max_unit: '',//最大单位
          min_unit: '',//最小单位
          unit_matrixing: '',//单位换算
          retail_price: '',//零售价
          last_price: '',//上次进价
          drug_control: '',//开药控制
          number: '',//批准文号
          drug_classify: '',//药物分类
          drug_dose: '',//药品剂量
          drug_dose_unit: '',
          medical_insurance_number: '',//医保编号
          manufacturer: '', //生产产商
          pharmacology_category: '',//药理分类
          statistics_category: '',//统计分类
          code: '',//本位码
          is_special_diseases: '',//是否特病目录
          is_record: '',//是否备案
          agent: '',// 代理商
          drug_status: '',// 状态
          limit_remark: '',//限制说明
          delivery_way: '',//默认给药途径
          execution_frequency: '',//默认执行频率
          single_dose: '',//默认单次用量
          prescribing_number: '',//默认开药数量
          label: '',//标签
          sort: '',//收费项目排序
          is_use_doctor_advice: '',//是否常用医嘱
          is_default: '',//是否默认
          is_charge_predict: '',//是否收费预估项
          is_statistics_work: '',//是否统计工作量
          is_charge_use: '',//是否收费常用项
          drug_code: ''

        },

        current_id: 0,

        search_input: '',
        total:0,
        options: [
          {
            value: '0',
            label: '全部'
          }, {
            value: '1',
            label: '已备案'
          }, {
            value: '2',
            label: '未备案'
          }],
        value: '',
       
        dealer:[],
        selectDrug:[],
      }
    },
    methods: {
      handleSizeChange(val) {
        this.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.page = val
        this.getList()
      },
      changeInject(val) {
        this.getList()

      },
      changeCharge(val) {
        this.getList()
      },
      changeUser(val) {
        this.getList()
      },
      changeManufacture(){
        this.getList()
      },
      changeRecord(){
         this.getList()
      },
      getName(id) {
        for (let i = 0; i < this.manufacturers.length; i++) {
          if (this.manufacturers[i].id == id) {
            return this.manufacturers[i].manufacturer_name
          }
        }
        return ''
      },
      getDealer(id){
        var name = ""
        for(let i=0;i<this.dealer.length;i++){
          if(this.dealer[i].id == id){
             name = this.dealer[i].dealer_name
          }
        }
        return name
      },
      goodInfoDialogComfirm: function(val) {

        //修改自备药
        var untit = ""
        var untis = getDataConfig('hemodialysis','units')
        console.log("999999",untis)
        for(let i=0;i<untis.length;i++){
           if(val.min_unit == untis[i].id){
              untit = untis[i].name
           }
        }
        if (val.id > 0) {
          //修改
          val['id'] = this.current_id
          editBaseDrugLib(val,untit).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg)
              return false
            } else {
              this.$refs.addDrugs.hide()
              this.getList()
              this.$message.success('修改成功')
            }
          })
        } else if (val.id == 0) {
          //新增
          console.log("vale222222",val)
         
          createBaseDrugLib(val).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg)
              return false
            } else {
              this.$refs.addDrugs.hide()
              this.getList()
              this.$message.success('新增成功')
            }
          })
        }
      },
      goodInfoDialogCancle: function() {
        this.$refs.addDrugs.hide()
      },
      getAllManufacturer: function() {
        this.manufacturers = []
        GetAllManufacturer().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
              var obj = {id:0,manufacturer_name:"全部"}
              this.manufacturers.push(obj)
          
            for (let i = 0; i < response.data.data.manufacturer.length; i++) {
              this.manufacturers.push(response.data.data.manufacturer[i])
            }
          
          }
        })
      },
      searchAction() {
        this.getList()
      },
      clickSelfPayment(drug_id) {
        this.$refs.selfPayment.show(drug_id, 1)
      },
      clickMainTain() {
        // this.$refs.maintain.show();
      },
      openForm(id) {
        this.current_id = id
        this.getAllManufacturer()
        if (id > 0) {
          let params = {
            id: this.current_id
          }
          getBaseDrugLib(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg)
              return false
            } else {
              for (let key in response.data.data.drug) {
                this.formValue[key] = response.data.data.drug[key]
              }

              if(this.formValue.is_special_diseases <= 0){
                this.formValue.is_special_diseases = ''
              } else{
                this.formValue.is_special_diseases = this.formValue.is_special_diseases.toString()
              }

              if(this.formValue.is_record <= 0){
                this.formValue.is_record = ''
              } else{
                this.formValue.is_record = this.formValue.is_record.toString()
              }


              if(this.formValue.is_use_doctor_advice <= 0){

                this.formValue.is_use_doctor_advice = ''
              } else{

                this.formValue.is_use_doctor_advice = this.formValue.is_use_doctor_advice.toString()


              }


              if(this.formValue.is_default <= 0){

                this.formValue.is_default = ''
              } else{

                this.formValue.is_default = this.formValue.is_default.toString()


              }

              if(this.formValue.is_charge_predict <= 0){

                this.formValue.is_charge_predict = ''
              } else{

                this.formValue.is_charge_predict = this.formValue.is_charge_predict.toString()


              }

              if(this.formValue.is_statistics_work <= 0){

                this.formValue.is_statistics_work = ''
              } else{

                this.formValue.is_statistics_work = this.formValue.is_statistics_work.toString()


              }

              if(this.formValue.is_charge_use <= 0){

                this.formValue.is_charge_use = ''
              } else{

                this.formValue.is_charge_use = this.formValue.is_charge_use.toString()


              }

              if(this.formValue.prescription_mark<=0){
                  this.formValue.prescription_mark = ''
              }else{
                this.formValue.prescription_mark = this.formValue.prescription_mark.toString()
              }

              this.formValue.record_date = this.getTime(this.formValue.record_date)

              this.$refs.addDrugs.show(id, this.formValue)

            }
          })
        } else {
          for (let key in this.tempFormValue) {
            this.formValue[key] = this.tempFormValue[key]
          }
          this.$refs.addDrugs.show(0, this.formValue)
        }
      },

       deleteDurg(id,index){
         console.log("id",id)
            this.$confirm('确认删除吗?', '删除', {
            confirmButtonText: '确 定',
            cancelButtonText: '取 消',
            type: 'warning'
         }).then(() => {
              const params = {
                id:id,
              }
            deleteDurg(params).then(response => {
              if (response.data.state == 1) {
                  var msg = response.data.data.msg
                  this.list.splice(index, 1);
                  this.$message.success("删除成功")
              } else {
                  this.$message.error("药品已经出库不能删除")
              }
            })
          })
          .catch(() => {
          })
        },
      getList() {
        let params = {
          page: this.page,
          limit: this.limit,
          keyword: this.keywords,
          is_use: this.is_use,
          is_charge: this.is_charge,
          is_inject: this.is_inject,
          manufacturer:this.manufacturer,
          is_record:this.is_record
        }
        getBaseDrugLibList(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.total = response.data.data.total
            this.list = []
            console.log("333333333",response.data.data.list)
            for (let i = 0; i < response.data.data.list.length; i++) {
              this.list.push(response.data.data.list[i])
            }
          }
        })
      },
     getDataConfig(module, filed_name){
        return getDataConfig(module, filed_name)
      },
      // toRecord(){
      //    var that = this
      //    axios.get('http://127.0.0.1:9532/sz/api/drug/get').then(function(response) {
      //     if (response.data.state == 0) {
      //          that.$message.error(response.data.msg)
      //          return false
      //       } else {
      //         that.$message({ message: '备案成功', type: 'success' })
      //          that.getList()
      //        }
      //      }).catch(function(error) {
      //   })
      // },
      toReturn(id,isMark){
        console.log("id2222",id)
         var that = this
         let params = {
             'id':id,
             'type_id':1,
             'is_mark':isMark,
             'admin_user_id':this.$store.getters.xt_user.user.id
          }
         axios.get('http://127.0.0.1:9532/sz/api/revocation/get',{params:params}).then(function(response) {
          if (response.data.state == 0) {
               that.$message.error(response.data.msg)
               return false
            } else {
              that.$message({ message: '操作成功', type: 'success' })
              that.getList()
             }
           }).catch(function(error) {
        })
      },
     GetAllConfig(){
        GetAllConfig().then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.dealer = response.data.data.dealer;
         
        }
       });
      },
      getTime(val) {
         if(val < 0){
           return ""
         }
         if(val == ""){
          return ""
         }else {
          return uParseTime(val, '{y}-{m}-{d}')
         }
      },

      handleSelectionChange(val){
        this.selectDrug = val
      },

      BatchDelete() {
      if (this.selectDrug.length == 0) {
        this.$message.error("请选择要备案的信息");
        return false;
      }
      this.$confirm(
        "确认要备案所选记录吗? <br>",
        "备案提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        var ids = [];
        var idMap = {};
        for (const index in this.selectDrug) {
          ids.push(this.selectDrug[index].id);
          idMap[this.selectDrug[index].id] = this.selectDrug[index].id;
        }
      
        var idss = ids.join(',')
        let params = {
          ids:idss,
          admin_user_id:this.$store.getters.xt_user.user.id
        }
       
        var that = this
        axios.get('http://127.0.0.1:9532/sz/api/drug/get',{ params: params }).then(function(response) {
         if (response.data.state == 0) {
               that.$message.error(response.data.msg)
               return false
            } else {
              if(response.data.msg != ""){
                that.$message.success(response.data.msg)
              }
              if(response.data.msg == ""){
               that.$message.success("备案成功")
              }
              that.getList()
             }
           }).catch(function(error) {
        })
       });
     },
    }, 
    created() {
      this.getList()
      this.getAllManufacturer()
      this.GetAllConfig()
    }
  }
</script>
