<template>
  <BasicModal
    width="800px"
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <Row>
      <Col :span="16">
        <BasicForm @register="registerForm">
          <template #contextSlot="{ model, field }">
            <InputGroup compact>
              <Textarea
                type="textarea"
                :rows="4"
                v-model:value="model[field]"
                @focus="treeDis = false"
                id="contexts"
              />
              <span class="context-tip"
                >例：患者今日常规透析，预设超滤{V值}。透前称重测血压{透前血压}。</span
              >
              <Button size="mini" type="primary" shape="round" class="per-btn" @click="handlePer"
                >内容预览</Button
              >
              <!-- @blur="treeDis = true" -->
            </InputGroup>
          </template>
          <template #previewSlot="{ model, field }"> {{ model[field] }} </template>
        </BasicForm>
      </Col>
      <Col :span="8">
        <a-tree
          :disabled="treeDis"
          :tree-data="noteFieldList"
          v-model:expanded-keys="expandedKeys"
          @select="handleSel"
          :field-names="{ children: 'children', title: 'fieldName', key: 'fieldName' }"
        />
      </Col>
    </Row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { Row, Col, InputGroup, Button, Textarea } from 'ant-design-vue';
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FormSchema } from '/@/components/Table';
  import { getNoteFieldList } from '/@/api/biz/management/complication';

  import {
    addComplicationExplain,
    editComplicationExplain,
    getComplicationExplainById,
    perComplicationExplain,
  } from '/@/api/biz/management/complication';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增说明模板' : '编辑说明模板'));
  const isUpdate = ref(false);
  const rowId = ref();
  const noteFieldList = ref([]);
  const expandedKeys = ref([]);
  const treeDis = ref(true);

  const noteFormSchema: FormSchema[] = [
    {
      label: '并发症ID',
      field: 'complicationId',
      component: 'Input',
      show: false,
    },
    {
      label: '模版名称',
      field: 'name',
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: '请输入模版名称',
        onFocus: function () {
          treeDis.value = true;
        },
      },
    },
    {
      label: '排序',
      field: 'sort',
      required: true,
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入排序',
        min: 0,
        onFocus: function () {
          treeDis.value = true;
        },
      },
    },
    {
      label: '模版内容',
      field: 'context',
      required: true,
      slot: 'contextSlot',
      component: 'Input',
    },
    {
      label: '预览内容',
      field: 'preview',
      slot: 'previewSlot',
      component: 'InputTextArea',
    },
  ];

  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate, setFieldsValue, getFieldsValue }] = useForm({
    layout: 'vertical',
    showResetButton: true,
    labelWidth: 100,
    schemas: noteFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    getNoteFieldLists();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await getComplicationExplainById(data.record.id);
      await setFieldsValue({
        ...resData,
      });
    } else {
      await setFieldsValue({
        complicationId: data.id,
      });
    }
  });
  //获取说明模板字段
  async function getNoteFieldLists() {
    const lists = await getNoteFieldList();
    noteFieldList.value = [];
    expandedKeys.value = Object.keys(lists);
    Object.keys(lists).forEach((item, index) => {
      lists[item].forEach((cItem, cIndex) => {
        cItem.key = index * 1000 + cIndex;
      });
      noteFieldList.value.push({
        fieldName: item,
        key: index,
        children: lists[item],
      });
    });
  }

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await addComplicationExplain({ ...values })
        : await editComplicationExplain({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false, canFullscreen: false });
    }
  }

  // 预览按钮事件
  async function handlePer() {
    const formVal = getFieldsValue();
    if (formVal && formVal.context) {
      const perVal = await perComplicationExplain(formVal.context);
      await setFieldsValue({
        ...formVal,
        preview: perVal,
      });
    } else {
      createMessage.error('请输入模板内容后进行预览');
    }
  }

  // 选择说明模板字段事件
  function handleSel(selectedKeys, { selectedNodes }) {
    // selected, selectedNodes, node, event
    treeDis.value = false;
    insertAtCursor(selectedNodes[0].fieldName);
    selectedKeys = [];
  }

  // 在鼠标光标处插入对应说明模板字段
  async function insertAtCursor(myValue: any) {
    let res = '';
    let frontString = '';
    let afterString = '';
    const fieldsValue = getFieldsValue();
    const position = document.getElementById('contexts');
    const pos = getPositionForTextArea(position);
    const y = fieldsValue.context ? fieldsValue.context : '';
    frontString = y.substring(0, pos);
    afterString = y.substring(pos, fieldsValue.context?.length);
    res = frontString + '{' + myValue + '}' + afterString;
    await setFieldsValue({
      ...fieldsValue,
      context: res,
    });
  }
  // 获取鼠标光标位置
  function getPositionForTextArea(ctrl) {
    let CaretPos = 0;
    if (ctrl.selectionStart || ctrl.selectionStart == '0') {
      CaretPos = ctrl.selectionStart;
    }
    return CaretPos;
  }
</script>
<style lang="less" scoped>
  .per-btn {
    margin-top: 6px;
    margin-right: 6px;
    border-radius: 12px !important;
    float: right;
  }

  .context-tip {
    font-size: 12px;
    font-weight: 400;
    color: #c3cdd8;
  }
</style>
