<template>
  <el-drawer v-loading="loading" :close-on-click-modal="false" :model-value="visible"
    :title="data._id ? '编辑药品' : '新增药品'" size="70%" style="--el-drawer-padding-primary: 0" @close="close">
    <my-layout>
      <layout-main>
        <el-form :label-width="140" :model="taskForm" label-suffix="：" class="p-15px pr-30px"
          :class="loading ? 'pointer-events-none' : ''">
          <div active-title-bar class="mb-2.5">药品基本信息</div>
          <el-row>
            <el-col :span="12" v-for="item in basicInfoList" :key="item.prop">
              <el-form-item :label="item.label" :prop="item.prop" :class="requiredMap[item.prop] ? 'is-required' : ''">
                <el-select v-if="item.options" filterable clearable :model-value="form[item.prop]"
                  :placeholder="`请选择${item.label}`" class="w-full" @update:model-value="changeValue($event, item.prop)">
                  <el-option v-for="option in item.options" :key="option" :label="option" :value="option" />
                </el-select>
                <el-input v-else clearable :model-value="form[item.prop]" :maxlength="item.maxlength"
                  :placeholder="`请输入${item.label}`" @update:model-value="changeValue($event, item.prop)" />
              </el-form-item>
            </el-col>
          </el-row>
          <div active-title-bar class="mb-2.5">药品标准用法用量</div>
          <el-row>
            <el-col :span="12" v-for="item in usageInfo" :key="item.prop">
              <el-form-item :label="item.label" :prop="item.prop" :class="requiredMap[item.prop] ? 'is-required' : ''">
                <el-select v-if="item.options" filterable clearable :model-value="form[item.prop]"
                  :placeholder="`请选择${item.label}`" class="w-full" @update:model-value="changeValue($event, item.prop)">
                  <el-option v-for="option in item.options" :key="option" :label="option" :value="option" />
                </el-select>
                <el-input v-else clearable :model-value="form[item.prop]" :maxlength="item.maxlength"
                  :placeholder="`请输入${item.label}`" @update:model-value="changeValue($event, item.prop)" />
              </el-form-item>
            </el-col>
          </el-row>
          <div active-title-bar class="mb-2.5">药品规则配置</div>
          <el-row>
            <template v-if="libType === 'online'">
              <el-col :span="12" v-for="item in suitableInfo" :key="item.prop">
                <el-form-item :label="item.label" :prop="item.prop"
                  :class="requiredMap[item.prop] ? 'is-required' : ''">
                  <el-select filterable clearable :model-value="form[item.prop]" :placeholder="`请选择${item.label}`"
                    class="w-full" @update:model-value="changeValue($event, item.prop)">
                    <el-option v-for="option in item.options" :key="option" :label="option.label"
                      :value="option.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" :key="repeatTag">
                <el-form-item label="重复用药标识" prop="repeatTag">
                  <!-- <el-select-v2 filterable clearable :multiple="true" :model-value="form.repeatTag" placeholder="请选择重复用药标识"
                    class="w-full" @update:model-value="changeValue($event, 'repeatTag')">
                    <el-option v-for="option in repeatTagList" :key="option.value" :label="option.label"
                      :value="option.value" />
                  </el-select-v2> -->
                  <el-select-v2 :model-value="form.repeatTag||[]" :options="repeatTagList" placeholder="请选择重复用药标识"
                    class="w-full" multiple filterable clearable
                    @update:model-value="changeValue($event, 'repeatTag')" />
                </el-form-item>
              </el-col>
            </template>
            <el-col v-for="item in otherInfo" :key="item.prop">
              <el-form-item :label="item.label" :prop="item.prop" :class="requiredMap[item.prop] ? 'is-required' : ''">
                <div class="other-info-row">
                  <el-select class="other-info-select" placeholder="请选择" :model-value="form[item.prop]"
                    @change="val => selectChange(item.prop, val)">
                    <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                      :value="option.value" />
                  </el-select>
                  <!-- 当选择为 true 时才渲染输入框，同时把输入框拉伸占满剩余空间 -->
                  <div v-if="item.prop === 'need_medication_proof' && form.need_medication_proof"
                    class="other-info-desc">
                    <el-input clearable :model-value="form.medication_proof_desc" placeholder="描述需上传的用药证明文件类型，用于患者端显示"
                      style="width:100%" @update:model-value="val => changeValue(val, 'medication_proof_desc')" />
                  </div>
                  <div v-else-if="item.prop === 'has_usage_restriction' && form.has_usage_restriction"
                    class="other-info-desc">
                    <el-input clearable :model-value="form.usage_restriction_desc" placeholder="描述该药品的限制使用范围，用于医生、药师端展示"
                      style="width:100%" @update:model-value="val => changeValue(val, 'usage_restriction_desc')" />
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </layout-main>
      <layout-item>
        <div common-shadow--r class="text-center py-10px">
          <el-button class="w-100px" @click="close()">取消</el-button>
          <el-button class="w-100px" :loading="loading" type="primary" @click="save()">保存</el-button>
        </div>
      </layout-item>
    </my-layout>
  </el-drawer>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { ElMessage } from "element-plus";
