<template>
  <div style="height:100%;">
    <div class="page_hisOrder" v-loading="loading"
         element-loading-text="加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <van-sticky>
        <div class="hisOrderTitle">
          <i class="iconfont icon-zuojiantou jiantou" @click="returnPage"></i>
          <span class="titleName" @click="patientShow = true">{{ patientInfo ? patientInfo.name : ''}}<van-icon
            name="arrow-down"/></span>
          <span @click="savePrescriptions">保存</span>
        </div>
      </van-sticky>
      <van-tabs v-model="activeTab" sticky class="hisOrderTabs">
        <van-tab v-for="(item,index) in prescriptions" :key="index" :name='item.name'>
          <!-- <template #title>{{ item.name }}
            <van-icon name="close" @click="deletePrescription(item.id,item.order_status,item.name)"/>
          </template> -->
          <van-sticky>
            <div class="newAdd" @click="newAdd"><img src="../../../assets/images/his1.png" alt="">
              <p>新增</p></div>
          </van-sticky>
          <div class="toolBox">
            <div class="toolOne toolTwo" @click="dateShow = true">
              {{ item.pre_time }}
              <van-icon name="arrow-down"/>
            </div>
            <div class="toolOne" @click="doctorShow = true">
              {{ doctor }}
              <van-icon name="arrow-down"/>
            </div>
            <div class="toolOne" @click="departmentShow = true">
              {{ department }}
              <van-icon name="arrow-down"/>
            </div>
          </div>
          <div class="prescriptionBox">
            <div v-if="item.advices.length > 0 && item.project.length == 0 " v-for="(subItem,subIndex) in item.advices"
                 :key="index" class="prescriptionOne">
              <div class="preTitle">
                <div style="flex:1">
                  处方内容：<span class="preContent">{{subItem.drug_name}}</span>
                </div>
                <!-- <van-icon name="delete" class="deleteIcon"
                          @click="deleteHisDoctorAdvice(subItem.advice_id, item.order_status,item.name,subIndex)"/> -->
              </div>
              <div class="preCell">
                <div class="preCellOne">
                  <p class="preCellLable">序号：</p>
                  <el-input v-model="subItem.groupno" style="width:60%"></el-input>
                </div>
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">单次<span style="visibility: hidden;">：</span><br>用量：</p>
                  <el-input v-model="subItem.single_dose" style="width:40%" @input="getAllChange(subItem)"></el-input>
                  <el-select v-model="subItem.single_dose_unit" placeholder="请选择" style="width:40%;margin-left:2px;" @change="getAllChange(subItem)">
                    <el-option :label="subItem.drug.min_unit" :value="subItem.drug.min_unit"></el-option>
                    <el-option :label="subItem.drug.dose_unit" v-if="subItem.drug.dose_unit != subItem.drug.min_unit" :value="subItem.drug.dose_unit"></el-option>
                  </el-select>
                </div>
                <div class="preCellOne">
                  <p class="preCellLable">用法：</p>

                  <el-autocomplete
                    style="width:60%;"
                    class="inline-input"
                    v-model="subItem.delivery_way"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入内容"
                  ></el-autocomplete>&nbsp;<span style="visibility: hidden;">天</span>
                </div>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">频率：</p>
                  <el-autocomplete
                    style="width:80%;"
                    class="inline-input"
                    v-model="subItem.execution_frequency"
                    :fetch-suggestions="querySearch2"
                    placeholder="请输入内容"
                    @change="getAllChange(subItem)"
                  ></el-autocomplete>
                </div>
                <div class="preCellOne">
                  <p class="preCellLable">天数：</p>
                  <el-input v-model="subItem.day" style="width:60%" @input="getAllChange(subItem)"></el-input>&nbsp;天
                </div>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">总量：</p>
                  <el-input v-model="subItem.prescribing_number" style="width:40%" @input="changePrescribingNumber(subItem)"></el-input>
                  <!-- &nbsp;{{subItem.prescribing_number_unit}} -->
                  <el-select v-model="subItem.prescribing_number_unit" placeholder="请选择" style="width:40%;margin-left:2px;" @change="getPrescribingNumberUnit(subItem)">
                    <el-option :label="subItem.drug.min_unit" :value="subItem.drug.min_unit"></el-option>
                    <el-option :label="subItem.drug.max_unit" v-if="subItem.drug.min_unit != subItem.drug.max_unit" :value="subItem.drug.max_unit"></el-option>
                  </el-select>
                </div>
                <div class="preCellOne">
                  <p class="preCellLable">单价：</p>
                  <el-input v-model="subItem.retail_price" style="width:60%"></el-input>&nbsp;元
                </div>
              </div>
              <div class="preCellOne preCellTwo">
                <p class="preCellLable">审批标志：</p>
                <el-select v-model="subItem.hosp_appr_flag" placeholder="请选择">
                  <el-option label="审批通过" value="1"></el-option>
                  <el-option label="无须审批" value="3"></el-option>
                  <el-option label="审批不通过" value="2"></el-option>
                </el-select>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo" style="width:100%;">
                  <p class="preCellLable">备注：</p>
                  <el-input v-model="subItem.remark" style="width:80%;"></el-input>&nbsp;<span
                  style="visibility: hidden;">天</span>
                </div>
              </div>
            </div>
            <div v-if="item.advices.length == 0 && item.project.length > 0 " v-for="(subItem,subIndex) in item.project"
                 :key="index" class="prescriptionOne">
              <div class="preTitle">
                <div style="flex:1">
                  处方内容：<span class="preContent">{{subItem.project_name}}</span>
                </div>
                <!-- <van-icon name="delete" class="deleteIcon"
                          @click="deleteProject(subItem.id,item.order_status,item.name,subIndex)"/> -->
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">单次<span style="visibility: hidden;">：</span><br>用量：</p>
                  <el-input v-model="subItem.single_dose" style="width:40%"></el-input>&nbsp;{{subItem.unit}}
                </div>
                <div class="preCellOne">
                  <p class="preCellLable">用法：</p>
                  <el-autocomplete
                    style="width:60%;"
                    class="inline-input"
                    v-model="subItem.delivery_way"
                    :fetch-suggestions="querySearch3"
                    placeholder="请输入内容"
                  ></el-autocomplete>&nbsp;<span style="visibility: hidden;">天</span>
                </div>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">频率：</p>
                  <el-input v-model="subItem.execution_frequency" style="width:40%"></el-input>

                </div>
                <div class="preCellOne">
                  <p class="preCellLable">天数：</p>
                  <el-input v-model="subItem.number_days" style="width:60%"></el-input>&nbsp;天
                </div>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo">
                  <p class="preCellLable">总量：</p>
                  <el-input v-model="subItem.total" style="width:40%"></el-input>&nbsp;&nbsp;{{subItem.unit}}
                </div>
                <div class="preCellOne">
                  <p class="preCellLable">单价：</p>
                  <el-input v-model="subItem.price" style="width:60%"></el-input>&nbsp;元
                </div>
              </div>
              <div class="preCell">
                <div class="preCellOne preCellTwo" style="width:100%;">
                  <p class="preCellLable">备注：</p>
                  <el-input v-model="subItem.remark" style="width:80%;"></el-input>&nbsp;<span
                  style="visibility: hidden;">天</span>
                </div>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>


      <div class="spread">
        <img src="../../../assets/images/his8.png" @click="spread" alt="">
      </div>
      <div v-if="!loading">
        <van-popup v-model="spreadShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <div style="display:flex;flex-direction: column;height:100%">
            <div class="dialogBox">
              <div class="dialogOne" @click="open(1)"><img src="../../../assets/images/his2.png" alt=""> 选择药品</div>
              <div class="dialogOne" @click="open(3)"><img src="../../../assets/images/his3.png" alt="">选择项目</div>
              <div class="dialogOne" @click="open(4)"><img src="../../../assets/images/his4.png" alt="">项目组套</div>
              <div class="dialogOne" @click="open(5)"><img src="../../../assets/images/his5.png" alt="">处方调用</div>
              <div class="dialogOne" @click="openLast(1)"><img src="../../../assets/images/his6.png" alt="">上一方</div>
              <!-- <div class="dialogOne" @click="openNext(2)"><img src="../../../assets/images/his7.png" alt="">下一方</div> -->
            </div>
            <div class="closeBtn" @click="spreadShow = false">
              取消
            </div>
          </div>
        </van-popup>
        <van-popup v-model="nextOrLastPrescriptionShow" class="newPopup" position="bottom" :style="{ height: '100%' }">
          <next-or-last-prescription :patient_id="patient_id" :next_or_last_prescriptions="next_or_last_prescriptions"
                                     :prescriptions="prescriptions"
                                     :request_record_date="request_record_date" :doctors="doctors"
                                     :departments="departments" :name="patientInfo.name"
                                     v-on:call="call"></next-or-last-prescription>
        </van-popup>

        <van-popup v-model="historicalPrescriptionShow" class="newPopup" position="bottom" :style="{ height: '100%' }">
          <historical-prescription :patient_id="patient_id" :all_prescription="all_prescription" :doctors="doctors"
                                   :departments="departments"
                                   :srcPrescriptions="prescriptions" v-on:call="call"></historical-prescription>
        </van-popup>
        <van-popup v-model="drugsShow" class="newPopup" position="bottom" :style="{ height: '100%' }">
          <drugs :drug="drugs" :all_drug="allDrugs" :drug_type_names="drug_type_names" :drug_type="drug_type"
                 v-on:add_drug="addDrug"></drugs>
        </van-popup>
        <van-popup v-model="projectShow" class="newPopup" position="bottom" :style="{ height: '100%' }">
          <project :project="projects" :all_project="projects" :cost_classify_names="cost_classify_names"
                   :cost_classify="cost_classify" v-on:add="addProject"></project>
        </van-popup>
        <van-popup v-model="projectTemplateShow" class="newPopup" position="bottom" :style="{ height: '100%' }">
          <project-template ref="project_template" :projects="project_team" :src_projects="projects_template"
                            v-on:add="addProject"></project-template>
        </van-popup>


        <van-popup v-model="dateShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="getNowDate"
            @cancel="dateShow = false"
          />
        </van-popup>
        <van-popup v-model="doctorShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <van-picker
            show-toolbar
            :columns="doctorColumns"
            @confirm="chooseDoctor"
            @cancel="doctorShow = false"
          />
        </van-popup>
        <van-popup v-model="departmentShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <van-picker
            show-toolbar
            :columns="departmentColumns"
            @confirm="chooseDepartment"
            @cancel="departmentShow = false"
          />
        </van-popup>


        <van-popup v-model="schTypeShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <van-picker
            show-toolbar
            :columns="schTypeColumns"
            @confirm="chooseSch"
            @cancel="schTypeShow = false"
          />
        </van-popup>


        <van-popup v-model="visitStatusShow" class="newPopup" position="bottom" :style="{ height: '40%' }">
          <van-picker
            show-toolbar
            :columns="visitStatusColumns"
            @confirm="chooseVisit"
            @cancel="visitStatusShow = false"
          />
        </van-popup>


        <div class="showBox">
          <van-popup v-model="patientShow" position="top" :style="{ height: '100%' }">
            <div
              style="padding:10px;font-size:20px;text-align:right"
              @click="patientShow = false"
            >
              <van-icon name="cross"/>
            </div>
            <van-search
              class="doctorAdviceSearch"
              v-model="searchValue"
              placeholder="请输入病人名字"
              @search="onSearch"
              @input='onSearch'
            />
            <div style="display:flex;justify-content: space-around;">
              <div class="toolOne" @click="schTypeShow = true">
                {{ schTypeName }}
                <van-icon name="arrow-down"/>
              </div>
              <div class="toolOne" @click="visitStatusShow = true">
                {{ visitStatusName }}
                <van-icon name="arrow-down"/>
              </div>
            </div>
            <van-index-bar class="indexBar" sticky highlight-color="#fb6463">
              <div v-for="(subItem, index) in patients" :key="index" :index="index">
                <van-index-anchor :index="index">
                </van-index-anchor>
                <van-cell
                  @click="choosePatient(item)"
                  v-for="(item, subIndex) in subItem"
                  :key="subIndex"
                  :title="item.name"
                />
              </div>
            </van-index-bar>

          </van-popup>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import historicalPrescription from './hisOrder/historicalPrescription'
  import drugs from './hisOrder/drugs'
  import drugsTemplate from './hisOrder/drugsTemplate'
  import project from './hisOrder/project'
  import projectTemplate from './hisOrder/projectTemplate'

  import {
    CreateHisPrescription,
    DeleteDoctorAdvice,
    DeletePrescription,
    DeleteProject,
    GetCallHisPrescription,
    GetHisPatientInfo,
    GetHisPatientList,
    GetHisPrescriptionConfig,
    GetLastOrNextHisPrescription
  } from "@/api/his";
  import { uParseTime } from '@/utils/tools'
  import {parseTime} from '@/utils'
  import {Dialog} from 'vant'
  import {getDictionaryDataConfig} from '@/utils/data'
  import NextOrLastPrescription from "./hisOrder/nextOrLastPrescription";

  let pinyin = require('js-pinyin')

  const moment = require('moment')

  export default {
    components: {
      NextOrLastPrescription,
      historicalPrescription,
      drugs,
      drugsTemplate,
      project,
      projectTemplate
    },
    data() {
      return {
        searchValue: "",
        schTypeColumns: ["全部", "上午", "下午", "晚上"],
        visitStatusColumns: ["全部", "未就诊", "已就诊"],

        schTypeName: "班次",
        visitStatusName: "就诊状态",
        schTypeShow: false,
        visitStatusShow: false,
        show: false,
        styleClass: 'b',
        tabArr: [
          {title: '处方1'},
        ],
        activeTab: '处方1',
        tabIndex: 1,

        doctor_id: 0,
        department_id: 0,

        //router query params
        patient_id: this.$route.query.id,
        record_date: this.$route.query.record_date,

        //api getPatientInfo
        all_prescription: [],
        prescriptions: [],
        project_team: [],
        patientInfo: null,
        hisPatientInfo: null,
        info: null,
        doctors: [],
        departments: [],
        admin_user_info: null,

        //api getPatientList
        patient_list: [],
        next_or_last_prescriptions: [],

        //api getPrescriptionConfig
        drugs: [],
        allDrugs: [],
        projects: [],
        good_info: [],
        projects_template: [],

        time: "",
        doctor: '',
        department: '',
        dateShow: false,
        doctorShow: false,
        departmentShow: false,
        currentDate: new Date(),
        minDate: new Date(1970, 0, 1),
        maxDate: new Date(2030, 10, 1),
        doctorColumns: [],
        departmentColumns: [],
        spreadShow: false,
        historicalPrescriptionShow: false,
        nextOrLastPrescriptionShow: false,
        drugsShow: false,
        drugsTemplateShow: false,
        projectShow: false,
        projectTemplateShow: false,
        request_record_date: "",


        cost_classify: [],
        drug_type: [],
        cost_classify_names: [],
        drug_type_names: [],


        delivery_ways: [],
        execution_frequencys: [],

        good_units: [{
          id: 1,
          name: '支'
        },
          {
            id: 2,
            name: '条'
          },
          {
            id: 3,
            name: '盒'
          },
          {
            id: 4,
            name: '包'
          },
          {
            id: 5,
            name: '件'
          },
          {
            id: 6,
            name: '个'
          },
          {
            id: 7,
            name: '套'
          },
          {
            id: 8,
            name: '袋'
          },
          {
            id: 9,
            name: '箱'
          },
          {
            id: 10,
            name: '瓶'
          },
          {
            id: 11,
            name: '付'
          },
          {
            id: 12,
            name: '颗'
          },
          {
            id: 13,
            name: '根'
          },
          {
            id: 14,
            name: '桶'
          },
          {
            id: 15,
            name: '台'
          },
          {
            id: 16,
            name: '张'
          },
          {
            id: 17,
            name: '把'
          },
          {
            id: 18,
            name: '卷'
          },
          {
            id: 19,
            name: '块'
          },
          {
            id: 20,
            name: '双'
          },
          {
            id: 21,
            name: '人份'
          },
          {
            id: 22,
            name: 'kg'
          },
          {
            id: 23,
            name: 'g'
          },
          {
            id: 24,
            name: 'mg'
          },
          {
            id: 25,
            name: 'u'
          },
          {
            id: 26,
            name: 'ml'
          },
          {
            id: 27,
            name: '万u'
          }, {
            id: 28,
            name: '片'
          }, {
            id: 29,
            name: '只'
          }, {
            id: 30,
            name: '次'
          }, {
            id: 31,
            name: '米'
          }, {
            id: 32,
            name: '对'
          },
          {
            id: 31,
            name: '米'
          },
          {
            id: 32,
            name: '对'
          },
          {
            id: 33,
            name: '万份'
          },
          {
            id: 34,
            name: '副'
          },
          {
            id: 35,
            name: '本'
          },
          {
            id: 36,
            name: '轴'
          },
        ],

        patients: {},
        //
        patientShow: false,
        classes: '班次',
        state: '就诊状态',
        classesShow: false,
        stateShow: false,
        sch_type: 0,
        visit_type: 0,
        FirstPin: [
          'A',
          'B',
          'C',
          'D',
          'E',
          'F',
          'G',
          'H',
          'I',
          'J',
          'K',
          'L',
          'M',
          'N',
          'O',
          'P',
          'Q',
          'R',
          'S',
          'T',
          'U',
          'V',
          'W',
          'X',
          'Y',
          'Z'
        ],

        allSearchArr: [],

        loading: true

      }
    },
    created() {
      // if (this.styleClass == "b") {
      require('../../../styles/hisOrder1.scss')
      // } else {
      //   require('../../../styles/hisOrder2.scss')
      // }

      var nowDate = new Date()
      var nowYear = nowDate.getFullYear()
      var nowMonth = nowDate.getMonth() + 1
      var nowDay = nowDate.getDate()
      var hours = nowDate.getHours()
      var min = nowDate.getMinutes()
      var nowTime =
        nowYear +
        '-' +
        (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
        '-' +
        (nowDay < 10 ? '0' + nowDay : nowDay) + ' ' + (hours < 10 ? '0' + hours : hours) +
        ':' + (min < 10 ? '0' + min : min)

      this.time = nowTime

      this.getPatientInfo()
      this.getPrescriptionConfig()
      this.getPatientList()

      this.cost_classify = getDictionaryDataConfig('system', 'cost_classify')
      this.drug_type = getDictionaryDataConfig('system', 'drug_type')

      this.cost_classify_names.push("全部")
      this.drug_type_names.push("全部")


      for (let i = 0; i < this.cost_classify.length; i++) {
        this.cost_classify_names.push(this.cost_classify[i].name)
      }

      for (let i = 0; i < this.drug_type.length; i++) {
        this.drug_type_names.push(this.drug_type[i].name)
      }

    },
    methods: {
      returnPage() {
        let isShowTip = false
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].id == 0) {
            isShowTip = true
          }
        }
        if (isShowTip) {
          Dialog.confirm({
            title: '处方数据尚未保存,是否要保存',
          }).then(() => {
            this.savePrescriptions()
          })
            .catch(() => {
              sessionStorage.setItem('newBarIndex', 0)
              this.$router.go(-1)

            });
        } else {
          sessionStorage.setItem('newBarIndex', 0)
          this.$router.go(-1)


        }
      },
      onSearch(val) {
        let arr = []
        this.allSearchArr.map(item => {
          if (item.name.indexOf(val) != -1) {
            arr.push(item)
          }
        })
        let cityNameList = []
        for (let p in arr) {
          cityNameList.push(arr[p])
        }
        let firstName = {}
        this.FirstPin.forEach(item => {
          firstName[item] = []
          cityNameList.forEach(el => {
            let first = pinyin.getFullChars(el.name).substring(0, 1)
            if (first == item) {
              firstName[item].push(el)
            }
          })
          this.patients = firstName
          // 判断非空
          let newObj = {}
          Object.keys(this.patients).map((item, index) => {
            if (this.patients[item].length != 0) {
              newObj[item] = this.patients[item]
            }
          })
          this.patients = newObj
        })
      }, getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
      },

      returnPage() {
        let isShowTip = false
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].id == 0) {
            isShowTip = true
          }
        }
        if (isShowTip) {
          Dialog.confirm({
            title: '处方数据尚未保存,是否要保存',
          }).then(() => {
            this.savePrescriptions()
          })
            .catch(() => {
              sessionStorage.setItem('newBarIndex', 0)
              this.$router.go(-1)

            });
        } else {
          sessionStorage.setItem('newBarIndex', 0)
          this.$router.go(-1)

        }
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      querySearch(queryString, cb) {
        var restaurants = this.delivery_ways
        restaurants.map(item => {
          item.value = item.name
        })
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      }, querySearch2(queryString, cb) {
        var restaurants = this.execution_frequencys
        restaurants.map(item => {
          item.value = item.name
        })
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      }, querySearch3(queryString, cb) {
        var restaurants = getDictionaryDataConfig("system", "project_use")
        restaurants.map(item => {
          item.value = item.name
        })
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      choosePatient(item) {
        this.patient_id = item.id
        this.getPatientInfo()
        this.patientShow = false
      },
      openLast(val) {
        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }
        if (curPrescriptions.order_status == 2) {
          this.$toast({
            message: '处方已经结算,无法添加'
          })
          return
        }

        if (val == 1) {
          this.request_record_date = this.record_date
          let params = {
            patient_id: this.patientInfo.id,
            record_time: this.request_record_date,
            type: 1
          }

          this.GetNextOrLastHisPrescription(params)
        } else if (val == 3) {
          let params = {
            patient_id: this.patientInfo.id,
            record_time: this.request_record_date,
            type: 1
          }

          this.GetNextOrLastHisPrescription(params)

        }
      },
      openNext(val) {
        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }
        if (curPrescriptions.order_status == 2) {
          this.$message.error('处方已经结算,无法添加')
          return
        }
        if (val == 2) {
          this.request_record_date = this.record_date

          let params = {
            patient_id: this.patientInfo.id,
            record_time: this.request_record_date,
            type: 2
          }

          this.GetNextOrLastHisPrescription(params)
        } else if (val == 4) {
          let params = {
            patient_id: this.patientInfo.id,
            record_time: this.request_record_date,
            type: 2
          }
          this.GetNextOrLastHisPrescription(params)

        }
      }, GetNextOrLastHisPrescription(params) {
        GetLastOrNextHisPrescription(params).then(response => {
          if (response.data.state == 1) {
            this.nextOrLastPrescriptionShow = true
            this.spreadShow = false
            this.next_or_last_prescriptions = response.data.data.prescriptions
            for (let i = 0; i < this.next_or_last_prescriptions.length; i++) {
              this.next_or_last_prescriptions[i].check_group = []
            }
            this.request_record_date = parseTime(response.data.data.prescriptions[0].record_date, '{y}-{m}-{d}')
          } else {
            this.$toast({
              message: response.data.msg
            })


          }
        })

      },

      addDrug(drugs) {

        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }

        for (let i = 0; i < drugs.length; i++) {
          for (let a = 0; a < curPrescriptions.advices.length; a++) {
            if (drugs[i].id == curPrescriptions.advices[a].id) {
              this.$toast({
                message: '当前处方存在相同的药品，无法添加相同的药品'
              })
              return
            }
          }
        }
        let index = 0
        if(curPrescriptions.advices.length > 0){
          index =  curPrescriptions.advices.length
        }

        for (let b = 0; b < drugs.length; b++){
          let temp_index = b + 1
          drugs[b]['groupno'] = index + temp_index
        }

        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            this.prescriptions[i].advices = this.prescriptions[i].advices.concat(drugs)
          }
        }
      },
      addProject(projects) {
        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }


        for (let i = 0; i < projects.length; i++) {
          for (let a = 0; a < curPrescriptions.project.length; a++) {
            if (projects[i].project_id == curPrescriptions.project[a].project_id) {
              this.$toast({
                message: '当前处方存在相同的项目，无法添加相同的项目'
              })
              return
            }
          }
        }


        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            this.prescriptions[i].project = this.prescriptions[i].project.concat(projects)
          }
        }
      },
      call(val) {
        this.prescriptions = []
        this.prescriptions = val
        for (let i = 0; i < this.prescriptions.length; i++) {
          var nowDate = new Date()
          var nowYear = nowDate.getFullYear()
          var nowMonth = nowDate.getMonth() + 1
          var nowDay = nowDate.getDate()
          var hours = nowDate.getHours()
          var min = nowDate.getMinutes()
          var nowTime =
            nowYear +
            '-' +
            (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
            '-' +
            (nowDay < 10 ? '0' + nowDay : nowDay) + ' ' + (hours < 10 ? '0' + hours : hours) +
            ':' + (min < 10 ? '0' + min : min)
          this.prescriptions[i]['pre_time'] = nowTime
          this.prescriptions[i]['med_type'] = ""
          this.prescriptions[i]['order_status'] = 1

          this.prescriptions[i].name = '处方' + (i + 1)

        }
      },
      spread() {
        this.spreadShow = true
      },
      open(index) {
        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }

        if (curPrescriptions.order_status == 2) {
          this.$toast({
            message: '当前处方已经结算,无法添加药品或者项目或者处方调用'
          })
          return
        }

        if (index == 1) {

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length > 0) {
            this.$toast({
              message: '当前处方为项目,无法添加药品'
            })
            return
          }

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length == 0) {
            this.drugsShow = true
          }

          if (curPrescriptions.advices.length > 0 && curPrescriptions.project.length == 0) {
            this.drugsShow = true

          }


        } else if (index == 2) {
          this.drugsTemplateShow = true
        } else if (index == 3) {

          if (curPrescriptions.advices.length > 0 && curPrescriptions.project.length == 0) {
            this.$toast({
              message: '当前处方为药品,无法添加项目'
            })
            return
          }

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length == 0) {
            this.projectShow = true

          }

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length > 0) {
            this.projectShow = true

          }


        } else if (index == 4) {
          if (curPrescriptions.advices.length > 0 && curPrescriptions.project.length == 0) {
            this.$toast({
              message: '当前处方为药品,无法添加项目'
            })
            return
          }

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length == 0) {
            this.projectTemplateShow = true

          }

          if (curPrescriptions.advices.length == 0 && curPrescriptions.project.length > 0) {
            this.projectTemplateShow = true

          }

          this.$nextTick(() => {
            this.$refs.project_template.setData()

          });

        } else if (index == 5) {
          this.historicalPrescriptionShow = true
        }
        this.spreadShow = false
      },
      close(index) {
        if (index == 1) {
          this.drugsShow = false
        } else if (index == 2) {
          this.drugsTemplateShow = false
        } else if (index == 3) {
          this.projectShow = false
        } else if (index == 4) {
          this.projectTemplateShow = false
        } else if (index == 5) {
          this.historicalPrescriptionShow = false
        }
      },
      savePrescriptions() {
        if (this.prescriptions[0].advices.length == 0 && this.prescriptions[0].project.length == 0) {
          this.$toast({
            message: '请先开处方'
          })
          return
        }

        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }
        if (curPrescriptions.order_status == 2) {
          this.$toast({
            message: '当前处方已经结算,无法保存'
          })
          return
        }
        if (this.doctor.length <= 0) {
          this.$toast({
            message: '医生不能为空'
          })
          return
        }

        if (this.department.length <= 0) {
          this.$toast({
            message: '科室不能为空'
          })
          return
        }
        let params = {
          patient_id: this.patientInfo.id,
          doctor: this.doctor_id,
          department: this.department_id,
          record_date: this.record_date,
          his_patient_id: this.hisPatientInfo.id,
        }

        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].advices.length > 0 && this.prescriptions[i].project.length == 0) {
            this.prescriptions[i]['type'] = 1
          }
          if (this.prescriptions[i].advices.length == 0 && this.prescriptions[i].project.length > 0) {
            this.prescriptions[i]['type'] = 2
          }

          for (let b = 0; b < this.prescriptions[i].advices.length; b++) {
            this.prescriptions[i].advices[b].single_dose = this.prescriptions[i].advices[b].single_dose.toString()
            this.prescriptions[i].advices[b].prescribing_number = this.prescriptions[i].advices[b].prescribing_number.toString()
            this.prescriptions[i].advices[b].retail_price = this.prescriptions[i].advices[b].retail_price.toString()
            this.prescriptions[i].advices[b].day = parseInt(this.prescriptions[i].advices[b].day)
            this.prescriptions[i].advices[b].groupno = parseInt(this.prescriptions[i].advices[b].groupno)

          }
          for (let b = 0; b < this.prescriptions[i].project.length; b++) {
            this.prescriptions[i].project[b].price = this.prescriptions[i].project[b].price.toString()
            this.prescriptions[i].project[b].total = this.prescriptions[i].project[b].total.toString()
            this.prescriptions[i].project[b].delivery_way = this.prescriptions[i].project[b].delivery_way.toString()
          }

        }
        let data = {
          'prescriptions': this.prescriptions
        }
        CreateHisPrescription(data, params).then(response => {
          if (response.data.state == 1) {
            this.getPatientInfo()
            this.$toast({
              message: '保存成功'
            })
          }else {
            this.$toast({
              message: response.data.msg
            })
          }
        })

      },
      deletePrescription(id, order_status, name) {
        if (order_status == 2) {
          this.$toast({
            message: '该处方已经结算，无法删除'
          })
          return
        }
        if (name == '处方1') {
          this.$toast({
            message: '处方1无法删除'
          })
          return
        }

        Dialog.confirm({
          title: '处方删除后不可恢复，是否确认删除',
        }).then(() => {
          if (id == 0) {
            this.prescriptions.map((item, index) => {
              if (item.name == name) {
                this.prescriptions.splice(index, 1);
              }
            })
            this.activeTab = this.prescriptions[this.prescriptions.length-1].name
          } else {
            let params = {
              'id': id,
            }
            DeletePrescription(params).then(response => {
              if (response.data.state == 0) {
                this.$toast({
                  message: response.data.msg
                })
                return false
              } else {
                this.prescriptions.map((item, index) => {
                  if (item.name == name) {
                    this.prescriptions.splice(index, 1);
                  }
                })

                this.$toast({
                  message: response.data.data.msg
                })
                this.activeTab = this.prescriptions[this.prescriptions.length-1].name
                // this.$message.success(response.data.data.msg)
              }
            })

          }

        })
          .catch(() => {

          });




      },
       deleteHisDoctorAdvice(id, order_status, name, subIndex) {

        if (order_status == 2) {
          this.$toast({
            message: '该处方已经结算，无法删除'
          })
          return
        }
        Dialog.confirm({
          title: '药品删除后不可恢复，是否确认删除',
        }).then(() => {
          if (id == 0) {
            this.prescriptions.map((item, index) => {
              if (item.name == name) {
                item.advices.splice(subIndex, 1)
              }
            })
          } else {
            let params = {
              'id': id,
            }
            DeleteDoctorAdvice(params).then(response => {
              if (response.data.state == 0) {
                // this.$message.error(response.data.msg)
                this.$toast({
                  message: response.data.msg
                })
                return false

              } else {
                this.prescriptions.map((item, index) => {
                  if (item.name == name) {
                    item.advices.splice(subIndex, 1)
                  }
                })
                // var temp2 = this.deepClone(this.prescription.advices)
                // temp2.splice(index, 1)
                // this.prescription.advices = temp2
                this.$message.success(response.data.data.msg)
              }
            })


          }

        })
          .catch(() => {

          });


      }, deleteProject(id, order_status, name, subIndex) {
        if (order_status == 2) {
          this.$toast({
            message: '该处方已经结算，无法删除'
          })
          return
        }

        Dialog.confirm({
          title: '项目删除后不可恢复，是否确认删除',
        }).then(() => {
          if (id == 0) {

            this.prescriptions.map((item, index) => {
              if (item.name == name) {
                item.project.splice(subIndex, 1)
              }
            })

          } else {

            let params = {
              'id': id,
            }
            DeleteProject(params).then(response => {
              if (response.data.state == 0) {
                this.$toast({
                  message: response.data.msg
                })
                return false

              } else {
                this.prescriptions.map((item, index) => {
                  if (item.name == name) {
                    item.project.splice(subIndex, 1)
                  }
                })
                this.$toast({
                  message: response.data.data.msg
                })

              }
            })


          }

        })
          .catch(() => {

          });


      },
      getPatientList() {
        let params = {
          'record_date': this.record_date,
          'sch_type': this.sch_type,
          'visit_type': this.visit_type,
        }
        this.patient_list = []
        GetHisPatientList(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.schTypeShow = false
            this.visitStatusShow = false
            this.patient_list = response.data.data.list

            this.allSearchArr = this.patient_list
            let cityNameList = []
            for (let p in this.patient_list) {
              cityNameList.push(this.patient_list[p])
            }
            let firstName = {}
            this.FirstPin.forEach(item => {
              firstName[item] = []
              cityNameList.forEach(el => {
                let first = pinyin.getFullChars(el.name).substring(0, 1)
                if (first == item) {
                  firstName[item].push(el)
                }
              })
              this.patients = firstName
              // 判断非空
              let newObj = {}
              Object.keys(this.patients).map((item, index) => {
                if (this.patients[item].length != 0) {
                  newObj[item] = this.patients[item]
                }
              })
              this.patients = newObj
              // console.log('所有的病人', this.allSearchArr)
            })

          }
        })

      },
      getPatientInfo() {
        this.loading = true
        var nowDate = new Date()
        var nowYear = nowDate.getFullYear()
        var nowMonth = nowDate.getMonth() + 1
        var nowDay = nowDate.getDate()
        var hours = nowDate.getHours()
        var min = nowDate.getMinutes()

        var nowTime =
          nowYear +
          '-' +
          (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
          '-' +
          (nowDay < 10 ? '0' + nowDay : nowDay) + " " + (hours < 10 ? '0' + hours : hours) +
          ':' + (min < 10 ? '0' + min : min)

        let params = {
          'record_date': this.record_date,
          'patient_id': this.patient_id,
          'start_time': moment(new Date()).subtract(30, 'days').format('YYYY-MM-DD'),
          'end_time': moment(new Date()).add('year', 0).format("YYYY-MM-DD")

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

              response.data.data.sch_prescriptions = []
            }
            for(let i = 0;i < response.data.data.sch_prescriptions.length; i++){
              if(response.data.data.sch_prescriptions[i].advices == null){
                response.data.data.sch_prescriptions[i].advices = []
              }

              if(response.data.data.sch_prescriptions[i].project == null){
                response.data.data.sch_prescriptions[i].project = []
              }

            }


            this.prescriptions = []
            this.all_prescription = []
            this.patientInfo = response.data.data.xt_info
            this.hisPatientInfo = response.data.data.his_info
            this.info = response.data.data.info
            this.doctors = response.data.data.doctors
            this.departments = response.data.data.department
            this.all_prescription = response.data.data.all_prescriptions



            // this.project_team = response.data.data.team


            for (let i = 0; i < this.all_prescription.length; i++) {
              this.all_prescription[i].check_group = []
            }
            // console.log(this.all_prescription)

            this.admin_user_info = response.data.data.admin_user_info

            for (let i = 0; i < this.doctors.length; i++) {
              this.doctorColumns.push(this.doctors[i].user_name)
            }
            for (let i = 0; i < this.departments.length; i++) {
              this.departmentColumns.push(this.departments[i].name)
            }


            if (this.info.id > 0) {
              // console.log(this.info)
              // console.log(this.info.doctor_id)
              // console.log(this.info.departments)
              for (let i = 0; i < this.doctors.length; i++) {
                // console.log(this.doctors[i].admin_user_id)
                // console.log(this.info.doctor_id)
                if (this.doctors[i].admin_user_id == this.info.doctor_id) {
                  this.doctor = this.doctors[i].user_name
                  this.doctor_id = this.doctors[i].admin_user_id
                }
              }
              for (let i = 0; i < this.departments.length; i++) {
                if (this.departments[i].id == this.info.departments) {
                  this.department = this.departments[i].name
                  this.department_id = this.departments[i].id
                }
              }


            } else {
              if (this.hisPatientInfo.doctor != 0 && this.hisPatientInfo.department != 0) {
                for (let i = 0; i < this.doctors.length; i++) {
                  if (this.doctors[i].admin_user_id == this.hisPatientInfo.doctor) {
                    this.doctor = this.doctors[i].name
                    this.doctor_id = this.doctors[i].admin_user_id
                  }
                }
                for (let i = 0; i < this.departments.length; i++) {
                  if (this.departments[i].id == this.hisPatientInfo.department) {
                    this.department = this.departments[i].name
                    this.department_id = this.departments[i].id

                  }
                }
              } else {
                if (this.admin_user_info.user_type == 2 || this.admin_user_info.user_type == 1) {

                  for (let i = 0; i < this.doctors.length; i++) {
                    if (this.doctors[i].admin_user_id == this.admin_user_info.admin_user_id) {
                      this.doctor = this.doctors[i].user_name
                      this.doctor_id = this.doctors[i].admin_user_id
                    }
                  }


                  if (this.admin_user_info.department_id == 0) {
                    if (this.departments && this.departments.length > 0) {
                      this.department_id = this.departments[0].id
                      this.department = this.departments[0].name

                    } else {
                      this.department_id = 0
                      this.department = ''
                    }

                  } else {
                    for (let i = 0; i < this.departments.length; i++) {
                      if (this.departments[i].id == this.admin_user_info.department_id) {
                        this.department = this.departments[i].name
                        this.department_id = this.departments[i].id
                      }
                    }
                  }
                } else {
                  this.doctor_id = this.doctors[0].admin_user_id
                  this.doctor = this.doctors[0].user_name
                  this.department_id = this.departments[0].id
                  this.department = this.departments[0].name
                }

              }
            }


            // if(this.doctor_id == 0){
            //   this.doctor_id = this.doctors[0].admin_user_id
            //   this.doctor = this.doctors[0].user_name
            // }
            //
            // if(this.department_id == 0){
            //   this.department_id = this.departments[0].id
            //   this.department = this.departments[0].name
            // }



            if (response.data.data.prescription.length > 0) {
              for (let i = 0; i < response.data.data.prescription.length; i++) {
                var prescription = response.data.data.prescription[i];
                let tempAdvice = [];
                let tempProject = [];
                let tempAddition = [];


                //药品
                for (let b = 0; b < prescription.advices.length; b++) {
                  let obj = {
                    advice_id: prescription.advices[b].id,
                    drug_name: prescription.advices[b].advice_name,
                    single_dose: prescription.advices[b].single_dose,
                    delivery_way: prescription.advices[b].delivery_way,
                    execution_frequency: prescription.advices[b].execution_frequency,
                    retail_price: prescription.advices[b].price.toString(),
                    remark: prescription.advices[b].remark,
                    day: prescription.advices[b].day,
                    prescribing_number: prescription.advices[b].prescribing_number.toString(),
                    single_dose_unit: prescription.advices[b].single_dose_unit,
                    prescribing_number_unit: prescription.advices[b].prescribing_number_unit,
                    medical_insurance_number: prescription.advices[b].med_list_codg,
                    id: prescription.advices[b].drug_id,
                    drug:prescription.advices[b].drug,
                    groupno:prescription.advices[b].groupno,
                    hosp_appr_flag:prescription.advices[b].hosp_appr_flag.toString(),

                  };
                  tempAdvice.push(obj)
                }


                //项目
                for (let b = 0; b < prescription.project.length; b++) {
                  let obj = {
                    id: prescription.project[b].id,
                    project_id: prescription.project[b].project_id,
                    project_name: prescription.project[b].project.project_name,
                    statistical_classification: prescription.project[b].project.statistical_classification,
                    single_dose: prescription.project[b].single_dose,
                    delivery_way: prescription.project[b].delivery_way,
                    execution_frequency: prescription.project[b].execution_frequency,
                    number_days: prescription.project[b].day,
                    total: prescription.project[b].count.toString(),
                    price: prescription.project[b].price,
                    remark: prescription.project[b].remark,
                    medical_code: prescription.project[b].project.medical_code,
                    unit: prescription.project[b].project.unit,
                    type: prescription.project[b].type
                  };

                  if(prescription.project[b].type == 2){
                    obj['statistical_classification'] =  prescription.project[b].project.statistical_classification
                    obj['medical_code'] =  prescription.project[b].project.medical_code
                    obj['project_name'] =  prescription.project[b].project.project_name

                  }else if(prescription.project[b].type == 3){
                    obj['statistical_classification'] = ""
                    obj['medical_code'] =  prescription.project[b].good_info.medical_insurance_number
                    obj['project_name'] =  prescription.project[b].good_info.good_name
                  }
                  tempProject.push(obj)
                }



                var preTime = "";

                if (prescription.pre_time == 0) {
                  preTime = nowTime
                } else {
                  preTime = this.getTime(prescription.pre_time, "{y}-{m}-{d} {h}:{i}")
                }

                let index = i + 1;
                let obj = {
                  id: prescription.id,
                  name: '处方' + index,
                  advices: tempAdvice,
                  project: tempProject,
                  addition: tempAddition,
                  order_status: prescription.order_status,
                  pre_time: preTime,
                  med_type: prescription.med_type,
                };
                this.prescriptions.push(obj)
              }
            } else {

              if(response.data.data.count <= 1 && response.data.data.schedule.id > 0 && response.data.data.sch_prescriptions.length > 0){

                for (let i = 0; i < response.data.data.sch_prescriptions.length; i++) {
                  var prescription = response.data.data.sch_prescriptions[i];
                  for (let b = 0; b < prescription.advices.length; b++) {
                    // console.log(prescription.advices[b].drug.is_special_diseases)
                    if (prescription.med_type == "14" && prescription.advices[b].drug.is_special_diseases != 1) {
                      prescription.advices.splice(b--,1)
                    }
                  }
                  for (let b = 0; b < prescription.project.length; b++) {
                    if(prescription.project[b].type == 2){
                      if (prescription.med_type == "14" && prescription.project[b].project.disease_directory != 1) {
                        prescription.project.splice(b--,1)
                      }
                    }else if(prescription.project[b].type == 3){
                      if (prescription.med_type == "14" && prescription.project[b].good_info.is_special_diseases != 1) {
                        prescription.project.splice(b--,1)
                      }
                    }
                  }
                }

                for (let i = 0; i < response.data.data.sch_prescriptions.length; i++) {
                  var prescription = response.data.data.sch_prescriptions[i];
                  let tempAdvice = [];
                  let tempProject = [];
                  let tempAddition = [];

                  //药品
                  for (let b = 0; b < prescription.advices.length; b++) {
                    let index = b + 1
                    let obj = {
                      advice_id:0,
                      drug_name: prescription.advices[b].advice_name,
                      single_dose: prescription.advices[b].single_dose,
                      delivery_way: prescription.advices[b].delivery_way,
                      execution_frequency: prescription.advices[b].execution_frequency,
                      // retail_price: prescription.advices[b].price.toString(),
                      remark: prescription.advices[b].remark,
                      day: prescription.advices[b].day,
                      prescribing_number: prescription.advices[b].prescribing_number.toString(),
                      single_dose_unit: prescription.advices[b].single_dose_unit,
                      prescribing_number_unit: prescription.advices[b].prescribing_number_unit,
                      medical_insurance_number: prescription.advices[b].med_list_codg,
                      id: prescription.advices[b].drug_id,
                      drug:prescription.advices[b].drug,
                      groupno: prescription.advices[b].groupno,
                      hosp_appr_flag:"1"

                    };
                    if (obj.prescribing_number_unit == prescription.advices[b].drug.min_unit){
                      obj['retail_price'] =  prescription.advices[b].drug.min_price.toString()
                    } else if(obj.prescribing_number_unit == prescription.advices[b].drug.max_unit){
                      obj['retail_price'] =  prescription.advices[b].drug.retail_price.toString()
                    } else {
                      obj['retail_price'] =  prescription.advices[b].drug.min_price.toString()
                    }
                    tempAdvice.push(obj)
                  }

                  //项目
                  for (let b = 0; b < prescription.project.length; b++) {
                    let obj = {
                      id:0,
                      project_id: prescription.project[b].project_id,
                      project_name: prescription.project[b].project.project_name,
                      statistical_classification: prescription.project[b].project.statistical_classification,
                      single_dose: prescription.project[b].single_dose,
                      delivery_way: prescription.project[b].delivery_way,
                      execution_frequency: prescription.project[b].execution_frequency,
                      number_days: prescription.project[b].day,
                      total: prescription.project[b].count.toString(),
                      price: prescription.project[b].price,
                      remark: prescription.project[b].remark,
                      medical_code: prescription.project[b].project.medical_code,
                      unit: prescription.project[b].project.unit,
                      type: prescription.project[b].type
                    };
                    if (prescription.project[b].type == 2) {
                      obj['statistical_classification'] = prescription.project[b].project.statistical_classification
                      obj['medical_code'] = prescription.project[b].project.medical_code
                      obj['project_name'] = prescription.project[b].project.project_name
                      obj['price'] = prescription.project[b].project.price
                    } else if (prescription.project[b].type == 3) {
                      obj['statistical_classification'] = ""
                      obj['medical_code'] = prescription.project[b].good_info.medical_insurance_number
                      obj['project_name'] = prescription.project[b].good_info.good_name
                      obj['price'] = prescription.project[b].good_info.packing_price
                    }
                    tempProject.push(obj)
                  }
                  var preTime = nowTime
                  let index = i + 1;
                  let obj = {
                    id: 0,
                    name: '处方' + index,
                    advices: tempAdvice,
                    project: tempProject,
                    addition: tempAddition,
                    order_status: 1,
                    pre_time: preTime,
                    med_type:"",
                  };
                  this.prescriptions.push(obj)
                }
              }else{
                let obj = {
                  id: 0,
                  name: '处方' + 1,
                  advices: [],
                  project: [],
                  addition: [],
                  order_status: 0,
                  pre_time: nowTime,
                  med_type:"",

                };
                this.prescriptions.push(obj)
              }
            }

            this.loading = false
            // console.log(this.prescriptions)
          }
        })
      },
      getPrescriptionConfig() {
        GetHisPrescriptionConfig().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.drugs = response.data.data.drugs
            this.allDrugs = response.data.data.drugs
            this.projects = response.data.data.projects
            this.projects_template = response.data.data.team
            this.delivery_ways = response.data.data.drugways
            this.execution_frequencys = response.data.data.efs
            this.good_info = response.data.data.good_info

            for (let i = 0; i < this.projects.length; i++) {
              this.projects[i]['type'] = 2
            }

            for (let i = 0; i < this.good_info.length; i++) {
              let obj = {
                id: this.good_info[i].id,
                project_name: this.good_info[i].good_name,
                price: this.good_info[i].retail_price,
                single_dose: this.good_info[i].specification_name,
                statistical_classification: "",
                delivery_way: "",
                execution_frequency: "",
                number_days: 1,
                total: 1,
                remark: "",
                medical_code: "",
                type: 3,
                unit: this.getGoodUnit(this.good_info[i].good_unit),
              }
              this.projects.push(obj)
            }


            for (let i = 0; i < this.projects_template.length; i++) {
              this.projects_template[i]['project'] = []
              for (let b = 0; b < this.projects_template[i].list.length; b++) {
                if(this.projects_template[i].list != null) {
                  if (this.projects_template[i].list[b].type == 3) {
                    let obj = {
                      id: this.projects_template[i].list[b].good_info.id,
                      project_name: this.projects_template[i].list[b].good_info.good_name,
                      price: this.projects_template[i].list[b].good_info.retail_price,
                      single_dose: "",
                      statistical_classification: "",
                      delivery_way: "",
                      execution_frequency: "",
                      remark: "",
                      medical_code: "",
                      number_days: 1,
                      total: 1,
                      type:3,
                      team_id:this.projects_template[i].id,
                      unit: this.getGoodUnit(this.projects_template[i].list[b].good_info.good_unit)
                    }
                    this.projects_template[i].project.push(obj)
                  } else if (this.projects_template[i].list[b].type == 2) {
                    this.projects_template[i].list[b].project['type'] = 2
                    this.projects_template[i].project.push(this.projects_template[i].list[b].project)
                  }
                }else{
                  this.projects_template[i].project = []
                }
              }
            }
            // console.log(this.projects_template)

            for (let i = 0; i < this.projects_template.length; i++) {
              let obj = {
                text: this.projects_template[i].project_team,
                children: []
              }
              for (let b = 0; b < this.projects_template[i].project.length; b++) {
                this.projects_template[i].project[b]['new_id'] = Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, 10 - 1))

                let obj2 = {
                  text: this.projects_template[i].project[b].project_name,
                  id: this.projects_template[i].project[b].new_id,
                }
                obj.children.push(obj2)
              }
              this.project_team.push(obj)
            }
          }
        })


      }, getGoodUnit(id) {
        var goodUnit = this.good_units
        for (let i = 0; i < goodUnit.length; i++) {
          if (goodUnit[i].id == id) {
            return goodUnit[i].name
          }
        }
      },
      deleteTab(title) {
        this.tabArr.map((item, index) => {
          if (item.title == title) {
            this.tabArr.splice(index, 1);
          }
        })

      },
      newAdd() {
        // console.log(this.activeTab)

        if (this.prescriptions[0].order_status == 2) {
          // this.$message.error('该处方已经结算或者退费，无法继续添加处方')
          this.$toast({
            message: '该处方已经结算或者退费，无法继续添加处方'
          })
          return
        }

        let curPrescriptions = null
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }
        if (curPrescriptions == null || (curPrescriptions.advices.length == 0 && curPrescriptions.project.length == 0)) {
          // this.$message.error('当前处方无数据，新增数据后才能新增处方')
          this.$toast({
            message: '当前处方无数据，新增数据后才能新增处方'
          })
          return
        }

        // this.tabIndex = this.prescriptions.length

        // this.tabIndex = this.prescriptions.length

        var str = this.prescriptions[this.prescriptions.length - 1].name
        this.tabIndex = parseInt(str.charAt(str.length - 1))
        ++this.tabIndex
        let newTabName = '处方' + this.tabIndex
        var nowDate = new Date()
        var nowYear = nowDate.getFullYear()
        var nowMonth = nowDate.getMonth() + 1
        var nowDay = nowDate.getDate()

        var hours = nowDate.getHours()
        var min = nowDate.getMinutes()

        var nowTime =
          nowYear +
          '-' +
          (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
          '-' +
          (nowDay < 10 ? '0' + nowDay : nowDay) + ' ' + (hours < 10 ? '0' + hours : hours) +
          ':' + (min < 10 ? '0' + min : min)

        this.prescriptions.push({
          id: 0,
          name: newTabName,
          order_status: 0,
          advices: [],
          project: [],
          addition: [],
          pre_time: nowTime,
          med_type:"",
        })


        this.$nextTick(function () {
          this.activeTab = newTabName
        })

      },
      getNowDate(value) {
        let year = value.getFullYear()
        let month = value.getMonth() + 1
        let day = value.getDate()
        let hour = value.getHours()
        let minuters = value.getMinutes()
        if (month >= 1 && month <= 9) {
          month = `0${month}`
        }
        if (day >= 1 && day <= 9) {
          day = `0${day}`
        }

        if (hour >= 1 && hour <= 9) {
          hour = `0${hour}`
        }

        if (minuters >= 1 && minuters <= 9) {
          minuters = `0${minuters}`
        }

        let curPrescriptions = {}
        for (let i = 0; i < this.prescriptions.length; i++) {
          if (this.prescriptions[i].name == this.activeTab) {
            curPrescriptions = this.prescriptions[i]
          }
        }
        curPrescriptions.pre_time = `${year}-${month}-${day} ${hour}:${minuters}`
        // this.time = `${year}-${month}-${day} ${hour}:${minuters}`
        this.dateShow = false
      },
      chooseDoctor(val) {
        this.doctorShow = false
        let tempDepartmentId = 0
        for (let i = 0; i < this.doctors.length; i++) {
          if (this.doctors[i].user_name == val) {
            this.doctor = this.doctors[i].user_name
            this.doctor_id = this.doctors[i].admin_user_id

            tempDepartmentId = this.doctors[i].department_id
            // console.log(tempDepartmentId)
          }
        }

        this.department = ""
        this.department_id = 0
        for (let i = 0; i < this.departments.length; i++) {
          if (this.departments[i].id == tempDepartmentId) {
            this.department = this.departments[i].name
            this.department_id = this.departments[i].id
          }
        }


      },
      chooseDepartment(val) {

        for (let i = 0; i < this.departments.length; i++) {
          if (this.departments[i].name == val) {
            this.department = this.departments[i].name
            this.department_id = this.departments[i].id
          }
        }
        this.departmentShow = false
      }, chooseSch(val) {
        this.schTypeName = val
        switch (val) {
          case '全部':
            this.sch_type = 0
            this.getPatientList()
            break
          case '上午':
            this.sch_type = 1
            this.getPatientList()
            break
          case '下午':
            this.sch_type = 2
            this.getPatientList()
            break
          case '晚上':
            this.sch_type = 3
            this.getPatientList()
            break

        }


      }, chooseVisit(val) {
        this.visitStatusName = val
        switch (val) {
          case '全部':
            this.visit_type = 0
            this.getPatientList()
            break
          case '未就诊':
            this.visit_type = 1
            this.getPatientList()
            break
          case '已就诊':
            this.visit_type = 2
            this.getPatientList()
            break
        }


      },
      getAllChange(subItem){
        if(subItem.drug.min_unit == subItem.single_dose_unit){
          if(subItem.prescribing_number_unit == subItem.drug.min_unit){
            subItem.prescribing_number = subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day
          }else{
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency)) * subItem.day / subItem.drug.min_number)
          }
        }else{
          if(subItem.prescribing_number_unit == subItem.drug.min_unit){
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day) / subItem.drug.dose)
          }else{
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day) / subItem.drug.dose / subItem.drug.min_number)
          }
        }
        if(subItem.prescribing_number == 0){
          subItem.prescribing_number = 1
        }
        if(subItem.prescribing_number_unit == subItem.drug.min_unit){
          // subItem.retail_price = subItem.drug.min_price * subItem.prescribing_number
          if(subItem.prescribing_number > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
        }else{
          if((parseInt(subItem.prescribing_number) * subItem.drug.min_number) > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
          // subItem.retail_price = subItem.drug.retail_price * subItem.prescribing_number
        }

      },
      getPrescribingNumberUnit(subItem){
        if(subItem.drug.min_unit == subItem.single_dose_unit){
          if(subItem.prescribing_number_unit == subItem.drug.min_unit){
            subItem.prescribing_number = subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day
          }else{
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency)) * subItem.day / subItem.drug.min_number)
          }
        }else{
          if(subItem.prescribing_number_unit == subItem.drug.min_unit){
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day) / subItem.drug.dose)
          }else{
            subItem.prescribing_number = Math.ceil((subItem.single_dose * this.getNum(subItem.execution_frequency) * subItem.day) / subItem.drug.dose / subItem.drug.min_number)
          }
        }
        if(subItem.prescribing_number == 0){
          subItem.prescribing_number = 1
        }
        if(subItem.prescribing_number_unit == subItem.drug.min_unit){
          subItem.retail_price = subItem.drug.min_number / subItem.retail_price
          if(subItem.prescribing_number > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
        }else{
          if((parseInt(subItem.prescribing_number) * subItem.drug.min_number) > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
          subItem.retail_price = subItem.drug.retail_price * subItem.prescribing_number
        }
      },
      changePrescribingNumber(subItem){
        if(subItem.prescribing_number_unit == subItem.drug.min_unit){
          if(parseInt(subItem.prescribing_number) > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
        }else{
          if((parseInt(subItem.prescribing_number) * subItem.drug.min_number) > subItem.drug.total){
            this.$toast({message: subItem.drug_name + '库存不足'})
          }
        }
      },
      getNum(execution_frequency){
        let arr = [
          {name:'立即执行',count:1},
          {name:'透析时',count:1},
          {name:'透析1h一次',count:1},
          {name:'透析2h一次',count:1},
          {name:'透析3h一次',count:1},
          {name:'每日一次',count:1},
          {name:'每日两次',count:2},
          {name:'每日三次',count:3},
          {name:'每晚一次',count:1},
          {name:'每晚',count:1},
          {name:'上机前',count:1},
          {name:'下机前',count:1},
          {name:'透析后立即',count:1},
          {name:'持续使用',count:1},
          {name:'临时开药',count:1},
          {name:'临睡前',count:1},
          {name:'隔日一次',count:1},
          {name:'隔三日一次',count:1},
          {name:'每二小时一次',count:12},
          {name:'每四小时一次',count:6},
          {name:'每六小时一次',count:4},
          {name:'每八小时一次',count:3},
        ]
        let num = ''
        arr.map(item => {
          if(item.name == execution_frequency){
            num = item.count
          }
        })
        if(num == ''){
          num = 1
        }
        return num
      }
    }
  }
</script>




