<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'
                  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="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_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>

      </div>

    </div>
    <div style="display:flex; align-items:center;margin-bottom:10px;">
        <!--<el-button type="primary" size="small" @click="BatchDelete()" v-if="$store.getters.xt_user.org_id == 9504 ||  this.$store.getters.xt_user.org_id == 10138 || $store.getters.xt_user.org_id == 10028" >批量备案</el-button>-->
        <el-button type="primary" size="small"  @click="GDYBBatchPutOnRecord()">批量备案</el-button>
        <el-link target="_blank" href="https://kuyi.shengws.com/drugTemplate.xlsx" :underline="false"
                 style="margin-left:15px">
          <el-button
            class="filter-item"
            type="primary"
            size="small"
          >下载模版
          </el-button>
        </el-link>
        <upload-excel :on-success='handleSuccessTwo'></upload-excel>
        <el-button
          style="margin-left:10px;"
          @click="generateLog()"
          class="filter-item"
          type="primary"
          size="small"
        >下载日志
        </el-button>
      </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" >
        <template slot-scope="scope">
          <div>{{scope.row.drug_name}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="单位&规格" align="center">
        <template slot-scope="scope">
          <!-- <div>{{scope.row.drug_spec}}</div> -->
          <div>
            <span v-if="scope.row.min_unit != scope.row.dose_unit">{{scope.row.dose}}{{scope.row.dose_unit}}&nbsp;* &nbsp;</span>{{scope.row.min_number}}{{scope.row.min_unit}}/{{scope.row.max_unit}}
          </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="100" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.last_price}}</div>
        </template>
      </el-table-column>
      <el-table-column label="零售价" width="100" 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="280" 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)" v-if="$store.getters.xt_user.org_id == 9504 || $store.getters.xt_user.org_id == 10028 || $store.getters.xt_user.org_id == 10138" >-->
          <!--<span v-if="scope.row.is_mark == 0">备案</span>-->
          <!--<span v-if="scope.row.is_mark == 1">撤消</span>-->
        <!--</el-button>-->


          <el-button type="primary" size="small" icon="el-icon-refresh-left">
            <span v-if="scope.row.is_mark == 0 || scope.row.is_mark == 2"  @click="putOnRecord(scope.row.id)" >目录对照</span>
            <span v-if="scope.row.is_mark == 1"  @click="putOnUnRecord(scope.row.id)" >撤消对照</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>


    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <span>您提交的文档不是系统标准导入模板，请检查您的文档或重新 </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>


     <el-dialog
      title="提示"
      :visible.sync="exportLogVisible"
      width="40%"
    >

      <div v-for="(item,index) in logs" :key="index">
        <span> {{ item.export_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        <br/>
        <br/>
        <span>{{getContent(item)}}</span>
        <span >点击</span>
        <span style="color:blue" @click="generateTxt(item)">查看详情</span>
        <br/>
        <br/>
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button @click="exportLogVisible = false">取 消</el-button>
    <el-button type="primary" @click="exportLogVisible = false">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import selfPayment from './selfPayment'
  import maintain from './maintain'
  import addDrugs from './addDrugs'
  import { GetAllManufacturer,postDrugInformation } from '@/api/stock'
  import { getDataConfig,getDictionaryDataConfig } from "@/utils/data";
  import { uParseTime } from '@/utils/tools'
  import {
    createBaseDrugLib,
    createDrugUnitSafeguard,
    createMedicineInsurancePercent,
    editBaseDrugLib,
    getBaseDrugLib,
    getBaseDrugLibList,
    deleteDurg
  } from '@/api/data'
 import {GetAllConfig } from "@/api/stock";
 import { generateLog } from '@/api/config'
 import UploadExcel from '@/xt_pages/components/UploadExcel'
  export default {
    components: {
      selfPayment,
      maintain,
      addDrugs,
      UploadExcel
    },
    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: '',
          hosp_appr_flag:'',
          lmt_used_flag:'',
          dose_unit:'',
          min_price:'',
          drug_day:"",//默认开药天数,
          total:"",
        },
        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: '',
          social_security_directory_code:'',
          is_mark:'',
          prescription_mark:'',
          hosp_appr_flag:'',
          lmt_used_flag:'',
          dosage:'', //剂量
          unval:'',//拆零
          packing_unit:"",//包装单位
          packing_price:"",//包装零售价
          drug_day:"",//默认开药天数
          total:"",

        },

        current_id: 0,

        search_input: '',
        total:0,
        options: [
          {
            value: '0',
            label: '全部'
          }, {
            value: '1',
            label: '已备案'
          }, {
            value: '2',
            label: '未备案'
          }],
        value: '',

        dealer:[],
        selectDrug:[],
        dialogVisible:false,
        exportLogVisible:false,
        logs:[]
      }
    },
    methods: {
      GDYBBatchPutOnRecord(){
        var that = this;
        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;
        }
        let params = {
          ids:ids.join(','),
          record_type: 1,
          admin_user_id:this.$store.getters.xt_user.user.id
        };
        axios.get('http://127.0.0.1:9532/api/checkcode/get',{params:params}).then(function(response) {
          if (response.data.state == 0) {
            that.$message.error(response.data.data.msg);
            return false
          } else {
            if(response.data.data.failed_code == -10){
              // that.$message.error(response.data.data.msg)
              that.$confirm(response.data.data.msg, '医保错误信息', {
                confirmButtonText: '确 定',
                type: 'warning'
              }).then(() => {

              }).catch(() => {
              })
            }else{


            }
          }
        }).catch(function(error) {
        })

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

        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;

          val.min_number =  parseInt(val.min_number)

          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) {
          //新增

          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 {
              console.log("药品详情",response.data.data.drug)
              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);

              if(this.formValue.drug_category == 0){
                  this.formValue.drug_category = ""
              }
              if(this.formValue.drug_control == 0){
                  this.formValue.drug_control = ""
              }
              if(this.formValue.pharmacology_category == 0){
                 this.formValue.pharmacology_category = ""
              }
              if(this.formValue.statistics_category == 0){
                this.formValue.statistics_category = ""
              }
              if(this.formValue.pinyin == 0){
                 this.formValue.pinyin = ""
              }
              if(this.formValue.wubi == 0){
                this.formValue.wubi = ""
              }
              if(this.formValue.last_price == 0){
                  this.formValue.last_price = ""
              }
              if(this.formValue.retail_price == 0){
                this.formValue.retail_price = ""
              }
              if(this.formValue.social_security_directory_code == 0){
                 this.formValue.social_security_directory_code = ""
              }
              if(this.formValue.is_mark == 0){
                 this.formValue.is_mark = ""
              }
              if(this.formValue.prescription_mark == 0){
                  this.formValue.prescription_mark = ""
              }
              if(this.formValue.hosp_appr_flag == 0){
                this.formValue.hosp_appr_flag = ""
              }
              if(this.formValue.drug_classify == 0){
                 this.formValue.drug_classify = ""
              }



              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){

            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 = [];
            for (let i = 0; i < response.data.data.list.length; i++) {
              this.list.push(response.data.data.list[i])
            }
            console.log("数据库字典",this.list)
          }
        })
      },
     getDataConfig(module, filed_name){
        return getDataConfig(module, filed_name)
      },
      putOnUnRecord(id){
        var that = this;
        let params = {
          ids:id.toString(),
          record_type: 1,
          admin_user_id:this.$store.getters.xt_user.user.id
        };
        axios.get('http://127.0.0.1:9532/api/uncheckcode/get',{params:params}).then(function(response) {
          if (response.data.state == 0) {
            that.$message.error(response.data.data.msg);
            return false
          } else {
            if(response.data.data.failed_code == -10){
              // that.$message.error(response.data.data.msg)
              that.$confirm(response.data.data.msg, '医保错误信息', {
                confirmButtonText: '确 定',
                type: 'warning'
              }).then(() => {

              }).catch(() => {
              })

            }else{
              // for (let i = 0; i < that.tableData.length; i++) {
              //   if (that.tableData[i].id == that.currentObject.id) {
              //     that.tableData[i].record.is_cancel == 1
              //   }
              // }
            }

          }
        }).catch(function(error) {
        })
      },
      putOnRecord(id){
        var that = this;

        let params = {
          ids:id.toString(),
          record_type: 1,
          admin_user_id:this.$store.getters.xt_user.user.id
        };

        axios.get('http://127.0.0.1:9532/api/checkcode/get',{params:params}).then(function(response) {
          if (response.data.state == 0) {
            that.$message.error(response.data.data.msg);
            return false
          } else {
            if(response.data.data.failed_code == -10){
              // that.$message.error(response.data.data.msg)
              that.$confirm(response.data.data.msg, '医保错误信息', {
                confirmButtonText: '确 定',
                type: 'warning'
              }).then(() => {

              }).catch(() => {
              })
            }else{


            }



          }
        }).catch(function(error) {
        })
      },
      // 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){

         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.data.msg);
               return false
            } else {
              if(response.data.data.msg == ""){
                  that.$message.success("备案成功!");
                  that.getList()
               }
               if(response.data.data.msg!=""){
                  that.$message.error(response.data.data.msg);
                  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.data.msg);
               return false
            } else {
               if(response.data.data.msg == ""){
                  that.$message.success("备案成功!");
                  that.getList()
               }
               if(response.data.data.msg!=""){
                  that.$message.error(response.data.data.msg);
                   that.getList()
               }
             }
           }).catch(function(error) {
        })
       });
     },

      handleSuccessTwo({ results, header }) {
         console.log("header22222",header)
        if (header != undefined && header.length > 0) {

          var isHasDrugName = header.includes('*药品名称');
          console.log("isHasDrugName",isHasDrugName)
          var isHasUnval = header.includes('*拆零');
          console.log("isHasUnval",isHasUnval)
          var isHasMinUnit= header.includes('*拆零单位');
           console.log("isHasMinUnit",isHasMinUnit)
          var isHasDosage =  header.includes('*剂量')
          console.log("isHasDosage",isHasDosage)

          var isHasMaxUnit= header.includes('*剂量单位');
          console.log("isHasMaxUnit",isHasMaxUnit)
          var isHasPackingUnit = header.includes('*包装单位')
          console.log("isHasPackingUnit",isHasPackingUnit)
          var isHasDrugType =  header.includes('*药品类型');
          console.log("isHasDrugType",isHasDrugType)
          var isHasDrugStockLimit =  header.includes('*库存警戒');
          console.log("isHasDrugStockLimit",isHasDrugStockLimit)
          var isHasDrugOriginPlace= header.includes('*产地');
          console.log("isHasDrugOriginPlace",isHasDrugOriginPlace)
          var isHasDrugDosageForm = header.includes('*药品剂型');
          console.log("isHasDrugDosageForm",isHasDrugDosageForm)

          var isHasUnitMatrixing= header.includes("*单位换算");
          console.log("isHasUnitMatrixing",isHasUnitMatrixing)
          var isHasRetailPrice = header.includes('*拆零零售价');
          console.log("isHasRetailPrice",isHasRetailPrice)
          var isHasLastPrice = header.includes('*进货价');
          var isHasPackingPrice= header.includes('*包装零售价');
         console.log("isHasLastPrice",isHasLastPrice)
          var isHasDrugClassifye = header.includes('*药物分类');
         console.log("isHasDrugClassifye",isHasDrugClassifye)
         var isHasManufacturer = header.includes('*生产厂商');
         console.log("isHasManufacturer",isHasManufacturer)
         var isHasDrugDose = header.includes('*默认单次用量');
        console.log("isHasDrugDose",isHasDrugDose)
         var isDrugDoseUnit = header.includes('*默认单次用量单位');
         console.log("isDrugDoseUnit",isDrugDoseUnit)
          if (!(isHasDrugName  && isHasUnval && isHasDrugType && isHasDrugStockLimit && isHasDrugOriginPlace && isHasDrugDosageForm && isHasMaxUnit &&  isHasMinUnit && isHasUnitMatrixing &&  isHasRetailPrice && isHasLastPrice && isHasPackingPrice && isHasDrugClassifye && isHasManufacturer && isHasDrugDose && isDrugDoseUnit && isHasDosage && isHasPackingUnit)) {
            console.log("分区222222222222222222222222222222")
            this.dialogVisible = true;
            return
          }
        }else {
          this.dialogVisible = true;
          return
        }

       var tableData = [];
       for(let i=1;i<results.length;i++){
         let obj = {"drug_type_id":0,"drug_dosage_form_id":0,"medical_insurance_level_id":0,"drug_classify_id":0,"manufacturer_id":0,"dealer_id":0,"statistics_category_id":0,"drug_control_id":0,"pharmacology_category_id":0,"drug_category_id":0};
         for (var key in results[i]) {

           if (results[i]['*药品名称'] === undefined) {
                obj['drug_name'] = ''
              } else {
           if (key == '*药品名称') {
               obj['drug_name'] = results[i][key].replace(/\s/g,"")
              }
           }


          if (results[i]['*拆零'] === undefined) {
                obj['min_number'] = ''
              } else {
           if (key == '*拆零') {
               obj['min_number'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['*拆零单位'] === undefined) {
                obj['min_unit'] = ''
              } else {
           if (key == '*拆零单位') {
               obj['min_unit'] = results[i][key].replace(/\s/g,"")
              }
           }


            if (results[i]['*剂量'] === undefined) {
                obj['dosage'] = ''
              } else {
            if (key == '*剂量') {
                obj['dosage'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['*剂量单位'] === undefined) {
                obj['max_unit'] = ''
              } else {
           if (key == '*剂量单位') {
               obj['max_unit'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['*包装单位'] === undefined) {
                obj['packing_unit'] = ''
              } else {
           if (key == '*包装单位') {
               obj['packing_unit'] = results[i][key].replace(/\s/g,"")
              }
           }


          if (results[i]['默认给药途径'] === undefined) {
                obj['delivery_way'] = ''
              } else {
           if (key == '默认给药途径') {
               obj['delivery_way'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['默认执行频率'] === undefined) {
                obj['execution_frequency'] = ''
              } else {
           if (key == '默认执行频率') {
               obj['execution_frequency'] = results[i][key].replace(/\s/g,"")
              }
           }

          if (results[i]['默认开药天数'] === undefined) {
                obj['drug_day'] = ''
              } else {
           if (key == '默认开药天数') {
               obj['drug_day'] = results[i][key].replace(/\s/g,"")
              }
           }



            if (results[i]['*药品类型'] === undefined) {
                obj['drug_type'] = ''
              } else {
           if (key == '*药品类型') {
               obj['drug_type'] = results[i][key].replace(/\s/g,"")
              }
           }


           if (results[i]['*库存警戒'] === undefined) {
                obj['drug_stock_limit'] = ''
              } else {
           if (key == '*库存警戒') {
               obj['drug_stock_limit'] = results[i][key].replace(/\s/g,"")
              }
           }


           if (results[i]['*产地'] === undefined) {
                obj['drug_origin_place'] = ''
              } else {
           if (key == '*产地') {
               obj['drug_origin_place'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['*药品剂型'] === undefined) {
                obj['drug_dosage_form'] = ''
              } else {
           if (key == '*药品剂型') {
               obj['drug_dosage_form'] = results[i][key].replace(/\s/g,"")
              }
           }


            if (results[i]['*医保等级'] === undefined) {
                obj['medical_insurance_level'] = ''
              } else {
           if (key == '*医保等级') {
               obj['medical_insurance_level'] = results[i][key].replace(/\s/g,"")
              }
           }




            if (results[i]['*单位换算'] === undefined) {
                obj['unit_matrixing'] = ''
              } else {
           if (key == '*单位换算') {
               obj['unit_matrixing'] = results[i][key].replace(/\s/g,"")
              }
           }




          if (results[i]['*拆零零售价'] === undefined) {
                obj['retail_price'] = ''
              } else {
           if (key == '*拆零零售价') {
               obj['retail_price'] = results[i][key].replace(/\s/g,"")
              }
           }


          if (results[i]['*包装零售价'] === undefined) {
                obj['packing_price'] = ''
              } else {
           if (key == '*包装零售价') {
               obj['packing_price'] = results[i][key].replace(/\s/g,"")
              }
           }


         if (results[i]['*进货价'] === undefined) {
                obj['last_price'] = ''
              } else {
           if (key == '*进货价') {
               obj['last_price'] = results[i][key].replace(/\s/g,"")
              }
           }


            if (results[i]['*药物分类'] === undefined) {
                obj['drug_classify'] = ''
              } else {
           if (key == '*药物分类') {
               obj['drug_classify'] = results[i][key].replace(/\s/g,"")
              }
           }





           if (results[i]['*默认单次用量'] === undefined) {
                obj['drug_dose'] = ''
              } else {
           if (key == '*默认单次用量') {
               obj['drug_dose'] = results[i][key].replace(/\s/g,"")
              }
           }


           if (results[i]['*默认单次用量单位'] === undefined) {
                obj['drug_dose_unit'] = ''
              } else {
           if (key == '*默认单次用量单位') {
               obj['drug_dose_unit'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['*生产厂商'] === undefined) {
                obj['manufacturer'] = ''
              } else {
           if (key == '*生产厂商') {
               obj['manufacturer'] = results[i][key].replace(/\s/g,"")
              }
           }



            if (results[i]['经销商'] === undefined) {
                obj['dealer'] = ''
              } else {
            if (key == '经销商') {
                obj['dealer'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['限制性用药'] === undefined) {
                obj['lmt_used_flag'] = ''
              } else {
            if (key == '限制性用药') {
                obj['lmt_used_flag'] = results[i][key].replace(/\s/g,"")
              }
           }



           if (results[i]['药品别名'] === undefined) {
                obj['drug_alias'] = ''
              } else {
           if (key == '药品别名') {
               obj['drug_alias'] = results[i][key].replace(/\s/g,"")
              }
           }


             if (results[i]['药品类别'] === undefined) {
                obj['drug_category'] = ''
              } else {
            if (key == '药品类别') {
                obj['drug_category'] = results[i][key].replace(/\s/g,"")
              }
           }



           if (results[i]['开药控制'] === undefined) {
                obj['drug_control'] = ''
              } else {
            if (key == '开药控制') {
                obj['drug_control'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['批准文号'] === undefined) {
                obj['number'] = ''
              } else {
            if (key == '批准文号') {
                obj['number'] = results[i][key].replace(/\s/g,"")
              }
           }



            if (results[i]['审批标志'] === undefined) {
                obj['hosp_appr_flag'] = ''
              } else {
            if (key == '审批标志') {
                obj['hosp_appr_flag'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['医保编码'] === undefined) {
                obj['medical_insurance_number'] = ''
              } else {
            if (key == '医保编码') {
                obj['medical_insurance_number'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['药理分类'] === undefined) {
                obj['pharmacology_category'] = ''
              } else {
            if (key == '药理分类') {
                obj['pharmacology_category'] = results[i][key].replace(/\s/g,"")
              }
           }


           if (results[i]['统计分类'] === undefined) {
                obj['statistics_category'] = ''
              } else {
            if (key == '统计分类') {
                obj['statistics_category'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['本位码'] === undefined) {
                obj['code'] = ''
              } else {
            if (key == '本位码') {
                obj['code'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['是否特病目录'] === undefined) {
                obj['is_special_diseases'] = ''
              } else {
            if (key == '是否特病目录') {
                obj['is_special_diseases'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['是否备案'] === undefined) {
                obj['is_record'] = ''
              } else {
            if (key == '是否备案') {
                obj['is_record'] = results[i][key].replace(/\s/g,"")
              }
           }

           if (results[i]['处方药标志'] === undefined) {
                obj['prescription_mark'] = ''
              } else {
            if (key == '处方药标志') {
                obj['prescription_mark'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['社保目录编码'] === undefined) {
                obj['social_security_directory_code'] = ''
              } else {
            if (key == '社保目录编码') {
                obj['social_security_directory_code'] = results[i][key].replace(/\s/g,"")
              }
           }


            if (results[i]['备案日期'] === undefined) {
                obj['record_date'] = ''
              } else {
            if (key == '备案日期') {
                obj['record_date'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['药品备注'] === undefined) {
                obj['drug_remark'] = ''
              } else {
            if (key == '药品备注') {
                obj['drug_remark'] = results[i][key].replace(/\s/g,"")
              }
           }

             if (results[i]['状态'] === undefined) {
                obj['drug_status'] = ''
              } else {
            if (key == '状态') {
                obj['drug_status'] = results[i][key].replace(/\s/g,"")
              }
           }

            if (results[i]['限制说明'] === undefined) {
                obj['limit_remark'] = ''
              } else {
            if (key == '限制说明') {
                obj['limit_remark'] = results[i][key].replace(/\s/g,"")
              }
           }

         }
         var newArr = [];
         tableData.push(obj);

        for(let i=0;i<tableData.length;i++){

         if(tableData[i].is_special_diseases == ""){
            tableData[i].is_special_diseases = 0
         }

         if(tableData[i].is_special_diseases == "是"){
            tableData[i].is_special_diseases = 1
         }
         if(tableData[i].is_special_diseases == "否"){
            tableData[i].is_special_diseases = 2
         }



          if(tableData[i].is_record == ""){
             tableData[i].is_record = 0
          }
          if(tableData[i].is_record == "是"){
            tableData[i].is_record = 1
          }
          if(tableData[i].is_record == "否"){
            tableData[i].is_record = 2
          }

          if(tableData[i].prescription_mark == ""){
              tableData[i].prescription_mark = 0
          }
          if(tableData[i].prescription_mark == "是"){
             tableData[i].prescription_mark =1
          }
          if(tableData[i].prescription_mark == "否"){
            tableData[i].prescription_mark =2
          }

          if(tableData[i].hosp_appr_flag == ""){
             tableData[i].hosp_appr_flag = 0
          }

          if(tableData[i].hosp_appr_flag == "无需审批"){
              tableData[i].hosp_appr_flag = 1
          }
          if(tableData[i].hosp_appr_flag == "审批通过"){
              tableData[i].hosp_appr_flag = 2
          }
          if(tableData[i].hosp_appr_flag == "审批不通过"){
              tableData[i].hosp_appr_flag = 3
          }
          if(tableData[i].lmt_used_flag == ""){
             tableData[i].lmt_used_flag = 0
          }

          if(tableData[i].lmt_used_flag == "否"){
              tableData[i].lmt_used_flag = 0
          }


          if(tableData[i].lmt_used_flag == "是"){
              tableData[i].lmt_used_flag = 1
          }

        }
       }

       let params = {
          'drugs':tableData
        };
        console.log("params222222222",params)

        postDrugInformation(params).then(response=>{
           if(response.data.state == 1){
             var msg =  response.data.data.msg;
             this.getList();
             this.getAllManufacturer();
             this.GetAllConfig();
             this.$message.success("导入成功!")

           }else{
             this.$message.error("导入失败,请下载日志查看")
           }
        })
      },
      generateTxt: function(log) {
        var content = '';
        var errlog = log.err_logs;
        content = this.getContent(log);
        for (let i = 0; i < errlog.length; i++) {
          if (content.length == 0) {
            content = errlog[i].err_msg
          } else {
            content = content + '\n' + errlog[i].err_msg
          }
        }

        var url = new Blob(['\ufeff' + content], { type: 'text/txt,charset=UTF-8' });
        if (typeof url === 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url) // 创建blob地址
        }
        const aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = this.timestampToTime(log.export_time) + '患者导入日志' + '.txt';
        aLink.click()

      },
      getContent(log) {
        return '您导入的文档共' + log.total_num + '条患者数据' + '，' + '已成功导入' + log.success_num + '条，导入失败' + log.fail_num + '条,'
      },
      timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '年';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + '时';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + '分';
        var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()) + '秒';
        return Y + M + D + h + m + s
      },
       generateLog() {
        let params = {
          'log_type': 4
        };
        generateLog(params).then(
          response => {
            if (response.data.state === 1) {
              this.logs = response.data.data.logs;
              this.exportLogVisible = true
            } else {
              this.$message.error(response.data.msg)
            }
          }
        )
      },
      getDictionaryDataConfig(module,filed_name){
        return getDictionaryDataConfig(module,filed_name)
      },

    },
    created() {

      this.getList();
      this.getAllManufacturer();
      this.GetAllConfig()

    }
  }
</script>
