<template>
  <div class="m-4">
    <div>
      <XTTitle title="查房" @click="callTitleClick" />
      <div class="flex justify-between my-4">
        <XTTab
          type="check"
          :width="160"
          :selected="activeKey"
          :data="tabData"
          @item-click="callTab"
        />
        <XTForm :form-data="formData" @change="callFormChange" @click="callFormClick" />
      </div>
      <div class="flex mb-2" v-if="siftData.length">
        <Sift :data="siftData" @close="callClose" />
      </div>
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <span :class="['table-dot', 'table-dot--' + record.status]" />
            <span>{{ record.name }}</span>
          </template>
          <template v-if="column.key === 'patrolTime'">
            {{ record.patrolTime ? dayjs(record.patrolTime).format('YYYY-MM-DD') : '' }}
          </template>

          <template v-if="column.key === 'action'">
            <TableAction
              :dropDownActions="[
                {
                  auth: 'storage:config:edit',
                  tooltip: '查房记录',
                  label: '查房记录',
                  ifShow: !record.master,
                },
                {
                  auth: 'storage:config:edit',
                  tooltip: '编辑',
                  label: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  auth: 'storage:config:remove',
                  tooltip: '取消关注',
                  label: '取消关注',
                  color: 'error',
                  // popConfirm: {
                  //   title: '是否确定要取消关注？',
                  //   placement: 'left',
                  //   confirm: handleDelete.bind(null, record),
                  // },
                },
              ]"
              :actions="[
                {
                  auth: 'sys:log:query',
                  // icon: 'icon-eye|iconfont',
                  tooltip: '查房',
                  label: '查房',
                  onClick: handleView.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <FormModal @register="registerModal" @success="handleSuccess" />
    <ViewDrawer @register="registerDrawerView" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { XTTitle } from '/@/components/XTTitle/index';
  import { XTTab } from '/@/components/XTTab/index';
  import { XTForm } from '/@/components/XTForm/index';
  import { Sift } from '/@/components/XTList/index';
  import { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import { BasicTab, BasicTabActive, columns } from './data';
  import { ref } from 'vue';
  // import { useRouter } from 'vue-router';
  import {
    archivesPatrolWardQueryCheckRoomRecord,
    archivesPatrolWardQueryPersonNumber,
  } from '/@/api/biz/visit/checkApi';
  // import { formatDictColor, formatDictFontColor, formatDictValue } from '/@/utils';
  import { onMounted, reactive } from 'vue';
  import dayjs from 'dayjs';
  import { useModal } from '/@/components/Modal';
  import FormModal from './formModal.vue';
  import ViewDrawer from './viewDrawer.vue';
  import { useDrawer } from '@/components/Drawer';

  // const bizDictOptions = reactive<any>({});
  //路由跳转
  // const router = useRouter();
  const activeKey = ref(BasicTabActive);
  const tabData = ref(BasicTab);
  const [registerModal, { openModal }] = useModal();
  const [registerDrawerView, { openDrawer, openDrawer: openDrawerView }] = useDrawer();

  onMounted(async () => {
    const personNumber = await archivesPatrolWardQueryPersonNumber();
    console.log('🚀 ~ file: index.vue:104 ~ onMounted ~ stats:', personNumber);
    tabData.value = tabData.value.map(ele => {
      if (ele.key == '0') {
        ele.value = personNumber.all;
      }
      if (ele.key == '1') {
        ele.value = personNumber.dialysisPatients;
      }
      if (ele.key == '2') {
        ele.value = personNumber.noDialysisPatients;
      }
      if (ele.key == '3') {
        ele.value = personNumber.newPatient;
      }
      if (ele.key == '4') {
        ele.value = personNumber.attention;
      }
      return ele;
    });
    console.log('🚀 ~ file: index.vue:118 ~ onMounted ~ tabData.value:', tabData.value);
  });
  const [registerTable, { reload }] = useTable({
    api: archivesPatrolWardQueryCheckRoomRecord,
    // exportAuthList: ['sys:log:export'],
    rowKey: 'id',
    columns,
    showIndexColumn: true,
    bordered: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
  });
  // 筛选数据
  const siftData = ref([]);

  // formdata
  const formData = [
    {
      name: 'tableSort',
      componentType: 'Select',
      placeholder: '请选择',
      width: 120,
      defaultValue: 'patrolTime',
      dicts: [
        { label: '按查房时间', value: 'patrolTime' },
        { label: '按姓氏', value: 'patientNamePinyin' },
      ],
    },
    {
      name: 'name',
      componentType: 'Input',
      placeholder: '请输入患者姓名',
      width: 200,
      prefix: 'icon-xt-search',
    },
  ];

  const formValue = reactive({
    name: '',
  }) as any;

  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    // return { ...params, orders: tableSort.value };
    const sift = {};
    siftData.value.forEach(ele => {
      sift[ele.field] = ele.isDict ? ele.dict : ele.value;
    });
    return {
      ...params,
      queryType: activeKey.value == '0' ? '0' : activeKey.value,
      name: formValue.name,
      orders: [{ field: 'patrolTime', direction: 'DESC' }],
      sortType: 'st_patrol_time',
      ...sift,
    };
  }

  function handleAfterFetch(data) {
    return data;
  }

  // 详情按钮事件
  function handleView(record: Recordable) {
    console.log(record);
    openDrawerView(true, {
      record,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  // 弹窗回调事件
  async function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    await reload();
  }
  // 回调
  async function callTab(data) {
    activeKey.value = data.value;
    await reload();
  }

  function callTitleClick(data) {
    if (data.type == 'add') {
      openDrawer(true, {
        isUpdate: false,
        record: data,
      });
    }
  }

  async function callFormChange(data) {
    formValue.name = data.name ? data.name : '';
    await reload();
  }

  async function callFormClick(data) {
    if (data.name == 'filter') {
      const record = [];
      siftData.value.forEach(ele => {
        const obj = {
          field: ele.field,
          value: ele.value,
        } as any;
        if (ele.isDict) {
          obj.value = ele.dict;
        }
        record.push(obj);
      });
      openDrawer(true, {
        record,
      });
    }
  }

  async function callClose(data) {
    if (data.type == 'clear') {
      console.log('清空全部');
      siftData.value = [];
    }
    if (data.type == 'close') {
      console.log('删除部分条件');
      siftData.value = siftData.value.filter(ele => {
        return ele.field != data.item?.field;
      });
    }
    await reload();
  }
</script>