import { addHlwDrugInfo, editHlwDrugInfo, addOnlineDrugInfo, editOnlineDrugInfo, getOnlineDrugRepeatTags } from "@/api/hlw";
import categoryList from '@/baseData/drug-category';
import frequencyList from '@/baseData/frequency.js';
import dosageUnitList from '@/baseData/dosageUnit.js';
import unitList from '@/baseData/unit';
import usageList from '@/baseData/usage.js';
import { drugFieldDict, getDrugList } from './drug-dict.js'

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";

const emits = defineEmits(['close', 'change'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 库类型：hlw = 互联网医院药品库(drug-info)，online = 配送/线上药品库(online-drug-info)
  libType: {
    type: String,
    default: 'hlw'
  },
  memberInfo: { type: Object, default: () => ({}) },
  data: {
    type: Object,
    default: () => ({})
  }
})

const repeatTagList = ref([])
const basicInfo = [
  { label: '药品名称', prop: "name", maxlength: 100 },
  { label: '药品规格', prop: "specification", maxlength: 100 },
  { label: '包装单位', prop: "unit", options: unitList },
  { label: '包装量', prop: "package_amount", maxlength: 100 },
  { label: '生产厂家', prop: "manufacturer", maxlength: 100 },
  { label: '商品条形码', prop: "barcode", maxlength: 100 },
  { label: '医保编码', prop: "insurance_code", maxlength: 100 },
  { label: '药品分类', prop: "category", options: categoryList },
  { label: '药品拼音码', prop: "pinyin_code", maxlength: 100 },
  { label: '药库货品ID', prop: "product_id", maxlength: 100 },
  { label: '通用名', prop: "generic_name", maxlength: 100 },
  { label: '通用名拼音码', prop: "generic_pinyin", maxlength: 100 },
]

// 在线药品库扩展字段：管理分类 + 剂型
const onlineBasicInfoExtra = [
  { label: '管理分类', prop: "manage_category", options: ['处方药', 'OTC'] },
  { label: '剂型', prop: "dosage_form", maxlength: 100 },
  { label: 'ERP编码', prop: "his_drug_code", maxlength: 100 },
]

// 根据 libType 决定展示哪些基础信息字段
const basicInfoList = computed(() => {
  return props.libType === 'online'
    ? [...basicInfo, ...onlineBasicInfoExtra]
    : basicInfo;
})

const usageInfo = [
  { label: '单次标准剂量', prop: "dosage", maxlength: 100 },
  { label: '剂量单位', prop: "dosage_unit", options: dosageUnitList },
  { label: '给药标准频次', prop: "frequency", options: frequencyList.map(i => i.name) },
  { label: '给药标准方式', prop: "administration_method", options: usageList.map(i => i.name) },
  { label: '用药标准天数', prop: "days", maxlength: 100 },
  { label: '发药标准数量', prop: "recommended_quantity", maxlength: 100 },
]
const suitableInfo = [
  { label: '适用性别', prop: 'suitableGender', options: [{ label: '通用', value: 'common' }, { label: '男', value: 'male' }, { label: '女', value: 'female' }] },
  { label: '是否儿童用药', prop: 'suitableChild', options: [{ label: '是', value: true }, { label: '否', value: false }] },
  // { label: '重复用药标识', prop: 'repeatTag', multiple: true, options: new Array(5).fill(1).map((_, index) => ({ label: index + 1, value: index + 1 })) },
]
// 其他信息：是否需要上传用药证明/是否有使用范围限制 与 对应描述
const otherInfo = [
  { label: '是否上传用药证明', prop: 'need_medication_proof', type: 'select', options: [{ label: '是', value: true }, { label: '否', value: false }] },
  { label: '是否限制使用范围', prop: 'has_usage_restriction', type: 'select', options: [{ label: '是', value: true }, { label: '否', value: false }] }
]

