<script>
import dayjs from 'dayjs';
import {listMedicalMechanism} from '@/api/medical/mechanism';
import {transformFlatObjectToNested, transformNestedObjectToFlat} from '@/tools/object';
import {bignumber, chain, multiply} from 'mathjs';
import {
  addPrescriptionCore2,
  check2,
  getPrescriptionReception,
  setPrescriptionReception,
} from '@/api/prescription/prescriptionCore';
import {mapGetters} from 'vuex';

import regionOptions from '@/utils/options';
import {getSchemeList} from '@/api/decoct/scheme';


export default {
  props: {
    id: {type: [String, Number]},
    mode: {type: String, default: 'edit'},
    editable: {type: Boolean, default: true},
  },
  data() {
    const locationValidator = (message) => (rule, value, callback) => {
      if (this.model.expressExecutor === '顺丰') {
        if (!value.length) { return callback(new Error(message)); }
      }
      callback();
    };
    return {
      medicines: [],
      model: {},
      rules: {
        yljgId: [{required: true, message: '请选择医疗机构'}],
        yfId: [{required: true, message: '请选择药房'}],
        preNo: [{required: true, message: '请输入医院处方号'}],
        name: [{required: true, message: '请输入患者姓名'}],
        sex: [{required: true, message: '请选择性别'}],
        age: [{required: true, message: '请输入年龄'}],
        // recipientTel: [{required: true, message: '请输入联系电话'}],
        expressExecutor: [{required: true, message: '请选择配送方式'}],
        consignee: [{validator: locationValidator('请输入收件电话')}],
        contactNumber: [{validator: locationValidator('请输入收件电话')}],
        // location: [{validator: locationValidator('请选择所属地域')}],
        address: [{required: true, message: '请输入详细地址'}],
      },

      ageOptions: [
        {label: '岁', value: '岁'},
        {label: '月', value: '月'},
        {label: '周', value: '周'},
        {label: '天', value: '天'},
      ],
      genderOptions: [
        {label: '男', value: '男'},
        {label: '女', value: '女'},
      ],
      recipeCategoryOptions: [
        {label: '门诊', value: '1'},
        {label: '住院', value: '2'},
      ],
      expressExecutorOptions: [
        {label: '送医院', value: '送医院'},
        {label: '顺丰', value: '顺丰'},
        {label: '其他', value: '其他'},
      ],
      whetherOptions: [
        {label: '是', value: '1'},
        {label: '否', value: '0'},
      ],
      communityOptions: [],
      mechanismOptions: [],
      dosageFormOptions: [],
      usageOptions: [],
      concentrationOptions: [],
      frequencyOptions: [],
      medicationTimeOptions: [],
      expressDechOptions: [],
      expressPayTypeOptions: [],
      schemeOptions: [],
      patternOptions: [],
      regionOptions,
      showPharmacy: false,
      searchTableForSystemColumns: [
        {title: '名称', data: 'drugsName'},
        // {title: '编码', data: 'drugsId'},
        // {title: '规格', data: 'drugsSpecsName'},
        // {title: '产地', data: 'placeName'},
        // {title: '零售价', data: 'retail'},
      ],
      loading: false,
      saving: false,

      tableHeight: 0,
    };
  },
  computed: {
    ...mapGetters(['pharmacyList']),
    isCheck() { return this.$props.mode === 'check';},
    isReception() { return this.$props.mode === 'reception';},
    getEmptyMedicineRowIndex() {
      return this.medicines.findIndex(medicine => Object.keys(medicine).length === 0);
    },
    medicineTotal() {
      return this.medicines.filter(medicine => medicine && medicine.matCode).length;
    },
    medicineDosageTotal() {
      let total = chain(bignumber(0));
      for (const medicine of this.medicines) {
        if (medicine['matDose']) total = total.add(bignumber(medicine['matDose']));
      }
      return total.done().toFixed(2);
    },
    medicineWholesalePriceTotal() {
      let total = chain(bignumber(0));
      for (const medicine of this.medicines) {
        if (medicine['matDose'] && medicine['matPfj']) total = total.add(multiply(
          bignumber(medicine['matDose']),
          bignumber(medicine['matPfj']),
        ));
      }
      return total.done().toFixed(2);
    },
    medicinePriceTotal() {
      let total = chain(bignumber(0));
      for (const medicine of this.medicines) {
        if (medicine['matDose'] && medicine['matXsj']) total = total.add(multiply(
          bignumber(medicine['matDose']),
          bignumber(medicine['matXsj']),
        ));
      }
      return total.done().toFixed(2);
    },
  },
  created() {
    if (this.$props.id) this.load();
    else this.formReset();
    this.getMechanismList();
    this.getDicts('dosage_form').then((response) => {this.dosageFormOptions = response.data;});
    this.getDicts('pressure_pattern').then((response) => {this.patternOptions = response.data;});
    this.getDicts('prescription.prescriptionUsage').then((response) => {this.usageOptions = response.data;});
    this.getDicts('prescription.concentration').then((response) => {this.concentrationOptions = response.data;});
    this.getDicts('prescription.frequency').then((response) => {this.frequencyOptions = response.data;});
    this.getDicts('prescription.medicationTime').then((response) => {this.medicationTimeOptions = response.data;});
    this.getDicts('expressDech').then((response) => {this.expressDechOptions = response.data;});
    this.getDicts('expressPayType').then((response) => {this.expressPayTypeOptions = response.data;});
    getSchemeList().then((response) => {this.schemeOptions = response.rows;});
  },
  mounted() {
    const rect = this.$el.getBoundingClientRect();
    this.tableHeight = rect.height - /* 内边距 */ 12 * 2 - /* 协定方 */ 32 - /* 表尾 */ (this.editable ? 20 : 0) - 12 * 2 - /* 拒绝原因 */ (this.isCheck ? 54 + 12 : 0) - /* 底部按钮 */ (36 + 12);
  },
  methods: {
    async load() {
      this.loading = true;
      try {
        const {medicines, ...model} = await getPrescriptionReception(this.$props.id);
        this.medicines = medicines.map(medicine => Object.assign(medicine, {subtotalMoney: this.calculationMedicinePrice(medicine)}));
        this.model = transformNestedObjectToFlat(model);
        if (this.editable && !this.isCheck) {
          this.model.id = null;
          this.model.tackleTime = '';
        }
        if (!this.model.id) this.model.id = this.$props.id;
      } catch (e) {
        this.cancel();
      }
      this.loading = false;
      if (this.editable) this.appendMedicine();
      const pharmacies = Array.isArray(this.pharmacyList) ? this.pharmacyList : [];
      this.showPharmacy = pharmacies.length > 1 || !this.model.yfId;

      if (this.editable && !this.model.tackleTime) this.model.tackleTime = dayjs().startOf('minute').format('YYYY-MM-DD HH:mm:ss');

      if (!this.editable) {
        this.showPharmacy = false;
        this.rules = {};
      }
    },
    formReset() {
      const pharmacies = Array.isArray(this.pharmacyList) ? this.pharmacyList : [];
      this.model = {
        yfId: window.localStorage.getItem('pharmacyId') || (pharmacies.length ? pharmacies[0].id : ''),
        /* 01 受理时间 */ tackleTime: dayjs().startOf('minute').format('YYYY-MM-DD HH:mm:ss'),
        /* 02 处方序号 */ recipeSerial: '',
        /* 03 处方编号 */ recipeBh: '',
        /* 04 患者姓名 */ name: '',
        /* 05 患者年龄 */ // age: '',
        /* 07 患者性别 */ sex: '',
        /* 08 联系电话 */ recipientTel: '',
        /* 09 医院处方 */ preNo: '',
        /* 10 医疗机构 */ yljgId: '',
        /* 11 门诊住院 */ preMzZy: '',
        /* 12 就诊科室 */ department: '',
        /* 13 病区     */ inpatientArea: '',
        /* 14 病床     */ bedNo: '',
        /* 15 就诊医生 */ doctor: '',
        /* 16 临床诊断 */ disName: '',
        /* 17 剂数     */ // prescription_number: '',
        /* 18 剂型     */ prescription_dosageForm: '',
        /* 19 处方用法 */ prescription_prescriptionUsage: '',
        /* 20 浓煎量   */ prescription_concentration: '',
        /* 21 服药频次 */ prescription_frequency: '',
        /* 22 服药时间 */ prescription_medicationTime: '',
        /* 23 医嘱     */ prescription_remark: '',
        /* 24 代煎     */ isBehalf: '',
        /* 24 配送     */ takingMethod: '',

        /* 26 配送方式 */ expressExecutor: '',
        /* 27 收件人名 */ consignee: '',
        /* 28 收件电话 */ contactNumber: '',
        location: [],
        /* 29 收件地址 */ address: '',
        /* 30 快递单号 */ expressCode: '',
        /*            */ expressDech: '',
        /*            */ expressPayType: '',
        /*    用药时间 */ expressTime: dayjs().startOf('minute').format('YYYY-MM-DD HH:mm'),

        /*    批发费用 */ // prescription_prescriptionPfSum: '',
        /*    含税金额 */ // prescription_prescriptionYsSum: '',
        /* 31 处方金额 */ // prescription_prescriptionSum: '',
        /* 32 代煎费用 */ // prescription_daijianCost: '',
        /* 33 配送费用 */ // prescription_distributionCost: '',
        /* 34 总金额 */ // prescription_prescriptionTotleSum: '',

        /*    浸泡水量 */ // steep_soakingWaterValue: '',
        /*    浸泡时间 */ // steep_soakingTime: '',
        /*    是否毒性 */ decoct_isPoison: '',
        /*    煎煮方案 */ decoct_schemeId: '',
        /*    煎煮剂型 */ decoct_dosageForm: '',
        /*    压力模式 */ decoct_pressurePattern: '',
        /*    煎煮时间 */ // decoct_decoctTime: '',
        /*    先煎时间 */ // decoct_preDecoctTime: '',
        /*    一煎时间 */ // decoct_firstDecoctTime: '',
        /*    二煎时间 */ // decoct_secondDecoctTime: '',
        /*    后下时间 */ // decoct_backDownTime: '',
        /*    包数     */ // pack_packageNumber: '',
        /*    包装量   */ // pack_packageDose: '',

        /* 审核理由 */
        remarks: '',
        thread: '',
      };
      this.appendMedicine();
      this.showPharmacy = pharmacies.length > 1 || !this.model.yfId;
    },
    /** 查询医疗机构列表 */
    async getMechanismList() {
      try {
        const {data: rows} = await listMedicalMechanism();
        this.mechanismOptions = rows.map(item => (item.disabled = item.state === '0', item));
      } catch (error) {
        this.mechanismOptions = [];
        this.model.yljgId = '';
      }
    },
    async handle() {
      try {
        await this.$refs.form.validate();
        const medicines = this.medicines.filter(medicine => Object.keys(medicine).length);
        if (medicines.length === 0) throw '请至少添加一味药品';
        if (medicines.find(medicine => !medicine.matDose)) throw '请补全药品剂量';

        const model = transformFlatObjectToNested(this.model);
        model['prescription'].drugs = medicines;
        model['prescription'].prescriptionPfSum = +this.medicineWholesalePriceTotal;
        model['prescription'].prescriptionYsSum = +this.medicineWholesalePriceTotal;
        model['prescription'].prescriptionSum = +this.medicinePriceTotal;

        [model.province = '', model.city = '', model.region = ''] = this.model.location;
        delete model['location'];

        if (model.steep == null) model.steep = null;
        if (model.decoct == null) model.decoct = null;
        if (model.pack == null) model.pack = null;

        this.saving = true;
        if (this.isCheck) await check2(model);
        else await addPrescriptionCore2(model);
        this.$emit('close', true);
      } catch (e) {
        if (e === false) this.$message.warning('请补全表单数据');
        else if (typeof e === 'string') this.$message.warning(e);
      }
      this.saving = false;
    },
    async reception() {
      try {
        await setPrescriptionReception(this.model);
        this.$message.success(`接收成功`);
        this.$emit('close', true);
      } catch (e) {

      }
    },
    async check(mode) {
      this.model.thread = mode;
      this.model.checkState = {110: '1', 120: '2'}[mode];
      await this.handle();
    },
    cancel() {
      this.$emit('close', false);
    },
    updateValidator(validators) {
      this.$refs.form.clearValidate(validators);
      this.$refs.form.validateField(validators);
    },
    updateJDModel(id) {
      const model = this.schemeOptions.find(scheme => scheme.id === id) || {};
      this.model.decoct_pressurePattern = model.pressurePattern;
      this.model.decoct_dosageForm = model.dosageForm;
      const keys = ['decoctTime', 'firstDecoctTime', 'secondDecoctTime', 'preDecoctTime', 'backDownTime'];
      for (const key of keys) {
        if (model[key]) this.model[`decoct_${key}`] = model[key];
        else delete model[`decoct_${key}`];
      }
    },
    searchMedicinesFormat(res) {
      try {
        if (res.rows) return {totalRow: res.total, list: res.rows};
        else return {totalRow: res.data.length, list: res.data};
      } catch (error) { return {totalRow: 0, list: []}; }
    },
    selectMedicine([value], row, index) {
      if (value) {
        row.matCode = value.drugsId;
        row.matName = value.drugsName;
        row.drugsSpecsName = value.drugsSpecsName;
        row.matUsageName = value.matUsageName;
        // row.matDose = '';
        row.matUnitName = value.dosageSizeUnit;
        row.matXsj = value.retail;
        row.matPfj = value.matPfj;
        row.subtotalMoney = this.calculationMedicinePrice(row);
      } else {
        delete row.matCode;
        delete row.matName;
        delete row.drugsSpecsName;
        delete row.matUsageName;
        delete row.matDose;
        delete row.matUnitName;
        delete row.matXsj;
        delete row.matPfj;
        this.medicines.splice(index, 1, row);
      }
      if (this.getEmptyMedicineRowIndex === -1) this.appendMedicine({}, index + 1);
    },
    appendMedicine(model, index = this.medicines.length) {
      this.medicines.splice(index, 0, model || {});
    },
    deleteMedicine(row, index) {
      this.medicines.splice(index, 1);
    },
    updateMedicine(row, index) {
      this.medicines.splice(index, 1, {...row, subtotalMoney: this.calculationMedicinePrice(row)});
    },
    calculationMedicinePrice(medicine) {
      let price = chain(bignumber(medicine.matXsj || 0));
      return price.multiply(bignumber(medicine.matDose || 0)).value.valueOf();
    },
    medicinesCellSpan({row, column, rowIndex, columnIndex}) {
      if (columnIndex >= 2 && !(row && row.matCode)) return {
        rowspan: 1,
        colspan: 8,
      };
    },
  },
};
</script>

