<template>
  <!--患者发药-->
  <div class="main-contain new-main-contain">
    <div class="position">
      <!--      <bread-crumb :crumbs='crumbs'></bread-crumb>-->
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div
      class="app-container"
      style="display: flex; flex: 1; padding: 10px 20px 0px 20px"
    >
      <div class="mainLeft">
        <div>
          <div class="list">
            <el-date-picker
              style="width: 200px"
              v-model="start_time"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              @change="changeTimes()"
            >
            </el-date-picker>
          </div>
          <!--          <el-button @click="testsss">调试1</el-button>-->
          <!--          <el-button @click="testsss2">调试2</el-button>-->
          <div class="list">
            <el-radio-group v-model="state" @change="lala()">
              <el-radio :label="1">待发药{{ waitmount }}人</el-radio>
              <el-radio :label="2">已发药{{ alreadmount }}人</el-radio>
            </el-radio-group>
          </div>
          <div
            class="list"
            style="display: flex; justify-content: space-between"
          >
            <el-input
              size="small"
              style="width: 130px"
              v-model="keywords"
              class="filter-item"
              placeholder="请输入患者名称"
              clearable
            />
            <el-button
              size="small"
              class="filter-item"
              type="primary"
              @click="searchAction"
              >搜索
            </el-button>
          </div>

          <el-table
            :height="tableHeight"
            ref="table01"
            :data="waitmount_data"
            highlight-current-row
            @current-change="handleCurrentChange"
            border
            style="width: 100%"
            v-if="state == 1"
             :row-style="{ color: '#303133' }"
            :header-cell-style="{
              backgroundColor: 'rgb(245, 247, 250)',
              color: '#606266',
            }"
          >
            <el-table-column prop="date" label="患者姓名" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.Name ? scope.row.Name : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="透析号" width="100">
              <template slot-scope="scope">
                <span>{{
                  scope.row.DialysisNo ? scope.row.DialysisNo : ""
                }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            :height="tableHeight"
            ref="table02"
            :data="alreadmount_data"
            highlight-current-row
            @current-change="handleCurrentChange"
            border
             :row-style="{ color: '#303133' }"
            :header-cell-style="{
              backgroundColor: 'rgb(245, 247, 250)',
              color: '#606266',
            }"
            style="width: 100%"
            v-if="state == 2"
          >
            <el-table-column prop="date" label="患者姓名" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.Name ? scope.row.Name : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="透析号" width="100">
              <template slot-scope="scope">
                <span>{{
                  scope.row.DialysisNo ? scope.row.DialysisNo : ""
                }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="mainRight">
        <div class="titlelist">
          <el-button type="primary" @click="dispense" v-if="state == 1"
            >发药</el-button
          >
          <el-button type="primary" @click="endispense" v-if="state == 2"
            >退药</el-button
          >
          <el-button type="primary" @click="toPrint">打印</el-button>
          <!--          <el-button @click="tiaoshi">调试</el-button>-->
          <el-button type="primary" v-if="state == 1" @click="toSetting"
            >设置</el-button
          >
        </div>
        <el-divider style="margin-top: 10px"></el-divider>
        <div>
          <el-table
            :height="tableHeight"
            :data="tableData"
            border
            style="width: 100%"
            :row-style="{ color: '#303133' }"
            :header-cell-style="{
              backgroundColor: 'rgb(245, 247, 250)',
              color: '#606266',
            }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column label="名称" width="200" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Name ? scope.row.Name : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单次用量" width="150" align="center">
              <template slot-scope="scope">
                <span>{{
                  scope.row.SingleDosage ? scope.row.SingleDosage : ""
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="用法" width="160" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Usage ? scope.row.Usage : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="频率" width="160" align="center">
              <template slot-scope="scope">
                <span>{{
                  scope.row.Frequency ? scope.row.Frequency : ""
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="天数" width="140" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Days ? scope.row.Days : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总量" width="140" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Total ? scope.row.Total : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开立医生" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Doctor ? scope.row.Doctor : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数据来源" width="162" align="center">
              <template slot-scope="scope">
                <span>{{
                  scope.row.DataSources ? scope.row.DataSources : ""
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" width="170" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.Remarks ? scope.row.Remarks : "" }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--        <div v-if="state == 2" style="margin-top: 25px">诊断时间：{{ timedate }}</div>-->
      </div>
      <el-dialog title="设置" :visible.sync="dialogVisible" width="30%">
        <span style="font-size: 17px">请选择药品是否要通过药房管理出库</span>
        <span style="display: block; padding: 18px 25px">
          <el-radio v-model="is_open" label="1">是</el-radio>
          <el-radio v-model="is_open" label="2">否</el-radio>
        </span>
        <div
          style="
            height: 50px;
            background: #c7ebfc;
            border-radius: 5px;
            padding: 7px;
          "
        >
          <i class="el-icon-info" style="color: #3399ff; font-size: 17px"></i>
          若选择为是，则通过药房发药的药品都会在发药之后进行出库，否则按原来的方式进行出库管理
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="SaveSetting">保 存</el-button>
        </span>
      </el-dialog>
    </div>

    <patient-print
      ref="patientprint"
      :visibility="isVisibility"
      :propsTable="propsTable"
    >
    </patient-print>
  </div>
</template>

<script>
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import patientPrint from "./print/patientPrint.vue";
import { getPharmacyConfig, SaveSetting } from "@/api/his/advice";
import {
  waitingdrug,
  issueddrugs,
  todaynumber,
  getpharmacycontent,
  dispensingmedicine,
  drugwithdrawal,
} from "@/api/pharmacy";
const moment = require("moment");
export default {
  components: {
    BreadCrumb,
    patientPrint,
  },
  data() {
    return {
      patient_id: 0,
      crumbs: [
        { path: false, name: "药房管理" },
        { path: "/Pharmacy/patiantDispensing", name: "患者发药" },
      ],
      tableHeight: 400,
      start_time: moment(new Date()).add("year", 0).format("YYYY-MM-DD"),
      state: 1, //1待发药，2已发药
      waitmount: 0, //待发药人数
      waitmount_data: [],
      alreadmount: 0, //已发药人数
      alreadmount_data: [],
      keywords: "",
      tableData: [],
      propsTable: [],
      tableData_list: [],
      isVisibility: false,
      currentRow: null,
      dialogVisible: false,
      is_open: "2",
    };
  },
  watch: {},
  created() {
    this.init();
    this.gettodaynumber();
    this.fun3();
    // this.getwaitmount();//fun3
    // this.selectedbydefault();
  },
  methods: {
    tiaoshi() {
      console.log("this.tableData", this.tableData);
    },
    async fun3() {
      console.log("fun3");
      this.fun1().then((val) => {
        this.fun2();
      });
    },
    async fun4(tmp) {
      console.log("fun3");
      this.fun1().then((val) => {
        console.log("this.alreadmount_data", this.alreadmount_data);
        for (let i = 0; i < this.alreadmount_data.length; i++) {
          console.log("tmp = ", tmp);
          if (this.alreadmount_data[i].PatientID == tmp) {
            console.log("i = ", i);
            this.$refs.table02.setCurrentRow(this.alreadmount_data[i]);
            this.handleCurrentChange(this.alreadmount_data[i]);
          }
        }
      });
    },
    async fun5(tmp) {
      console.log("fun5555");
      this.fun1().then((val) => {
        console.log("this.alreadmount_data", this.waitmount_data);
        for (let i = 0; i < this.waitmount_data.length; i++) {
          console.log("tmp = ", tmp);
          if (this.waitmount_data[i].PatientID == tmp) {
            console.log("i = ", i);
            this.$refs.table01.setCurrentRow(this.waitmount_data[i]);
            this.handleCurrentChange(this.waitmount_data[i]);
          }
        }
      });
    },

    lala() {
      console.log("this.state!!!!!!", this.state);
      //初始化状态
      this.tableData = null;
      this.currentRow = null;
      this.selectedbydefault();
    },
    //选中行数
    handleCurrentChange(val) {
      this.currentRow = val;
      console.log("this.currentRow", this.currentRow);
      if (this.state == 1) {
        this.getpatientdetails(0);
      }
      if (this.state == 2) {
        this.getpatientdetails(1);
      }
    },
    init() {
      // console.log("初始化了")
      this.state = 1;
      this.tableData = null;
      this.currentRow = null;
    },
    testsss() {
      this.state = 1;
    },
    //默认选中的
    selectedbydefault() {
      if (this.state == 1 && this.waitmount_data.length > 0) {
        this.$refs.table01.setCurrentRow(this.waitmount_data[0]);
        this.handleCurrentChange(this.waitmount_data[0]);
      }
      if (this.state == 2 && this.alreadmount_data.length > 0) {
        this.$refs.table02.setCurrentRow(this.alreadmount_data[0]);
        this.handleCurrentChange(this.alreadmount_data[0]);
      }
    },
    //包装selectedbydefault
    fun2() {
      console.log("3333333this.waitmount_data", this.waitmount_data);
      // return new Promise((resolve, reject) => {
      if (this.state == 1 && this.waitmount_data.length > 0) {
        this.$refs.table01.setCurrentRow(this.waitmount_data[0]);
        this.handleCurrentChange(this.waitmount_data[0]);
      }
      if (this.state == 2 && this.alreadmount_data.length > 0) {
        this.$refs.table02.setCurrentRow(this.alreadmount_data[0]);
        this.handleCurrentChange(this.alreadmount_data[0]);
      }
      // });
    },
    changeTimes() {
      this.gettodaynumber();
      this.getwaitmount();
      this.fun3();
    },
    //获取当天发药的人数
    gettodaynumber() {
      console.log("aaa");
      var params = {
        time: this.start_time,
      };
      todaynumber(params).then((res) => {
        if (res.data.state == 1) {
          this.waitmount = res.data.data.itotal;
          this.alreadmount = res.data.data.wtotal;
        }
      });
      // console.log("2222222")
    },
    //获取发药人列表
    getwaitmount() {
      var params = {
        keyword: this.keywords,
        time: this.start_time,
      };
      waitingdrug(params).then((res) => {
        if (res.data.state == 1) {
          this.waitmount_data = res.data.data.list;
        }
      });
      issueddrugs(params).then((res) => {
        if (res.data.state == 1) {
          this.alreadmount_data = res.data.data.list;
        }
      });
    },
    //包装getwaitmount
    async fun1() {
      // return new Promise((resolve, reject) => {
      var params = {
        keyword: this.keywords,
        time: this.start_time,
      };
      await waitingdrug(params).then((res) => {
        if (res.data.state == 1) {
          this.waitmount_data = res.data.data.list;
          console.log("1111111");
        }
      });
      await issueddrugs(params).then((res) => {
        if (res.data.state == 1) {
          this.alreadmount_data = res.data.data.list;
          console.log("1111111s");
        }
      });
      console.log("222222222");

      // })
    },
    //获取患者信息详情
    getpatientdetails(val) {
      var params = {
        patient_id: this.currentRow.PatientID,
        is_medicine: val,
        time: this.start_time,
      };
      getpharmacycontent(params).then((res) => {
        if (res.data.state == 1) {
          this.tableData = res.data.data.list;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 跳转打印页面
    toPrint() {
      if (this.tableData == null) {
        this.$message.error("未选择任何数据");
        return;
      }
      this.$refs.patientprint.show(
        this.tableData,
        this.currentRow,
        this.state,
        this.start_time
      );
    },

    // 搜索患者
    searchAction() {
      this.tableData = null;
      this.getwaitmount();
    },

    // 药品发药
    dispense() {
      var tmp = this.currentRow.PatientID;
      var params = {
        patient_id: this.currentRow.PatientID,
        time: this.start_time,
      };
      this.$confirm("确定是否对该患者进行发药?", "患者发药", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning",
      })
        .then(() => {
          dispensingmedicine(params).then((res) => {
            if (res.data.state == 1) {
              this.$message.success("操作成功");
              this.gettodaynumber();
              this.searchAction();
              this.tableData = null;
              this.fun4(tmp);
              this.state = 2;
              // console.log("this.alreadmount_data",this.alreadmount_data)
              // for (let i = 0;i < this.alreadmount_data.length;i++){
              //   console.log("tmp = ",tmp)
              //     if (this.alreadmount_data[i].PatientID == tmp){
              //       console.log("i = ",i)
              //       this.$refs.table02.setCurrentRow(this.alreadmount_data[i]);
              //       this.handleCurrentChange(this.alreadmount_data[i])
              //     }
              // }
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },

    toSetting() {
      getPharmacyConfig().then((response) => {
        if (response.data.state == 1) {
          this.dialogVisible = true;
          var config = response.data.data.config;
          this.is_open = config.is_open.toString();
        }
      });
    },
    SaveSetting() {
      var params = {
        is_open: parseInt(this.is_open),
      };
      SaveSetting(params).then((response) => {
        if (response.data.state == 1) {
          var config = response.data.data.config;
          this.$message.success("保存成功!");
          this.dialogVisible = false;
        }
      });
    },
    // 药品退药
    endispense() {
      var tmp = this.currentRow.PatientID;
      var params = {
        patient_id: this.currentRow.PatientID,
        time: this.start_time,
      };
      this.$confirm("确定是否对该患者进行退药?", "患者退药", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning",
      })
        .then(() => {
          drugwithdrawal(params).then((res) => {
            if (res.data.state == 1) {
              this.$message.success("操作成功");
              this.gettodaynumber();
              this.searchAction();
              this.tableData = null;
              this.fun5(tmp);
              this.state = 1;
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>

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

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

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

  .list {
    margin: 10px 0;
  }
}
.mainRight {
  margin-left: 10px;
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  .titlelist {
    display: flex;
    justify-content: flex-end;
  }
  .el-table {
    margin-top: -13px;
  }
  .el-button {
    height: 34px;
    width: 65px;
  }
  /deep/ .el-divider {
    height: 2px;
    margin-top: 10px;
  }
}

/deep/ .el-input__inner {
  padding-right: 15px;
}

/deep/ .el-table--scrollable-x .el-table__body-wrapper {
  overflow: auto;
}
/deep/ .gutter {
  width: 15px !important;
  display: inline-block !important;
}
/deep/ .el-table__fixed-right-patch {
  width: 15px !important;
}

/deep/ .el-table__fixed-right {
  bottom: 0 !important;
  left: auto;
  right: 0;
}
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 15px !important;
  height: 15px !important;
}
</style>
