<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" />
      </div>
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <span :class="['table-dot', 'table-dot--' + record.status]" />
            <span :title="record.name">{{ record.name }}</span>
          </template>
          <template v-if="column.dataIndex === 'updatorName'">
            <Image
              v-if="record.updateAvatar"
              :src="record.updateAvatar"
              style="width: 20; height: 20px"
            />
            {{ record.updatorName }}
          </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),
                },
                {
                  auth: 'archives:patrolWard:edit',
                  tooltip: '编辑',
                  label: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  auth: 'archives:patrolWard:followOrNo',
                  tooltip: '关注',
                  label: '关注',
                  ifShow: record.status > 1,
                  popConfirm: {
                    title: '是否确定要关注？',
                    placement: 'left',
                    confirm: handleCancel.bind(null, record),
                  },
                },
                {
                  auth: 'archives:patrolWard:followOrNo',
                  tooltip: '取消关注',
                  label: '取消关注',
                  ifShow: record.status == 1,
                  popConfirm: {
                    title: '是否确定要取消关注？',
                    placement: 'left',
                    confirm: handleClick.bind(null, record),
                  },
                },
              ]"
              :actions="[
                {
                  auth: 'archives:patrolWard:query',
                  icon: 'icon-xt-ward_default|iconfont',
                  tooltip: '查房',
                  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 { Icon } from '/@/components/Icon';
  import { Image } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import { checkColumns, BasicTabActive, BasicTab } 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 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 () => {
    getTab();
    console.log('🚀 ~ file: index.vue:118 ~ onMounted ~ tabData.value:', tabData.value);
  });
  const [registerTable, { reload, clearSelectedRowKeys }] = 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: 'st_patrol_time',
      dicts: [
        { label: '按查房时间', value: 'st_patrol_time' },
        { label: '按姓氏', value: 'st_family_name' },
      ],
    },
    {
      name: 'name',
      componentType: 'Input',
      placeholder: '请输入患者姓名',
      width: 200,
      prefix: 'icon-xt-search',
    },
  ];

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

  async function getTab() {
    const personNumber = await checkQueryPersonNumber();
    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.attention;
      }
      if (ele.key == '2') {
        ele.value = personNumber.newPatient;
      }
      if (ele.key == '3') {
        ele.value = personNumber.dialysisPatients;
      }
      if (ele.key == '4') {
        ele.value = personNumber.noDialysisPatients;
      }
      return ele;
    });
  }
  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    return {
      ...params,
      patientType: activeKey.value == '0' ? '0' : activeKey.value,
      name: formValue.name,
      orders: [],
      sortType: formValue.tableSort,
    };
  }
  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,
        activeKeys: 5,
      },
    });
  }

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

  // 取消按钮事件
  const { createMessage } = useMessage();
  async function handleCancel(record: Recordable) {
    await checkFollowOrNo(record.patientBasicId);
    createMessage.success('关注成功！');
    clearSelectedRowKeys();
    await getTab();
    await reload();
  }
  async function handleClick(record: Recordable) {
    await checkFollowOrNo(record.patientBasicId);
    createMessage.success('取消关注成功！');
    clearSelectedRowKeys();
    await getTab();
    await reload();
  }

  // 弹窗回调事件
  async function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    await getTab();
    await reload();
  }
  // 回调
  async function callTab(data) {
    activeKey.value = data.value;
    await getTab();
    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 : '';
    //   formValue.patientName = data.patientName ? data.patientName : '';
    formValue.tableSort = data.tableSort ? data.tableSort : '';
    await getTab();
    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%;

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

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

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

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

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