<template>
    <div class="prescriptionTable">
        <el-table v-if="activeType  == 1" :data="prescription.advices" border style="width: 99%;"
                  :row-style="{ color: '#303133' }"
                  :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}" highlight-current-row>
            <el-table-column align="center" prop="day" width="70" label="序号">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.groupno" placeholder=""></el-input>
                    </div>
                </template>
            </el-table-column>


            <el-table-column align="center" prop="drug_name" label="名称">
                <template slot-scope="scope"><span :title="scope.row.drug_name">{{ scope.row.drug_name }}</span>
                </template>
            </el-table-column>


            <el-table-column align="center" prop="single_dose" width="120" label="单次用量">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.single_dose" @input="getAllChange(scope)"
                                  style="width:50%;"></el-input>
                        <!-- <div>{{scope.row.single_dose_unit}}</div> -->
                        <el-select v-model="scope.row.single_dose_unit" placeholder="请选择" style="width:50%;"
                                   @change="getAllChange(scope)">
                            <el-option :label="scope.row.drug.min_unit" :value="scope.row.drug.min_unit"></el-option>
                            <el-option :label="scope.row.drug.dose_unit"
                                       v-if="scope.row.drug.dose_unit != scope.row.drug.min_unit"
                                       :value="scope.row.drug.dose_unit"></el-option>
                        </el-select>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="delivery_way" width="100" label="用法">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.delivery_way" placeholder="请选择">
                        <el-option
                                v-for="(item,index) in drugways"
                                :key="index"
                                :label="item.name"
                                :value="item.name">
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="execution_frequency" width="100" label="频率">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.execution_frequency" placeholder="请选择" @change="getAllChange(scope)">
                        <el-option
                                v-for="item,index in efs"
                                :key="index"
                                :label="item.name"
                                :value="item.name">
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>


            <el-table-column align="center" prop="day" width="70" label="天数">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.day" @input="getAllChange(scope)" placeholder=""></el-input>
                        {{'天'}}
                    </div>
                </template>
            </el-table-column>

            <el-table-column align="center" prop="prescribing_number" width="120" label="总量">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.prescribing_number" @input="changePrescribingNumber(scope)"
                                  style="width:50%" placeholder=""></el-input>
                        <!-- <div> {{scope.row.prescribing_number_unit}}</div> -->
                        <el-select v-model="scope.row.prescribing_number_unit" placeholder="请选择" style="width:50%;"
                                   @change="getPrescribingNumberUnit(scope)">
                            <el-option :label="scope.row.drug.min_unit" :value="scope.row.drug.min_unit"></el-option>
                            <el-option :label="scope.row.drug.max_unit"
                                       v-if="scope.row.drug.min_unit != scope.row.drug.max_unit"
                                       :value="scope.row.drug.max_unit"></el-option>
                        </el-select>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="retail_price" width="80" label="单价">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.retail_price" placeholder="" readonly></el-input>
                        <div>{{'元'}}</div>
                    </div>

                </template>
            </el-table-column>
            <el-table-column align="center" prop="hosp_appr_flag" width="100" label="医院审批标志">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.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>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="remark" width="50" label="备注">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" :title="scope.row.remark" placeholder=""></el-input>
                </template>
            </el-table-column>
            <el-table-column align="center" width="40" prop="name" label="操作">
                <template slot-scope="scope">
                    <i class="el-icon-delete" @click="deleteDrug(scope.$index, scope.row)"></i>
                </template>
            </el-table-column>
        </el-table>

        <el-table v-if="activeType == 2" :data="prescription.project" border style="width: 99%;"
                  :row-style="{ color: '#303133' }"
                  :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}" highlight-current-row>
            <el-table-column align="center" type="index" width="40" label="序号"></el-table-column>
            <el-table-column align="center" prop="project_name" label="名称">
                <template slot-scope="scope"><span :title="scope.row.project_name">{{ scope.row.project_name }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="statistical_classification" width="100" label="组">
                <template slot-scope="scope">{{scope.row.statistical_classification}}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="single_dose" width="80" label="单次用量">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.single_dose" @input="getProjectSingleDose(scope)"
                                  placeholder=""></el-input>
                        <div>{{scope.row.unit}}</div>
                    </div>

                </template>
            </el-table-column>
            <el-table-column align="center" prop="delivery_way" width="80" label="用法">
                <template slot-scope="scope">
                    <el-autocomplete
                            style="width:100%;"
                            class="inline-input"
                            v-model="scope.row.delivery_way"
                            :fetch-suggestions="querySearch2"
                            placeholder="请输入内容"
                    ></el-autocomplete>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="execution_frequency" width="80" label="频率">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.execution_frequency" @input="getProjectSingleDose(scope)"
                              placeholder=""></el-input>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="number_days" width="70" label="天数">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.number_days" @input="getProjectSingleDose(scope)"
                                  placeholder=""></el-input>
                        <div>{{'天'}}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="total" width="70" label="总量">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.total" style="width:60%" placeholder=""></el-input>
                        <div>{{scope.row.unit}}</div>

                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="name" width="70" label="单价">
                <template slot-scope="scope">
                    <div style="display:flex;align-items:center;">
                        <el-input v-model="scope.row.price" placeholder="" readonly></el-input>
                        <div>{{'元'}}</div>
                    </div>

                </template>
            </el-table-column>
            <el-table-column align="center" prop="name" width="50" label="备注">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" :title="scope.row.remark"></el-input>
                </template>
            </el-table-column>
            <el-table-column align="center" width="40" prop="name" label="操作">
                <template slot-scope="scope">
                    <i class="el-icon-delete" @click="deleteProject(scope.row,scope.$index)"></i>
                </template>
            </el-table-column>
        </el-table>

        <div class="additionalBox">
            <div class="additionalOne" v-for="(item,index) in prescription.addition" :key="index">
                <span :title="item.item_name">{{item.item_name}}</span>
                <el-input v-model="item.price" placeholder="" style="width:50px;"></el-input>
                共
                <el-input v-model="item.count" placeholder="" style="width:50px;"></el-input>
                次
                <i class="el-icon-delete deleteIcon" @click="delAddition(index,item)"></i>
            </div>
        </div>


    </div>
</template>

<script>
  import { getDictionaryDataConfig } from '@/utils/data'
  import { delHisAddition, delHisAdvice, delHisProject, getInitData,getHisDoctorAdviceInfo } from '@/api/his/his'

  export default {
    props: {
      preDrugs: Array,
      activeType: Number,
      addtions_charge: Array,
      prescription: {
        type: Object,
        default: function() {
          return {
            name: '',
            advices: [],
            project: [],
            drugways: [],
            efs: [],
            drugList:[],
            adviceList:{}
          }
        }
      }
    },
    data() {
      return {
        advices: [],
        tableData: [],
        newoptions: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }],
        value: '1',
        input: 1,
        efs: [],
        drugways: []
      }
    },

    methods: {
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      querySearch2(queryString, cb) {
        var restaurants = this.getDictionaryDataConfig('system', 'project_use')
        restaurants.map(item => {
          item.value = item.name
        })
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      delAddition(index, addition) {
        if (this.prescription.order_status == 2 || this.prescription.order_status == 5) {
          this.$message.error('该处方已经结算或记账，无法删除')
          return
        }
        this.$confirm('附加费删除后不可恢复，是否确认删除', '删除', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning'
        }).then(() => {
          this.$nextTick(function() {
            if (addition.id == 0) {
              this.prescription.addition.splice(index, 1)
            } else {
              let params = {
                'id': addition.id
              }
              delHisAddition(params).then(response => {
                if (response.data.state == 0) {
                  this.$message.error(response.data.msg)
                  return false
                } else {
                  var temp2 = this.deepClone(this.prescription.addition)
                  temp2.splice(index, 1)
                  this.prescription.addition = temp2
                  this.$message.success(response.data.data.msg)
                }
              })
            }
          })

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

      },
      getInitData() {
        getInitData().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.drugways = response.data.data.drugways
            this.efs = response.data.data.efs
            this.drugList = response.data.data.drugs
          }
        })

      }, deleteDrug: function(index, row) {
        if (this.prescription.order_status == 2 ||  this.prescription.order_status ==5) {
          this.$message.error('该处方已经结算或记账，无法删除')
          return
        }
        this.$confirm('药品删除后不可恢复，是否确认删除', '删除', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning'
        }).then(() => {
          this.$nextTick(function() {
            if (row.advice_id == 0) {
              this.prescription.advices.splice(index, 1)
            } else {
              let params = {
                'id': row.advice_id
              }
              delHisAdvice(params).then(response => {
                if (response.data.state == 0) {
                  this.$message.error(response.data.msg)
                  return false
                } else {
                  var temp2 = this.deepClone(this.prescription.advices)
                  temp2.splice(index, 1)
                  this.prescription.advices = temp2
                  this.$message.success(response.data.data.msg)
                }
              })

            }

          })

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

      }, deepClone(source) {
        if (!source && typeof source !== 'object') {
          throw new Error('error arguments', 'shallowClone')
        }
        const targetObj = source.constructor === Array ? [] : {}
        Object.keys(source).forEach((keys) => {
          if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = this.deepClone(source[keys])
          } else {
            targetObj[keys] = source[keys]
          }
        })
        return targetObj
      },

      setNewData: function(data) {
        this.prescription = data

        // this.prescription.advices = data.advices
      },
      getDictionaryDataConfig(module, filed_name) {
        return getDictionaryDataConfig(module, filed_name)
      },
      getGroup(id) {
        var name = ''
        var statistics_category = getDictionaryDataConfig('system', 'statistics_category')
        // console.log('2235', statistics_category)
        for (let i = 0; i < statistics_category.length; i++) {
          if (id == statistics_category[i].id) {
            name = statistics_category[i].name
          }
        }
        return name
      },
      deleteProject(row, i) {
        if (this.prescription.order_status == 2  || this.prescription.order_status == 5) {
          this.$message.error('该处方已经结算或记账，无法删除')
          return
        }
        this.$confirm('项目删除后不可恢复，是否确认删除', '删除', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning'
        }).then(() => {
          if (row.id == 0) {
            this.prescription.project.splice(i, 1)

          } else {
            let params = {
              'id': row.id
            }
            delHisProject(params).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                for (let i = 0; i < this.prescription.project.length; i++) {
                  if (this.prescription.project[i].id == row.id) {
                    this.prescription.project.splice(i, 1)
                  }
                }
                this.$message.success(response.data.data.msg)
              }
            })
          }
        })
          .catch(() => {
          })

      },
      getAllChange(scope) {
        if (scope.row.drug.min_unit == scope.row.single_dose_unit) {
          if (scope.row.prescribing_number_unit == scope.row.drug.min_unit) {
            console.log(1)
            scope.row.prescribing_number = scope.row.single_dose * (scope.row.execution_frequency ? this.getNum(scope.row.execution_frequency) : 1) * (scope.row.day ? scope.row.day : 1)
          } else {
            console.log(12)
            scope.row.prescribing_number = Math.ceil((scope.row.single_dose * (scope.row.execution_frequency ? this.getNum(scope.row.execution_frequency) : 1)) * (scope.row.day ? scope.row.day : 1) / scope.row.drug.min_number)
          }
        } else {
          if (scope.row.prescribing_number_unit == scope.row.drug.min_unit) {
            console.log(123)
            scope.row.prescribing_number = Math.ceil((scope.row.single_dose * (scope.row.execution_frequency ? this.getNum(scope.row.execution_frequency) : 1) * (scope.row.day ? scope.row.day : 1)) / scope.row.drug.dose)
          } else {
            console.log(1234)
            scope.row.prescribing_number = Math.ceil((scope.row.single_dose * (scope.row.execution_frequency ? this.getNum(scope.row.execution_frequency) : 1) * (scope.row.day ? scope.row.day : 1)) / scope.row.drug.dose / scope.row.drug.min_number)
          }
        }
        if (scope.row.prescribing_number == 0) {
          scope.row.prescribing_number = 1
        }
        if (scope.row.prescribing_number_unit == scope.row.drug.min_unit) {
          // scope.row.retail_price = scope.row.drug.min_number / scope.row.retail_price
          if (scope.row.prescribing_number > scope.row.drug.total) {
            this.$message.error(scope.row.drug_name + '库存不足')
          }
        } else {
          if ((parseInt(scope.row.prescribing_number) * scope.row.drug.min_number) > scope.row.drug.total) {
            this.$message.error(scope.row.drug_name + '库存不足')
          }
          // scope.row.retail_price = scope.row.drug.retail_price * scope.row.prescribing_number
        }

      },
      getPrescribingNumberUnit(scope) {

         console.log('scope',scope)
        // if(scope.row.drug.min_unit == scope.row.single_dose_unit){
        //   if(scope.row.prescribing_number_unit == scope.row.drug.min_unit){
        //     scope.row.prescribing_number = scope.row.single_dose * this.getNum(scope.row.execution_frequency) * scope.row.day
        //   }else{
        //     scope.row.prescribing_number = Math.ceil((scope.row.single_dose * this.getNum(scope.row.execution_frequency)) * scope.row.day / scope.row.drug.min_number)
        //   }
        // }else{
        //   if(scope.row.prescribing_number_unit == scope.row.drug.min_unit){
        //     scope.row.prescribing_number = Math.ceil((scope.row.single_dose * this.getNum(scope.row.execution_frequency) * scope.row.day) / scope.row.drug.dose)
        //   }else{
        //     scope.row.prescribing_number = Math.ceil((scope.row.single_dose * this.getNum(scope.row.execution_frequency) * scope.row.day) / scope.row.drug.dose / scope.row.drug.min_number)
        //   }
        // }
        // if(scope.row.prescribing_number == 0){
        //   scope.row.prescribing_number = 1
        // }
        if (scope.row.prescribing_number_unit == scope.row.drug.min_unit) {
          scope.row.retail_price = scope.row.drug.min_price
          // if (scope.row.prescribing_number > scope.row.drug.total) {
          //   this.$message.error(scope.row.drug_name + '库存不足')
          // }
        } else {
          // if ((parseInt(scope.row.prescribing_number) * scope.row.drug.min_number) > scope.row.drug.total) {
          //   this.$message.error(scope.row.drug_name + '库存不足')
          // }
          scope.row.retail_price = scope.row.drug.retail_price
        }
      },
      changePrescribingNumber(scope) {
        //  var max_number = 0
        //  if(scope.row.prescribing_number_unit == scope.row.drug.max_unit){
        //     max_number = parseInt(scope.row.prescribing_number) * scope.row.drug.min_number
        //  }
        //  if(scope.row.prescribing_number_unit == scope.row.drug.min_unit){
        //    max_number = parseInt(scope.row.prescribing_number)
        //  }
        //  console.log("修改的数量",max_number)
        //  //查询该药品库存
        //  if(this.drugList.length > 0){
        //     var stock_number = 0
        //     for(let i=0;i<this.drugList.length;i++){
        //       if(scope.row.id == this.drugList[i].id){
        //          for(let j=0;j<this.drugList[i].stock_in.length;j++){
        //             stock_number += this.drugList[i].stock_in[j].stock_max_number * this.drugList[i].min_number + this.drugList[i].stock_in[j].stock_min_number
        //          }
        //       }
        //     }
        //     console.log("库存数量",stock_number)
        //  }
        // if(scope.row.advice_id > 0){
        //   //获取该药品上一次出库的的数量
        //   getHisDoctorAdviceInfo(scope.row.advice_id).then(response=>{
        //     if(response.data.state == 1){
        //        var out_count  = 0
        //        var adviceList = response.data.data.advice
        //        if(adviceList.prescribing_number_unit == adviceList.drug.max_number){
        //            out_count = adviceList.prescribing_number * adviceList.drug.min_number
        //        }
        //        if(adviceList.prescribing_number_unit == adviceList.drug.min_unit){
        //           out_count = adviceList.prescribing_number
        //        }

        //        //如果更改的数量大于修改之前的数量
        //        if(max_number > out_count){
        //          if((max_number - out_count)>stock_number){
        //            this.$message.error(scope.row.drug_name + '库存不足')
        //          }
        //        }
        //     }
        //   })
        // }

        // if(scope.row.advice_id == 0){
        //    if(max_number > stock_number){
        //     this.$message.error(scope.row.drug_name + '库存不足')
        //    }
        // }


        if (scope.row.prescribing_number_unit == scope.row.drug.min_unit) {
          if (parseInt(scope.row.prescribing_number) > scope.row.drug.total) {
            this.$message.error(scope.row.drug_name + '库存不足')
          }
        } else {
          if ((parseInt(scope.row.prescribing_number) * scope.row.drug.min_number) > scope.row.drug.total) {
            this.$message.error(scope.row.drug_name + '库存不足')
          }
        }
      },
      getProjectSingleDose(scope) {
        this.prescription.project[scope.$index].total = scope.row.single_dose * (scope.row.execution_frequency ? this.getNum(scope.row.execution_frequency) : 1) * (scope.row.number_days ? scope.row.number_days : 1)
        if (this.prescription.project[scope.$index].total == 0) {
          this.prescription.project[scope.$index].total = 1
        }
      },
      getProjectDay(scope) {
        this.prescription.project[scope.$index].total = scope.row.single_dose * scope.row.number_days
        if (this.prescription.project[scope.$index].total == 0) {
          this.prescription.project[scope.$index].total = 1
        }

      },
      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
      },

    }, mounted() {
      this.getInitData()

    },
    watch: {
      'prescription.advices': {
        handler(newVal, oldVal) {

        },
        deep: true
      }
      // "prescription.project":{
      //   handler(newVal,oldVal){
      //     newVal.map((item,index) => {
      //       if(item.single_dose != oldVal[index].single_dose || item.number_days != oldVal[index].number_days){
      //         item.total = item.single_dose * item.number_days
      //       }

      //     })
      //   },
      //   deep:true
      // }
    }

  }
</script>

<style lang="scss">
    .prescriptionTable {

    .el-input__inner {
        padding: 0 5px;
    }

    .additionalBox {
        margin-top: 20px;
        display: flex;
        flex-wrap: wrap;

    .additionalOne {
        margin-right: 20px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;

    > span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 80px;
        display: inline-block;
        font-size: 14px;
    }

    }
    .deleteIcon {
        color: red;
        margin-left: 5px;
    }

    }
    .el-table th .cell, .el-table td .cell {
        padding: 0 2px;
        white-space: pre-line;
    }

    .el-icon-delete {
        color: red;
    }

    }
</style>
