<template>
  <div class="LaboratoryTests-container">
    <el-dialog
      title="批量导入项目"
      :model-value="props.dialogVisible"
      @update:modelValue="(val) => emit('update:dialogVisible', val)"
      width="842"
      append-to-body
      destroy-on-close
      :draggable="true"
    >
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form ref="formEl" :rules="rules" :model="form" label-width="100px">
            <el-form-item label="项目类型" prop="clinicalType">
              <el-select
                v-model="form.clinicalType"
                placeholder="请选择"
                @change="getList()"
                filterable
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="item in categoryCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row :gutter="30" style="margin-top: 30px">
        <el-col :span="24">
          <el-transfer
            v-model="transferValue"
            :data="applicationList"
            filter-placeholder="项目代码/名称"
            filterable
            :titles="['未选择', '已选择']"
            style="width: 100%"
          />
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="LaboratoryTests">
import { getCurrentInstance, onBeforeMount, onMounted, reactive, ref } from 'vue';
import {
  getApplicationList,
  editImplementDepartment,
  addImplementDepartment,
} from './implementDepartment.js';
const { proxy } = getCurrentInstance();
// 属性
const props = defineProps({
  // 弹框显示信息
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  // 选择科室
  organizationId: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['update:dialogVisible', 'confirm', 'cancel', 'submitOk']);
// 申请项目列表
const applicationListAll = ref();
// 获取所有申请项目
const applicationList = ref();
// 申请项目列表
const transferValue = ref([]);
// 项目类型
const formEl = ref();
const form = reactive({ clinicalType: '23' });
// 加载中
const loading = ref(false);
// 弹窗显隐由父组件控制，通过 v-model 事件同步
// 项目类型
const categoryCodeList = ref([
  { label: '治疗', value: '21' },
  { label: '检验', value: '22' },
  { label: '检查', value: '23' },
  { label: '手术', value: '24' },
]);
// 规则校验
const rules = ref({
  clinicalType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
});
const getList = () => {
  if (!form.clinicalType) {
    return;
  }
  loading.value = true;
  getApplicationList({
    pageSize: 10000,
    pageNum: 1,
    // 项目类型 枚举类中
    categoryCode: form.clinicalType,
    adviceTypes: '3', //1 药品 2耗材 3诊疗
  }).then((res) => {
    if (res.code === 200) {
      loading.value = false;
      applicationListAll.value = res.data.records;
      applicationList.value = res.data.records.map((item) => {
        return {
          label: item.adviceName + item.adviceDefinitionId,
          key: item.adviceDefinitionId,
        };
      });
    } else {
      proxy.$message.error(res.message);
      applicationList.value = [];
    }
  });
};

function onCancel() {
  emit('cancel');
  emit('update:dialogVisible', false);
}

// 批量添加
async function onConfirm() {
  if (!formEl) return;
  formEl.value.validate(async (valid) => {
    if (!valid) return;
    if (!transferValue.value || transferValue.value.length === 0) {
      proxy.$message.error('请选择至少一个项目');
      return;
    }
    const requests = (transferValue.value || []).map((defId) => {
      const params = {
        // 诊疗定义id
        activityDefinitionId: defId,
        // 科室ID
        organizationId: props.organizationId,
        // 诊疗类型
        activityCategoryCode: form.clinicalType,
        // 开始时间
        startTime: '00:00:00',
        // 结束时间
        endTime: '23:59:59',
        /*
          方法类别：DistributionCategoryCodeEnum 枚举
          desription: 8代表诊疗
        */
        distributionCategoryCode: '8',
      };
      return handleSave(params);
    });
    await Promise.all(requests);
    emit('submitOk');
    emit('update:dialogVisible', false);
    transferValue.value = [];
  });
}
// 保存
async function handleSave(params) {
  if (params.id) {
    return editImplementDepartment(params).then((res) => {
      proxy.$modal.msgSuccess('保存成功！');
      return res;
    });
  } else {
    delete params.id;
    return addImplementDepartment(params).then((res) => {
      proxy.$modal.msgSuccess('保存成功！');
      return res;
    });
  }
}

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-transfer-panel) {
  width: 300px;
}
</style>
