<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <div class="!pl-8 !pt-2">
      <BasicForm @register="registerForm" layout="vertical">
        <template #wardInfo="{ model, field }">
          <div class="flex">
            <div
              v-for="item in model[field]"
              :key="item"
              :style="{
                backgroundColor: formatDictColor(bizDictOptions.wardType, item),
                color: formatDictFontColor(bizDictOptions.wardType, item),
                padding: '1px 6px',
                borderRadius: '2px',
                marginRight: '4px',
              }"
            >
              {{ formatDictValue(bizDictOptions.wardType, item) }}
            </div>
          </div>
        </template>
        <template #deviceInfo="{ model, field }">
          {{ model[field] }}
        </template>
        <template #deviceType="{ model, field }">
          <span
            :class="['table-dot']"
            :style="{
              backgroundColor: formatDictPreColor(bizDictOptions.deviceType, model[field]),
            }"
          />
          <span>{{ formatDictValue(bizDictOptions.deviceType, model[field]) }}</span>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref, computed, reactive, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';
  import { listDictModelBatch } from '/@/api/common';
  import { engineerBedAdd, engineerBedDetail, engineerBedEdit } from '@/api/biz/engineer/bedApi';
  import {
    formatDictColor,
    formatDictValue,
    formatDictPreColor,
    formatDictFontColor,
  } from '@/utils';
  const bizDictData = ref([
    { key: 'wardType', dictCode: 'pb_epidemic' },
    { key: 'deviceType', dictCode: 'bm_det' },
  ]);
  const bizDictOptions = reactive<any>({});
  // 组件加载前事件
  onBeforeMount(async () => {
    const res = await listDictModelBatch(bizDictData.value.map(ele => ele.dictCode));
    for (const i in res) {
      const filter = bizDictData.value.filter(ele => ele.dictCode == i)[0];
      bizDictOptions[filter.key] = res[i];
    }
  });
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(false);
  const getTitle = computed(() => (!unref(isUpdate) ? '新增床位' : '绑定床位'));
  const width = '600px';
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 24,
    },
    wrapperCol: {
      span: 22,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      const resData = await engineerBedDetail(data.record.id);
      rowId.value = resData.id;
      await setFieldsValue({
        ...resData,
        name: resData.bedName,
        wardInfo: resData.infectiousDiseases,
      });
      await updateSchema([
        {
          field: 'wardId',
          componentProps: {
            disabled: true,
          },
        },
      ]);
      await updateSchema({
        field: 'name',
        componentProps: {
          disabled: true,
        },
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (!isUpdate.value) {
        await engineerBedAdd({ ...values });
        createMessage.success('新增成功！');
      } else {
        await engineerBedEdit({ ...values, id: rowId.value });
        console.log(values);
        createMessage.success('绑定成功！');
      }
      closeModal();
      emit('success', {
        values: { ...values, id: rowId.value },
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .table-dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-right: 6px;
    border-radius: 50%;
  }
</style>
