<template>
    <div>
      <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
        <div class="cell clearfix">
          <span>发药时间:</span>
          <el-date-picker
            size="small"
            v-model="start_time"
            prefix-icon="el-icon-date"
            :editable="false"
            style="width: 196px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="changeStartTime"
          ></el-date-picker>-
          <el-date-picker
           @change="changeEndTime"
            size="small"
            v-model="end_time"
            prefix-icon="el-icon-date"
            :editable="false"
            style="width: 196px;margin-right:10px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>


        <div>
          <div>上传状态:
            <el-select size="small" v-model="is_sale" placeholder="请选择" style="width:100px;" @change="changeStock">
                <el-option
                  v-for="item,index in items"
                  :key="index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
         </div>
        </div>

        <div>
          <el-button type="primary" @click="query()">查询</el-button>
          <el-button type="primary" @click="exportdata()">导出</el-button>
        </div>
      </div>
      <el-table :data="tableData" border :row-style="{ color: '#303133' }" ref="table2"
                :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                max-height="800"
                @select="selectCostInfo"
                @selection-change="changeCostInfoTableData"
                @select-all="changeAllCostInfoTableData"
                highlight-current-row>
        <el-table-column align="center" prop="name" label="患者姓名">
          <template slot-scope="scope">{{getPatientName(scope.row.patient_id) }}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="处方日期">
          <template slot-scope="scope">{{getTime(scope.row.advice_date)}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="药品名称">
          <template slot-scope="scope">{{ scope.row.advice_name }}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="规格">
          <template slot-scope="scope">{{getDrugSpec(scope.row.drug_id)}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="开药总量">
          <template slot-scope="scope">{{scope.row.prescribing_number}}{{ scope.row.prescribing_number_unit }}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="药品追溯码">
          <template slot-scope="scope">
            <div @click="getDrugCode(scope.row.id,scope.row.DataSources,scope.row.drug_code,scope.$index)"><el-input style="width: 100;" v-model="scope.row.drug_code"></el-input></div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="上传状态">
          <template slot-scope="scope">
            <div v-if="scope.row.is_upload == 1">已上传</div>
            <div v-if="scope.row.is_upload == 2 || scope.row.is_upload == 0">未上传</div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="name" label="发药状态">
          <template slot-scope="scope">
            <div v-if="scope.row.is_medicine == 1">已发药</div>
            <div v-if="scope.row.is_medicine == 2 || scope.row.is_medicine == 0">未发药</div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="name" label="操作" width="200">
          <template slot-scope="scope">
            <div>
             <el-button v-if="scope.row.is_upload == 1" type="primary" @click="sigle_stock(scope.row)">未上传</el-button>
            <el-button type="primary" v-if="scope.row.is_upload == 0 || scope.row.is_upload == 2" @click="toUpload(scope.row)">上传</el-button>
            <el-button v-if="faShow == true" type="primary" @click="toFaYao(scope.row)">发药</el-button>
            </div>
          </template>
        </el-table-column>


      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="10"
        :page-sizes="[10, 20, 50, 100,500,1000,2000]"
        background
        style="margin-top:20px;float: right"
        :total="total"
      ></el-pagination>





      <el-dialog
        title="药品追溯码"
        :visible.sync="dialogVisibleOne"
         width="40%">
       <span>
        <el-input
          @keyup.native="changeText"
          type="textarea"
          placeholder="请输入内容"
          v-model="textarea"
          :rows="10"
        >
        </el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOne = false">取 消</el-button>
        <el-button type="primary" @click="saveTextArea()">确 定</el-button>
      </span>
      </el-dialog>
    </div>


  </template>


  <script>
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  import { getHisDrugCodeQueryList,createUploadDrugCode,getPatientDrugCode } from '../../api/new_stock/stock'
  import { getDictionaryDataConfig } from "@/utils/data";
  import { uParseTime } from '@/utils/tools'
  import { changeDrugCode } from "@/api/pharmacy";

  import axios from 'axios'
  const moment = require('moment')
  export default {
    components: {
      BreadCrumb
    },
    data() {
      return {
        drugTypeList: [{ id: 0, name: "全部" }],
        start_time: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toLocaleDateString('en-CA'),
        end_time: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).toLocaleDateString('en-CA'),

        tableData: [],
        change_type:"3",
        selection:[],
        page:1,
        limit:10,
        value:0,
        is_sale:"0",
        items: [
          { id: "0", name: '全部' },
          { id: "1", name: '已上传' },
          { id: "2", name: '未上传' },
        ],
        patientList:[],
        drugList:[],
        dialogVisibleOne:false,
        id:0,
        is_source:0,
        drug_code:0,
        currentRow:{},
        currentIndex:0,
        is_drug_open:"2",
        textarea:'',
        total:0,
        faShow:false,
        is_open:false,
      }
    },
    methods: {
        changeText(event){
        // 检查是否为特定的按键，例如回车键，来确认扫码枪输入完成
        if (event.key === 'Enter') {
            var textarea = ""
            textarea += this.textarea + ","
            this.textarea = textarea
        }
       },
       getDrugCode(id,DataSources,DrugCode,index){
            this.id = id
            this.textarea = DrugCode
            this.currentIndex = index
            this.dialogVisibleOne = true
      },
      saveTextArea(){
       var params = {
        id:this.id,
        data_source:1,
        drug_code:this.textarea,
       }
       console.log("paramss",params)
      changeDrugCode(params).then(response=>{
         if(response.data.state == 1){
            this.$message.success("保存成功!")
            for(let i=0;i<this.tableData.length;i++){
             if(this.currentIndex == i){
                this.tableData[i].drug_code = this.textarea
             }
            }
            this.dialogVisibleOne = false
         }
      })
    },
    getPatientName(id){
       var name = ""
       for(let i=0;i<this.patientList.length;i++){
          if(id == this.patientList[i].id){
             name = this.patientList[i].name
          }
       }
       return name
      },
      getTime(val) {
         if(val < 0){
           return ""
         }
         if(val == ""){
          return ""
         }else {
          return uParseTime(val, '{y}-{m}-{d}')
         }
      },
      getDrugName(drug_id){
        var drug_name = ""
        for(let i=0;i<this.drugList.length;i++){
           if(drug_id == this.drugList[i].id){
              drug_name = this.drugList[i].drug_name
           }
        }
        return drug_name
      },
      getDrugSpec(drug_id){
        var specification_name = ""
        for(let i=0;i<this.drugList.length;i++){
          if(drug_id == this.drugList[i].id){
            specification_name = this.drugList[i].specification_name
          }
        }
        return specification_name
      },
      handleSizeChange(val) {
        this.limit = val
        this.getlist()
      },
      handleCurrentChange(val) {
        this.page = val
        this.getlist()
      },
      selectCostInfo(selection, row) {
        this.selection = selection
      },
       changeCostInfoTableData(val) {
        this.selection = val
      }, changeAllCostInfoTableData(selection) {
        this.selection = selection
      },
      delete(){


      },
      exportdata(){
        console.log("hahahahh",this.tableData)
        if(this.tableData!=null && this.tableData.length>0){
           for(let i=0;i<this.tableData.length;i++){
             this.tableData[i].patient_name = this.getPatientName(this.tableData[i].patient_id)
             this.tableData[i].advice_date_str = this.getTime(this.tableData[i].advice_date)
             if(this.tableData[i].is_upload == 1){
                this.tableData[i].is_upload_name = "已上传"
             }
             if(this.tableData[i].is_upload == 2 || this.tableData[i].is_upload == 0){
                this.tableData[i].is_upload_name = "未上传"
             }

             if(this.tableData[i].is_medicine == 1){
                this.tableData[i].is_medicine_name = "已发药"
             }
             if(this.tableData[i].is_medicine == 2 || this.tableData[i].is_medicine == 0){
                this.tableData[i].is_medicine_name = "未发药"
             }
             this.tableData[i].specification_name = this.getDrugSpec(this.tableData[i].drug_id)
           }
        }

        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['患者姓名', '处方日期', '药品名称', '规格', '开药总量', '药品追溯码','上传状态','发药状态']
          const filterVal = ['patient_name', 'advice_date_str', 'advice_name', 'specification_name', 'prescribing_numbers', 'drug_code','is_upload_name','is_medicine_name']

          const data = this.formatJson(filterVal, this.tableData)
           excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '药品追溯'
         })
        })

      },formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },

      query(){
        this.getlist()
      },
      getDrugType(id) {
        var name = "";
        for (let i = 0; i < this.drugTypeList.length; i++) {
          if (this.drugTypeList[i].id == id) {
            name = this.drugTypeList[i].name;
          }
        }

        return name;
      },
      getTime(val) {
        if(val == "" || val == undefined){
          return ""
        }else {
          return uParseTime(val, '{y}-{m}-{d}')
        }
      },
      getlist(){
        this.tableData = []
        let params = {
          start_time: this.start_time,
          end_time: this.end_time,
          page:this.page,
          limit:this.limit,
          is_sale:this.is_sale,

        }
        getHisDrugCodeQueryList(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {

             this.tableData = response.data.data.list
             this.total = response.data.data.total
             this.drugList = response.data.data.drug
             this.patientList = response.data.data.patients
             this.is_open = response.data.data.codeConfig.is_open
          }
        })
      },
      changeStock(val){
        this.is_sale = val
        this.getlist()
      },
      changeStartTime(val){
        this.start_time = val
      },
      changeEndTime(val){
        this.end_time = val
      },
      toUpload(row){
        if(row.is_medicine == 0 || row.is_is_medicine == 2){
          this.$message.error("该药品未发药,请先发药")
          this.faShow = true
          return
        }
        var params = {
          drug_id:row.drug_id,
          patient_id:row.patient_id,
         advice_date:row.advice_date,
        }
        createUploadDrugCode(params).then(response=>{
          if(response.data.state == 1){
            this.$message.success("上传成功!")
          }
        })
      },
      toFaYao(row){

        if(this.is_open == 1){
          if(row.drug_code==''){
             this.$message.error("药品追溯码不能为空!")
             return
          }
        }
          var params= {
            drug_id:row.drug_id,
            patient_id:row.patient_id,
            advice_date:row.advice_date,
          }
        getPatientDrugCode(params).then(response=>{
          if(response.data.state == 1){
             this.$message.success("发药成功!")
             this.getlist()
          }
        })
      }
    },
    created() {
      var drugTypeList = getDictionaryDataConfig("system", "drug_type");
      this.drugTypeList.push(...drugTypeList);
      this.getlist()
    }
  }
  </script>


