<template>
  <el-container style="width: 1100px;height: 500px;overflow: auto">
    <el-header style="height: 40px">
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="muBanZuJian = true">取模板</el-button>
      <el-button :disabled="mingXi.list.length === 0" type="success" @click="cunMuBan.dialog = true">存模板</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-button :disabled="mingXi.list.length === 0" type="success" @click="dianJiBaoCunCaoYao">保存数据</el-button>
      <cao-yao-cuo-wu-xin-xin :data="errorMsg"/>
    </el-header>
    <el-main>
      <el-form label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="处方名：">
              <el-input v-model="chuFang.orderName" style="width: 120px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="剂数：">
              <el-input-number v-model="chuFang.quantity" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="代煎：">
              <el-input-number v-model="chuFang.quantityDj" :max="chuFang.quantity" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="执行科室：">
              {{ huanZheXinXi.smallDeptName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="每日剂数：">
              <el-input-number v-model="chuFang.cyMtjs"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="类型：">
              <el-select v-model="chuFang.cyJssm" clearable filterable size="small" style="width: 120px">
                <el-option v-for="item in jiaShuiLeiXing" :key="item.code" :label="item.name"
                           :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加水量（ml）：">
              <el-input-number v-model="chuFang.cyJsl"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="煮取（ml）：">
              <el-input-number v-model="chuFang.cyZql"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="复煎：">
              <el-input-number v-model="chuFang.cyFj"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分几次：">
              <el-input-number v-model="chuFang.cyFfcs"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服用说明：">
              <el-select v-model="chuFang.cyFysm" clearable filterable size="small" style="width: 120px">
                <el-option v-for="item in fuYongFangFaShuJu" :key="item.code" :label="item.name" :value="item.code">
                  <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                  <el-divider direction="vertical"></el-divider>
                  <span>{{ item.name }}</span></el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="药房：">
              <el-switch
                  v-model="chuFang.groupNo"
                  active-color="#13ce66"
                  active-text="中药颗粒"
                  active-value="82"
                  inactive-color="#fbbd08"
                  inactive-text="草药"
                  inactive-value="81"
                  @change="clearHerbalInformation">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <el-form label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item class="bi_tian" label="药品编码：">
              <xc-combo-grid v-model="caoYao.chargeCodeName"
                             :table-header="headerTable"
                             @rowClick="dianJiXuanZhongCaoYao"
                             ref="xcComboRef"
                             :query-data-func="queryHerbalMedicineOrder">
              </xc-combo-grid>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量：">
              <el-input-number v-model="caoYao.quantity" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="说明：">
              <el-input v-model="caoYao.instruction"
                        :maxlength="30"
                        clearable
                        show-word-limit
                        type="textarea"
                        @keydown.tab="addTo"/>
              <el-button @click="addTo">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="mingXi.list" :height="windowSize.h / 2.3" highlight-current-row stripe @row-click="dianJiBianJi">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="编码" prop="chargeCode"></el-table-column>
        <el-table-column label="名称" prop="chargeCodeName"></el-table-column>
        <el-table-column label="数量" prop="quantity"></el-table-column>
        <el-table-column label="金额" prop="je"></el-table-column>
        <el-table-column label="规格" prop="specification"></el-table-column>
        <el-table-column label="单价" prop="retprice"></el-table-column>
        <el-table-column label="药房" prop="groupName"></el-table-column>
        <el-table-column label="说明" prop="instruction"></el-table-column>
        <el-table-column label="包装大小" prop="serial">
          <template #default="scope">
            <span v-if="scope.row.serial === '01'">小包装</span>
            <span v-else-if="scope.row.serial === '99'">大包装</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                circle
                icon="Delete"
                type="danger"
                @click="removeHerbs(scope.$index)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
  <!-- 获取草药模板 -->
  <cao-yao-mu-ban v-if="muBanZuJian" @close="muBanZuJian = false"
                  @xuanZhongShuJu="dianJiXuanZhongMuBanShuJu"></cao-yao-mu-ban>
  <!-- 下面是新增模板 -->
  <el-dialog v-model="cunMuBan.dialog" center title="存模板">
    模板名称：
    <el-input v-model="cunMuBan.patternName" clearable maxlength="30" show-word-limit
              @keyup.enter="dianJiCunMuBan"></el-input>
  </el-dialog>
</template>

<script setup name="XinZhenCaoYao">
import {computed, onMounted, ref, watch} from 'vue'
import {
  cuoWuXinXi,
  huanZheXinXi,
  youWuXuanZheHuanZhe,
  mingXi
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {
  baoCunCaoYao,
  chongFuMuBanMing,
  cunMuBanApi,
  fuYongFangFa,
  huoQuCaoYao
} from '@/api/zhu-yuan-yi-sheng/cao-yao-yi-zhu'
import store from '@/store'
import {ElMessage, ElMessageBox} from 'element-plus'
import {stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import CaoYaoMuBan from '@/components/zhu-yuan-yi-sheng/cao-yao-yi-zhu/CaoYaoMuBan.vue'
import {yaoPinXiangMuPiPeiYiBao} from '@/api/public-api'
import CuoWuXinXi from '@/components/zhu-yuan-yi-sheng/CuoWuXinXi.vue'
import XcComboGrid from "@/components/xiao-chan/combo-grid/XcComboGrid";
import sleep from "@/utils/sleep";
import CaoYaoCuoWuXinXin from "@/components/zhu-yuan-yi-sheng/cao-yao-yi-zhu/CaoYaoCuoWuXinXin.vue";

const props = defineProps({
  saveSuccess: Function
})

const windowSize = computed(() => {
  return store.state.app.windowSize
})

/**
 * 处方信息
 */
const chuFang = ref({
  orderName: '',
  quantity: 0,
  quantityDj: 0,
  cyMtjs: 0,
  cyJsl: 0,
  cyZql: 0,
  cyFj: 0,
  cyFfcs: 0,
  cyJssm: '',
  groupNo: '81',
})
/**
 * 编辑草药
 * @type {Ref<UnwrapRef<{chargeCodeName: string, quantity: number, retprice: number, instruction: string, je: string, chargeCode: string}>>}
 */
const caoYao = ref({
  chargeCode: '',
  chargeCodeName: '',
  quantity: 0,
  retprice: 0,
  instruction: '',
  je: '',
})

// 清空数据
const wipeData = () => {
  mingXi.value.list = []
  mingXi.value.weiYi = []
  caoYao.value = {
    chargeCode: '',
    chargeCodeName: '',
    quantity: 0,
    retprice: 0,
    instruction: '',
    je: '',
  }
  chuFang.value = {
    orderName: '',
    quantity: 0,
    quantityDj: 0,
    cyMtjs: 0,
    cyJsl: 0,
    cyZql: 0,
    cyFj: 0,
    cyFfcs: 0,
    cyJssm: '',
    groupNo: '81',
  }
}

/**
 * 删除草药下标
 * @param index
 */
const removeHerbs = (index) => {
  mingXi.value.weiYi.splice(index, 1);
  mingXi.value.list.splice(index, 1)
}

const headerTable = [
  {label: '编码', prop: 'chargeCode'},
  {label: '名称', prop: 'chargeCodeName'},
  {label: '药房', prop: 'groupName'},
  {label: '单价', prop: 'retprice'},
  {label: '规格', prop: 'specification'},
  {label: '包装大小', prop: 'serial'},
]
const queryHerbalMedicineOrder = (val) => {
  return huoQuCaoYao(val, chuFang.value.groupNo)
}

/**
 * 草药服用方法数据
 * @type {Ref<UnwrapRef<*[]>>}
 */
const fuYongFangFaShuJu = ref([])

const dianJiXuanZhongCaoYao = (row) => {
  let key = row.chargeCode + row.serial
  if (mingXi.value.weiYi.indexOf(key) > -1) {
    return ElMessage.error('请勿重复添加。')
  } else {
    row.quantity = 1
    row.je = row.retprice
    caoYao.value = row
  }
}
const xcComboRef = ref()
const addTo = async () => {
  if (stringNotBlank(caoYao.value.chargeCode)) {
    let key = caoYao.value.chargeCode + caoYao.value.serial
    let index = mingXi.value.weiYi.indexOf(key)
    if (index > -1) {
      mingXi.value.list.splice(index, 1)
      mingXi.value.weiYi.splice(index, 1)
    }

    mingXi.value.list.push(caoYao.value)
    mingXi.value.weiYi.push(key)
    caoYao.value = {
      chargeCode: '',
      chargeCodeName: '',
      quantity: 0,
      retprice: 0,
      instruction: '',
      je: '',
    }
  }
  await sleep(100)
  xcComboRef.value.focus()
}


const dianJiBianJi = (row) => {
  caoYao.value = row
}

watch(
    () => caoYao.value.quantity,
    () => {
      caoYao.value.je = (caoYao.value.quantity * caoYao.value.retprice).toFixed(2)
    }
)

/**
 * 下面是取模板的
 */
const muBanZuJian = ref(false)

const dianJiXuanZhongMuBanShuJu = (data) => {
  let flag = false
  for (let item of data) {
    if (item.groupNo !== chuFang.value.groupNo) {
      ElMessage.error('模板药房和当前药房不相同')
      return
    }
  }
  data.forEach((item) => {
    let key = item.chargeCode + item.serial
    if (mingXi.value.weiYi.indexOf(key) > -1) {
      flag = true
    } else {
      item.je = (item.quantity * item.retprice).toFixed(2)
      item.groupName = item.groupNo === '81' ? '门诊中药房' : '颗粒剂药房'
      mingXi.value.list.push(item)
      mingXi.value.weiYi.push(key)
    }
  })
  if (flag) {
    ElMessage({
      showClose: true,
      message: '请勿重复添加。',
      type: 'error',
    })
  }
}

/**
 * 下面是存模板
 */
const cunMuBan = ref({
  patternName: '',
  dialog: false,
  chongFuBiaoZhi: false,
})

const dianJiCunMuBan = () => {
  let val = cunMuBan.value.patternName
  if (stringIsBlank(val)) return
  chongFuMuBanMing(val).then((res) => {
    if (res) {
      return ElMessage.error('模板名重复。')
    } else {
      let data = {
        patternName: val,
        list: mingXi.value.list,
        deptCode: store.state.user.info.deptCode,
      }
      cunMuBanApi(data).then(() => {
        cunMuBan.value.dialog = false
        cunMuBan.value.patternName = ''
        wipeData()
      })
    }
  })
}

/**
 * 保存草药
 */
const dianJiBaoCunCaoYao = () => {
  if (youWuXuanZheHuanZhe()) return
  if (stringIsBlank(chuFang.value.orderName)) {
    return ElMessage.error('请输入处方名。')
  }
  if (chuFang.value.quantity === 0) {
    return ElMessage.error('请选择剂数')
  }
  if (chuFang.value.quantityDj === 0) {
    return ElMessage.error('请选择代煎数')
  }
  let listCode = []
  mingXi.value.list.forEach((item) => {
    listCode.push(item.chargeCode + '-' + item.serial)
  })
  yaoPinXiangMuPiPeiYiBao(listCode).then((res) => {
    if (stringNotBlank(res)) {
      cuoWuXinXi.value = res
      ElMessageBox.confirm(res, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
      })
          .then(() => {
            baoCunShuJu()
          })
          .catch(() => {
          })
    } else {
      baoCunShuJu()
    }
  })
}

const errorMsg = ref({
  data: {},
  count: 0
})

function baoCunShuJu() {
  ElMessageBox.confirm(chuFang.value.quantity > 20 ? '剂数大于20是否继续录入？' : '请确定好数据？', '提示', {
    type: 'warning',
  }).then(() => {
    let data = chuFang.value
    data.inpatientNo = huanZheXinXi.value.inpatientNo
    data.admissTimes = huanZheXinXi.value.admissTimes
    data.list = mingXi.value.list
    data.deptCode = store.state.user.info.deptCode
    baoCunCaoYao(data).then((res) => {
      if (res?.error) {
        errorMsg.value.data = res.data
        errorMsg.value.count = msgLength()
      } else {
        errorMsg.value.data = {}
        errorMsg.value.count = 0
        wipeData();
        props.saveSuccess()
      }
    })
  })
      .catch(() => {
      })
}

const msgLength = () => {
  let a = 0;
  for (let dataKey in errorMsg.value.data) {
    a += 1
  }
  return a
}

const clearHerbalInformation = () => {
  mingXi.value.weiYi = []
  mingXi.value.list = []
}

onMounted(() => {
  fuYongFangFa().then((res) => {
    fuYongFangFaShuJu.value = res
  })
})

let jiaShuiLeiXing = [
  {code: '加凉水', name: '加凉水'},
  {code: '加温水', name: '加温水'},
  {code: '加开水', name: '加开水'},
  {code: '加冰水', name: '加冰水'},
  {code: '加外糖水', name: '加外糖水'},
  {code: '外敷', name: '外敷'},
]

</script>

<style scoped></style>