const requiredMap = computed(() => {
  const m = drugFieldDict.reduce((acc, cur) => {
    acc[cur.field] = typeof cur.required === 'boolean' ? cur.required : false
    return acc
  }, {})
  m.medication_proof_desc = Boolean(m.medication_proof_desc);
  m.usage_restriction_desc = Boolean(m.usage_restriction_desc);
  if (props.libType === 'online') {
    m.his_drug_code = true
  }
  return m
})

const editForm = ref({})
const form = computed(() => ({ ...props.data, ...editForm.value }))
const tableRef = ref(null);
const loading = ref(false)

function changeValue(val, prop) {
  editForm.value[prop] = val
}


function close() {
  if (loading.value) return;
  emits('close')
}

async function save() {
  if (loading.value) return;
  const isEdit = Boolean(props.data._id);
  const [drug] = getDrugList([editForm.value], 'field', !isEdit, props.libType);
  if (drug.msgs.length) {
    ElMessage.info(drug.msgs[0])
    return
  }

  if (Object.keys(editForm.value).length) {
    loading.value = true;
    const isOnline = props.libType === 'online';
    const apiMap = {
      update: isOnline ? editOnlineDrugInfo : editHlwDrugInfo,
      add: isOnline ? addOnlineDrugInfo : addHlwDrugInfo,
    }
    const api = props.data._id ? apiMap.update : apiMap.add;
    const payload = {
      params: { ...editForm.value },
      id: props.data._id,
      operator: props.memberInfo.anotherName,
      operatorId: props.memberInfo._id,
    }
    if (!props.data._id) {
      payload.params.onSale = true;
    }
    loading.value = false;
    const { success, message } = await api(payload);
    loading.value = false;
    if (success) {
      ElMessage.success(message)
      emits('change')
      close();
    } else {
      ElMessage.error(message)
      return
    }
  }
}

async function getRepeatTags() {
  const res = await getOnlineDrugRepeatTags()
  repeatTagList.value = res && res.data && Array.isArray(res.data.data) ? res.data.data.map(i => ({ label: `${i}`, value: i })) : [];
}

watch(() => props.visible, (val) => {
  if (val) {
    // reset local editForm when opening drawer
    editForm.value = {}
    if (props.libType === 'online') {
      getRepeatTags()
    }
    // initialize select values based on props.data for edit scenario
    if (props.data) {
      if (props.data.medication_proof_desc) {
        editForm.value.medication_proof_desc = props.data.medication_proof_desc
        editForm.value.need_medication_proof = true
      } else {
        editForm.value.need_medication_proof = false
      }
      if (props.data.usage_restriction_desc) {
        editForm.value.usage_restriction_desc = props.data.usage_restriction_desc
        editForm.value.has_usage_restriction = true
      } else {
        editForm.value.has_usage_restriction = false
      }
      if (props.data.repeatTag && !Array.isArray(props.data.repeatTag)) {
        editForm.value.repeatTag = [props.data.repeatTag]
      }
    }
  }
})

function selectChange(prop, val) {
  // store select value and clear description when selecting '否' (false)
  changeValue(val, prop)
  if (prop === 'need_medication_proof' && !val) {
    changeValue('', 'medication_proof_desc')
  }
  if (prop === 'has_usage_restriction' && !val) {
    changeValue('', 'usage_restriction_desc')
  }
}

</script>
<style scoped>
.other-info-row {
  display: flex;
  align-items: center;
  /* vertically center select and input */
  gap: 12px;
  width: 100%;
}

.other-info-select {
  flex: 0 0 140px;
  /* slightly wider to accommodate labels */
}

.other-info-desc {
  flex: 1 1 0;
  /* take remaining space */
  min-width: 0;
  /* allow input to shrink properly inside flex */
}
</style>
