<template>
  <CyFlex content-size>
    <template #header>
      <div>
        <el-button type="primary" @click="openCaoYaoTemplate">取模板</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"/>
      </div>
      <div style="margin-top: 5px">
        <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" v-if="show">
              <el-form-item class="bi_tian" label="代煎：">
                <el-input-number v-model="chuFang.quantityDj"
                                 :max="chuFang.quantity"
                                 :min="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item class="bi_tian" label="执行科室：">
                <dept-select v-model="chuFang.execDept"/>
              </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-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="加水量（ml）：">
                <el-input-number v-model="chuFang.cyJsl"/>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="show">
              <el-form-item label="煮取（ml）：">
                <el-input-number v-model="chuFang.cyZql"/>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="show">
              <el-form-item label="复煎：">
                <el-input-number v-model="chuFang.cyFj"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="分几次：">
                <el-input-number v-model="chuFang.cyFfcs"/>
              </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="83"
                    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="药品编码：">
                <CyComboGrid v-model="caoYao"
                             value="chargeCode"
                             label="chargeCodeName"
                             @rowClick="({row}) => dianJiXuanZhongCaoYao(row)"
                             :table-header="headerTable"
                             :remote-method="queryHerbalMedicineOrder"
                             ref="xcComboRef"
                >
                </CyComboGrid>
              </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>
      </div>
    </template>

    <template #default="{height}">
      <el-table :data="mingXi.list"
                style="width: 100%"
                :height="height"
                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>
    </template>
  </CyFlex>

  <!-- 获取草药模板 -->
  <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>
import {computed, onMounted, ref, watch} from 'vue'
import {
  cuoWuXinXi,
  huanZheXinXi,
  youWuXuanZheHuanZhe,
  mingXi,
  onChangePatient
} 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 {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 sleep from "@/utils/sleep";
import CaoYaoCuoWuXinXin from "@/components/zhu-yuan-yi-sheng/cao-yao-yi-zhu/CaoYaoCuoWuXinXin.vue";
import DeptSelect from "@/components/xiao-chan/dept-code/DeptSelect.vue";
import Dig from "@/utils/math";
import CyFlex from "@/components/cy/flex/src/CyFlex.vue";
import CyComboGrid from "@/components/cy/combo-grid/src/CyComboGrid.vue";
import {useUserStore} from "@/pinia/user-store";
import useDialogToJs from "@/components/js-dialog-comp/useDialogToJs";

const props = defineProps({
  saveSuccess: Function
})

/**
 * 处方信息
 */
const chuFang = ref({
  orderName: '草药',
  quantity: 0,
  quantityDj: 0,
  cyMtjs: 0,
  cyJsl: 400,
  cyZql: 200,
  cyFj: 0,
  cyFfcs: 0,
  cyJssm: '',
  groupNo: '81',
  execDept: ''
})

const show = computed(() => {
  return chuFang.value.groupNo !== '83'
})

/**
 * 编辑草药
 * @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: 400,
    cyZql: 200,
    cyFj: 0,
    cyFfcs: 0,
    cyJssm: '',
    groupNo: '81',
    execDept: huanZheXinXi.value.smallDept
  }
}

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

const headerTable = [
  {name: '编码', code: 'chargeCode', width: 60},
  {name: '名称', code: 'chargeCodeName', width: 150},
  {name: '药房', code: 'groupName', width: 100},
  {name: '单价', code: 'retprice', width: 90},
  {name: '规格', code: 'specification', width: 50},
  {name: '包装', code: 'serial', width: 50},
]
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 = Dig.multiply(caoYao.value.quantity, caoYao.value.retprice).toFixed(2)
    }
)

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

const dianJiXuanZhongMuBanShuJu = (data, next) => {
  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 = Dig.multiply(item.quantity, item.retprice).toFixed(2)
      item.groupName = item.groupNo === '81' ? '门诊中药房' : '颗粒剂药房'
      mingXi.value.list.push(item)
      mingXi.value.weiYi.push(key)
    }
  })
  next()
  if (flag) {
    ElMessage({
      showClose: true,
      message: '请勿重复添加。',
      type: 'error',
    })
  }
}

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

const userStore = useUserStore()
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: userStore.userInfo.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 (stringIsBlank(chuFang.value.execDept)) {
    chuFang.value.execDept = huanZheXinXi.value.smallDept
    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,
        confirmButtonText: '继续录入'
      })
          .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 = userStore.userInfo.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 = []
  caoYao.value.chargeCodeName = ''
  caoYao.value.quantity = 1
  caoYao.value.instruction = ''
  chuFang.value.cyZql = 0
  chuFang.value.quantityDj = 0
  chuFang.value.cyFj = 0
  chuFang.value.orderName = chuFang.value.groupNo === '81' ? '草药' : '中药颗粒'
}

function openCaoYaoTemplate() {
  useDialogToJs(CaoYaoMuBan, {
    onXuanZhongShuJu: dianJiXuanZhongMuBanShuJu
  })
}

onChangePatient(() => {
  chuFang.value.execDept = huanZheXinXi.value.smallDept || ""
})

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

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

</script>

<style scoped></style>
