<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>
      <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 === 'gender'">
            <Icon
              v-if="record.gender == 'pb_sex_man'"
              icon="icon-xt-male_sm|iconfont"
              color="#0057FF"
            />
            <Icon
              v-if="record.gender == 'pb_sex_woman'"
              icon="icon-xt-female_sm|iconfont"
              color="#FF0066"
            />({{ record.age }})</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:query',
                  tooltip: '查房记录',
                  label: '查房记录',
                  onClick: handleDetail.bind(null, record),
                  // ifShow: !record.master,
                },
                {
                  auth: 'archives:patrolWard:edit',
                  tooltip: '编辑',
                  label: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  auth: 'storage:config:remove',
                  tooltip: '关注',
                  label: '关注',
                  color: 'error',
                  popConfirm: {
                    title: '是否确定要关注？',
                    placement: 'left',
                    confirm: handleCancel.bind(null, record),
                  },
                },
                {
                  auth: 'storage:config:remove',
                  tooltip: '取消关注',
                  label: '取消关注',
                  color: 'error',
                  popConfirm: {
                    title: '是否确定要取消关注？',
                    placement: 'left',
                    confirm: handleCancel.bind(null, record),
                  },
                },
              ]"
              :actions="[
                {
                  auth: 'archives:patrolWard:query',
                  icon: 'icon-eye|iconfont',
                  tooltip: '查房',
                  onClick: handleView.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <FormModal @register="registerModal" @success="handleSuccess" />
    <ViewDrawer @register="registerDrawerView" @success="handleSuccess" />
    <!-- <DatailModal @register="registerModalView" /> -->
  </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 { Icon } from '/@/components/Icon';
  import { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import { BasicTab, BasicTabActive, checkColumns } from './data';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';

  import {
    checkQueryCheckRoomRecord,
    checkQueryPersonNumber,
    checkFollowOrNo,
  } from '/@/api/biz/visit/checkApi';

  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';

  import { useMessage } from '/@/hooks/web/useMessage';

  //路由跳转

  const router = useRouter();
  const activeKey = ref(BasicTabActive);
  const tabData = ref(BasicTab);
  const [registerModal, { openModal }] = useModal();
  const [registerDrawerView, { openDrawer, openDrawer: openDrawerView }] = useDrawer();

  onMounted(async () => {
    const stats = await checkQueryPersonNumber();
    console.log('🚀 ~ file: index.vue:104 ~ onMounted ~ stats:', stats);
    tabData.value = tabData.value.map(ele => {
      if (ele.key == '0') {
        ele.value = stats.all;
      }
      if (ele.key == '1') {
        ele.value = stats.dialysisPatients;
      }
      if (ele.key == '2') {
        ele.value = stats.noDialysisPatients;
      }
      if (ele.key == '3') {
        ele.value = stats.newPatient;
      }
      if (ele.key == '4') {
        ele.value = stats.attention;
      }
      return ele;
    });
    console.log('🚀 ~ file: index.vue:118 ~ onMounted ~ tabData.value:', tabData.value);
  });
  const [registerTable, { reload }] = useTable({
    api: checkQueryCheckRoomRecord,
    // exportAuthList: ['sys:log:export'],
    rowKey: 'id',
    columns: checkColumns,
    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) {
    // data.forEach(item => {
    //   item.status = 2;
    // });
    return data;
  }

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

  //查房记录事件
  function handleDetail(record: Recordable) {
    router.push({
      path: '../../bizArchives/detail',
      query: {
        id: record.id,
        accessId: record.accessId,
        name: record.name,
        gender: record.gender,
        age: record.age,
      },
    });
  }

  const { createMessage } = useMessage();

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

  // 取消按钮事件
  async function handleCancel(record) {
    // clearSelectedRowKeys();
    await checkFollowOrNo(record.id);
    createMessage.success('操作成功！');
    await reload();
    // await getTab();
  }

  // 弹窗回调事件
  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,
      });
    }
  }
</script>

<style lang="less" scoped>
  .table-dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-right: 6px;
    border-radius: 50%;

    &hb--1 {
      background-color: #1bc1b3;
    }

    &--2 {
      background-color: #d3d8dd;
    }

    &--3 {
      background-color: #f7b500;
    }

    &--4 {
      background-color: #3cf;
    }
  }

  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }
</style>