<template>
  <el-form v-loading="loading" class="wrapper" :class="{editable}" ref="form"
           :model="model" :rules="rules" label-position="right" label-width="auto"
  >
    <el-row :gutter="20">
      <el-col class="col-container" :span="12">
        <div class="row">
          <div class="title-container">医疗机构信息</div>
          <el-row class="form-container" :gutter="8">
            <el-col :span="8">
              <el-form-item label="医疗机构" prop="yljgId">
                <el-select v-model="model.yljgId" placeholder="医疗机构" clearable :disabled="!editable">
                  <el-option v-for="item in mechanismOptions" :key="item.code" :value="item.code" :label="item.name"
                             :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门诊住院" prop="preMzZy">
                <el-select v-model="model.preMzZy" placeholder="" clearable :disabled="!editable">
                  <el-option v-for="item in recipeCategoryOptions" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编号" prop="recipeBh">
                <el-input v-model="model.recipeBh" placeholder="编号" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受理时间" prop="tackleTime">
                <el-date-picker v-model="model.tackleTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="受理时间" :disabled="!editable"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处方号" prop="preNo">
                <el-input v-model="model.preNo" placeholder="处方号" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="序号" prop="recipeSerial">
                <el-input v-model="model.recipeSerial" placeholder="序号" :disabled="!editable"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="row">
          <div class="title-container">就诊信息</div>
          <el-row class="form-container" :gutter="8">
            <el-col :span="8">
              <el-form-item label="患者姓名" prop="name">
                <el-input v-model="model.name" placeholder="患者姓名" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="4em" label="年龄" prop="age">
                <div style="display: flex">
                  <el-input-number v-model="model.age" :controls="false" controls-position="right"
                                   :min="0" placeholder="" :disabled="!editable"
                  ></el-input-number>
                </div>
              </el-form-item>
              <el-form-item label-width="4em" label="性别" prop="sex">
                <el-select v-model="model.sex" placeholder="" clearable :disabled="!editable">
                  <el-option v-for="item in genderOptions" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电话" prop="recipientTel">
                <el-input type="tel" v-model="model.recipientTel" placeholder="电话" minlength="11"
                          maxlength="11" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="就诊科室" prop="department">
                <el-input v-model="model.department" placeholder="就诊科室" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="病区" prop="inpatientArea">
                <el-input v-model="model.inpatientArea" placeholder="病区" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="病床" prop="bedNo">
                <el-input v-model="model.bedNo" placeholder="病床" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="临床诊断" prop="disName">
                <el-input v-model="model.disName" placeholder="临床诊断" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="医生" prop="doctor">
                <el-input v-model="model.doctor" placeholder="医生" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="医院金额" prop="prescription_prescriptionTotleSum">
                <el-input-number class="full" v-model="model.prescription_prescriptionTotleSum" :controls="false"
                                 :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代煎费" prop="prescription_daijianCost">
                <el-input-number class="full" v-model="model.prescription_daijianCost" :controls="false"
                                 :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="配送费" prop="prescription_distributionCost">
                <el-input-number class="full" v-model="model.prescription_distributionCost" :controls="false"
                                 :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="row">
          <div class="title-container">处方信息</div>
          <el-row class="form-container" :gutter="8">
            <el-col :span="8">
              <el-form-item label-width="3em" label="剂型" prop="prescription_dosageForm">
                <el-select v-model="model.prescription_dosageForm" placeholder="" clearable :disabled="!editable">
                  <el-option v-for="item in dosageFormOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="3em" label="用法" prop="prescription_prescriptionUsage">
                <el-select v-model="model.prescription_prescriptionUsage" placeholder="" clearable
                           :disabled="!editable">
                  <el-option v-for="item in usageOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="3em" label="剂数" prop="prescription_number">
                <el-input-number v-model="model.prescription_number" :controls="false" controls-position="right"
                                 :min="0" placeholder="" :disabled="!editable"
                ></el-input-number>
              </el-form-item>
              <el-form-item label-width="3em" label="包数" prop="pack_packageNumber">
                <el-input-number v-model="model.pack_packageNumber" :controls="false" controls-position="right"
                                 :min="0" placeholder="" :disabled="!editable"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装量" prop="pack_packageDose">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.pack_packageDose" :controls="false"
                                   :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">ml</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="3em" label="代煎" prop="isBehalf">
                <el-select v-model="model.isBehalf" placeholder="是 / 否" clearable :disabled="!editable">
                  <el-option v-for="item in whetherOptions" :key="item.value"
                             :label="item.label" :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="3em" label="配送" prop="takingMethod">
                <el-select v-model="model.takingMethod" placeholder="是 / 否" clearable :disabled="!editable">
                  <el-option label="是" :value="'配送'"></el-option>
                  <el-option label="否" :value="'自提'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="服药频次" prop="prescription_frequency">
                <el-select v-model="model.prescription_frequency" placeholder="服药频次" clearable
                           :disabled="!editable">
                  <el-option v-for="item in frequencyOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="服药时间" prop="prescription_medicationTime">
                <el-select v-model="model.prescription_medicationTime" placeholder="服药时间" clearable
                           :disabled="!editable">
                  <el-option v-for="item in medicationTimeOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showPharmacy" :span="8">
              <el-form-item label="药房" prop="yfId">
                <el-select v-model="model.yfId" placeholder="药房" clearable :disabled="!editable">
                  <el-option v-for="item in pharmacyList" :key="item.id" :label="item.name" :value="item.id"
                             :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="showPharmacy ? 16 : 24">
              <el-form-item label-width="3em" label="医嘱" prop="prescription_remark">
                <el-input v-model="model.prescription_remark" placeholder="医嘱" :disabled="!editable"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="row">
          <div class="title-container">配送信息</div>
          <el-row class="form-container" :gutter="8">
            <el-col :span="8">
              <el-form-item label="配送方式" prop="expressExecutor">
                <el-select v-model="model.expressExecutor" placeholder="配送方式" clearable :disabled="!editable"
                           @change="updateValidator(['consignee', 'contactNumber', 'location', 'address'])">
                  <el-option v-for="item in expressExecutorOptions" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收件人" prop="consignee">
                <el-input v-model="model.consignee" placeholder="收件人" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收件电话" prop="contactNumber">
                <el-input type="tel" v-model="model.contactNumber" placeholder="收件电话" minlength="11"
                          maxlength="11" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="收件地址" prop="location">
                <el-cascader v-model="model.location" :options="regionOptions" :props="{ value: 'label' }"
                             placeholder="省/市/区" clearable :disabled="!editable"></el-cascader>
              </el-form-item>
              <el-form-item label-width="4px" prop="address">
                <el-input v-model="model.address" placeholder="详细地址" :disabled="!editable"/>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item style="flex-basis: 70%;" label="快递单号" prop="expressCode">
                <el-input v-model="model.expressCode" placeholder="快递单号" :disabled="!editable"/>
              </el-form-item>
              <el-form-item style="flex-basis: 15%;" label-width="4px" label="" prop="expressDech">
                <el-select v-model="model.expressDech" placeholder="顺丰标快" clearable :disabled="!editable">
                  <el-option v-for="item in expressDechOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="flex-basis: 10%;" label-width="4px" label="" prop="expressPayType">
                <el-select v-model="model.expressPayType" placeholder="月结" clearable :disabled="!editable">
                  <el-option v-for="item in expressPayTypeOptions" :key="item.dictValue"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用药时间" prop="expressTime">
                <el-date-picker v-model="model.expressTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                                placeholder="用药时间" clearable :disabled="!editable"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="row">
          <div class="title-container">煎煮信息</div>
          <el-row class="form-container" :gutter="8">
            <el-col :span="8">
              <el-form-item label="是否毒性" prop="decoct_isPoison">
                <el-select v-model="model.decoct_isPoison" placeholder="" clearable :disabled="!editable">
                  <el-option label="是" :value="'1'"></el-option>
                  <el-option label="否" :value="'0'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="浸泡水量" prop="steep_soakingWaterValue">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.steep_soakingWaterValue" :controls="false"
                                   :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">ml</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="浸泡时间" prop="steep_soakingTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.steep_soakingTime" :controls="false"
                                   :precision="2" :step="1" :min="0" placeholder="" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="煎药方案" prop="decoct_schemeId">
                <el-select v-model="model.decoct_schemeId" placeholder="煎药方案" clearable :disabled="!editable"
                           @change="updateJDModel">
                  <el-option v-for="item in schemeOptions" :key="item.id"
                             :label="item.schemeName" :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="压力模式" prop="decoct_pressurePattern">
                <el-select v-model="model.decoct_pressurePattern" placeholder="压力模式" clearable
                           :disabled="!editable">
                  <el-option v-for="item in patternOptions" :key="item.dictCode"
                             :label="item.dictLabel" :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="煎煮时间" prop="decoct_decoctTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.decoct_decoctTime" :controls="false"
                                   :precision="2" :step="1" :min="0" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="先煎时间" prop="decoct_preDecoctTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.decoct_preDecoctTime" :controls="false"
                                   :precision="2" :step="1" :min="0" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一煎时间" prop="decoct_firstDecoctTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.decoct_firstDecoctTime" :controls="false"
                                   :precision="2" :step="1" :min="0" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二煎时间" prop="decoct_secondDecoctTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.decoct_secondDecoctTime" :controls="false"
                                   :precision="2" :step="1" :min="0" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="后下时间" prop="decoct_backDownTime">
                <div style="display: flex">
                  <el-input-number class="full" v-model="model.decoct_backDownTime" :controls="false"
                                   :precision="2" :step="1" :min="0" :disabled="!editable"
                  ></el-input-number>
                  <span style="flex: none; margin-left: 4px;">min</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col class="col-container" :span="12">
        <div class="area" style="flex: auto;display: flex;flex-direction: column;">
          <div style="flex: none;display: flex;justify-content: space-between;align-items: center;">
            <div style="display: flex;align-items: center;">
              <span style="flex: none">协定方：</span>
              <el-input :disabled="!editable"></el-input>
              <el-button style="margin-left: 8px;" type="primary" size="small" :disabled="!editable">添加</el-button>
            </div>
            <div>
              <span>合计 </span>
              <span style="font-weight: 700;">{{ medicineTotal }}</span>
              <span> 味药品，总重 </span>
              <span style="font-weight: 700;">{{ medicineDosageTotal }}</span>
            </div>
          </div>
          <div v-if="tableHeight" style="flex: auto;margin: 12px 0;">
            <el-table style="width: 100%;" :height="tableHeight" size="mini" :data="medicines"
                      :span-method="medicinesCellSpan">
              <el-table-column v-if="editable" label="" width="48" align="center" fixed>
                <template slot-scope="scope">
                  <el-button type="danger" icon="el-icon-close" circle size="mini"
                             :disabled="Object.keys(scope.row).length === 0 || saving"
                             @click="deleteMedicine(scope.row, scope.$index)"
                  ></el-button>
                </template>
              </el-table-column>
              <el-table-column label="序号" type="index" width="55" align="center" fixed></el-table-column>
              <el-table-column label="药品名称" prop="matName" min-width="120px" align="center">
                <template slot-scope="scope">
                  <template v-if="!scope.row.matCode && editable">
                    <v-selectpage :tb-columns="searchTableForSystemColumns"
                                  key-field="drugsId" v-model="scope.row.matCode"
                                  placeholder="药品名称" title="药品"
                                  data="drugsSearchForSystem" :params="{}" :pagination="false"
                                  :result-format="searchMedicinesFormat"
                                  @values="selectMedicine($event, scope.row, scope.$index)"
                    ></v-selectpage>
                  </template>
                  <a v-else>
                    {{ scope.row.matName }}
                    <i v-if="editable" class="icon el-icon-circle-close" @click="selectMedicine([], scope.row, scope.$index)"></i>
                  </a>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="drugsSpecsName" min-width="110px" align="center"></el-table-column>
              <el-table-column label="剂量" prop="matDose" width="110px" align="center">
                <template slot-scope="scope" v-if="scope.row.matCode">
                  <template v-if="editable">
                    <el-input-number style="width: 100%;" v-model="scope.row.matDose" :min="0" :precision="2"
                                     :controls="false"
                                     :disabled="saving" size="mini"
                                     @change="updateMedicine(scope.row, scope.$index)"></el-input-number>
                  </template>
                  <template v-else>{{ scope.row.matDose }}</template>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="matUnitName" align="center"></el-table-column>
              <el-table-column label="用法" prop="matUsageName" width="110px" align="center">
                <template slot-scope="scope" v-if="scope.row.matCode">
                  <template v-if="editable">
                    <el-input v-model="scope.row.matUsageName" :disabled="saving"
                              @input="updateMedicine(scope.row, scope.$index)"></el-input>
                  </template>
                  <template v-else>{{ scope.row.matUsageName }}</template>
                </template>
              </el-table-column>
              <el-table-column label="批发价" prop="matPfj" width="110" align="center"></el-table-column>
              <el-table-column label="零售价" prop="matXsj" width="110" align="center"></el-table-column>
              <el-table-column label="小计" prop="subtotalMoney" width="110" align="center"></el-table-column>
            </el-table>
          </div>
          <el-row v-if="editable" style="flex: none;" :gutter="8">
            <el-col :span="8" style="text-align: center;">
              <span>批发费用：</span>
              <span style="font-weight: 700;">{{ medicineWholesalePriceTotal }}</span>
            </el-col>
            <el-col :span="8" style="text-align: center;">
              <span>零售费用：</span>
              <span style="font-weight: 700;">{{ medicinePriceTotal }}</span>
            </el-col>
            <el-col :span="8" style="text-align: center;">
              <span>含税金额：</span>
              <span style="font-weight: 700;">{{ medicineWholesalePriceTotal }}</span>
            </el-col>
          </el-row>
        </div>


        <el-input v-if="isCheck" style="margin-top: 12px;" v-model="model.remarks" type="textarea"
                  placeholder="若审核拒绝，请输入原因"
                  :autosize="{ minRows: 2, maxRows: 2}">
        </el-input>
        <div class="footer">
          <div>
            <template v-if="isCheck">
              <div v-if="model.remarks">
                <el-button type="danger" @click="model.remarks && check('120')" :disabled="saving">审核拒绝</el-button>
              </div>
              <el-popconfirm v-else title="不通过理由未输入，确定现在提交？" icon="el-icon-info" icon-color="red"
                             @confirm="check('120')">
                <template slot="reference">
                  <el-button type="danger" :disabled="saving">审核拒绝</el-button>
                </template>
              </el-popconfirm>
            </template>
          </div>
          <div>
            <el-button v-if="isCheck" type="primary" @click="check('110')" :disabled="saving">审核通过</el-button>
            <el-button v-else-if="isReception" type="primary" :loading="saving" @click="reception">接 收</el-button>
            <el-button v-else-if="editable" type="primary" :loading="saving" @click="handle">保 存</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss">
.wrapper {
  display: flex;
  height: 100%;
  overflow: hidden;

  .col-container {
    display: flex;
    flex-direction: column;
    height: 100%;

    &:first-of-type {
      overflow: auto;
      //justify-content: space-between;
    }
  }

  &:not(.editable) ::v-deep {
    .el-input.is-disabled .el-input__inner {
      color: #606266;
    }

    .area,
    .row .form-container,
    .el-table tr {
      background-color: #f2f2f2;
    }

    .row .title-container,
    .el-table th {
      background-color: #d7d7d7;
    }
  }


  .row {
    display: flex;
    margin: 12px 0;

    &:first-of-type {
      margin-top: 0;
    }

    &:last-of-type {
      margin-bottom: 0;
    }

    .title-container {
      flex: none;
      display: flex;
      align-items: center;
      padding: 12px 6px;
      width: 2.8em;
      color: #fff;
      font-weight: 700;
      letter-spacing: 0.3em;
      line-height: 1.5em;
      text-align: right;
      box-sizing: content-box;
      background-color: #1DBFA7;
    }

    .form-container {
      flex: auto;
      padding: 12px 12px 0;
      background-color: #5AD8A6;

      .el-col {
        display: flex;

        > .el-form-item {
          flex: 1 0 50%;
          width: 100%;
        }
      }

      .el-form-item {
        margin-bottom: 12px;

        ::v-deep {
          .el-form-item__label {
            color: #000;
            padding-right: 6px;
          }

          .el-input__inner {
            padding-left: 6px;
            padding-right: 24px;
          }
        }

        .el-date-editor ::v-deep {
          .el-input__inner {
            padding-left: 28px;
          }
        }
      }
    }
  }

  .area {
    padding: 12px 6px;
    color: #000;
    background-color: #5AD8A6;
  }

  .el-table {
    ::v-deep {
      th {
        color: #000;
        background-color: #1DBFA7;
      }

      tr {
        color: #000;
        background-color: #D9EEE5;
      }
    }
  }
}

.el-input-number--medium {
  width: auto;

  &:not(.full) {
    width: min-content;
    min-width: 100px;
  }
}

.el-form, .el-input, .el-select, .el-cascader {
  width: 100%;
}

.footer {
  flex: none;
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
}
</style>
<style lang="scss">
.el-dialog {
  &.prescription-core-edit-container {
    overflow: hidden;
  }

  &__header {
    flex: none;
    padding: 12px 12px 0;
  }

  &__body {
    flex: auto;
    padding: 12px;

    > * {
      height: 100%;
    }
  }
}
</style>
