<template>
  <div class="m-4">
    <div>
      <XTTitle title="透析设备" :right-data="titleData" @click="callTitleClick" />
      <div class="flex justify-between my-4">
        <XTTab
          type="illness"
          :width="136"
          :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 === 'birthday'">
            {{ record.birthday ? dayjs(record.birthday).format('YYYY-MM-DD') : '' }}
          </template>
          <template v-if="column.key === 'firstDialysisTime'">
            {{
              record.firstDialysisTime ? dayjs(record.firstDialysisTime).format('YYYY-MM-DD') : ''
            }}
          </template>
          <template v-if="column.key === 'gender'">
            <span
              :style="{
                backgroundColor: formatDictColor(bizDictOptions.gender, record.gender),
                color: formatDictFontColor(bizDictOptions.gender, record.gender),
                padding: '1px 6px',
                borderRadius: '2px',
                marginRight: '4px',
              }"
            >
              {{ formatDictValue(bizDictOptions.gender, record.gender) }}
            </span>
          </template>
          <template v-if="column.key === 'firstDialysisType'">
            {{ formatDictValue(bizDictOptions.firstDialysisType, record.firstDialysisType) }}
          </template>
          <template v-if="column.key === 'type'">
            {{ formatDictValue(bizDictOptions.type, record.type) }}
          </template>
          <template v-if="column.key === 'infectiousDiseases'">
            <div class="flex">
              <div
                v-for="item in record.infectiousDiseases"
                :key="item"
                :style="{
                  backgroundColor: formatDictColor(bizDictOptions.infectiousDiseases, item),
                  color: formatDictFontColor(bizDictOptions.infectiousDiseases, item),
                  padding: '1px 6px',
                  borderRadius: '2px',
                  marginRight: '4px',
                }"
              >
                <!-- {{ record.infectiousDiseases }} -->
                {{ formatDictValue(bizDictOptions.infectiousDiseases, item) }}
              </div>
            </div>
          </template>
          <template v-if="column.key === 'vascularAccess'">
            {{ formatDictValue(bizDictOptions.vascularAccess, record.vascularAccess) }}
          </template>
          <template v-if="column.key === 'patientReturn'">
            {{ formatDictValue(bizDictOptions.patientReturn, record.patientReturn) }}
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  auth: 'archives:patientBasic:query',
                  icon: 'icon-xt-medical_default|iconfont',
                  tooltip: '详情',
                  label: '详情',
                  onClick: handleView.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
    <FormDrawerSift @register="registerDrawer" @success="callSift" />
  </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, siftFormSchema } from './data';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { archivesPatientBasicStats } from '/@/api/biz/archives/patientBasicApi';
  import { engineerDialysisDeviceQueryPage } from '@/api/biz/engineer/dialysisDeviceApi';
  import { listDictModelBatch } from '@/api/common';
  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 FormDrawerSift from './FormDrawerSift.vue';
  import { useDrawer } from '@/components/Drawer';

  const bizDictOptions = reactive<any>({});
  const bizDictData = ref([
    // 血管材料
    { key: 'gender', dictCode: 'pb_sex' },
    // 转归类型
    { key: 'patientReturn', dictCode: 'pb_return' },
    // 传染病
    { key: 'infectiousDiseases', dictCode: 'pb_epidemic' },
    // 患者类型
    { key: 'type', dictCode: 'pb_type' },
    // 通路类型
    { key: 'vascularAccess', dictCode: 'va_type' },
    // 转归原因
    { key: 'return', dictCode: 'va_return' },
    // 首次透析方式
    { key: 'firstDialysisType', dictCode: 'dt' },
  ]);
  // 路由跳转
  const router = useRouter();
  const activeKey = ref(BasicTabActive);
  const tabData = ref(BasicTab);
  const [registerModal, { openModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();

  onMounted(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 stats = await archivesPatientBasicStats();
    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.newPatient;
      }
      if (ele.key == '2') {
        ele.value = stats.noneFormulate;
      }
      if (ele.key == '3') {
        ele.value = stats.positive;
      }
      return ele;
    });
    console.log('🚀 ~ file: index.vue:118 ~ onMounted ~ tabData.value:', tabData.value);
  });
  const [registerTable, { reload }] = useTable({
    api: engineerDialysisDeviceQueryPage,
    exportAuthList: ['sys:log:export'],
    rowKey: 'id',
    columns,
    showIndexColumn: false,
    bordered: true,
    actionColumn: {
      width: 100,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
  });
  // 筛选数据
  const siftData = ref([]);
  // 标题数据
  const titleData = [
    {
      type: 'import',
      icon: 'icon-xt-import_default',
    },
    {
      type: 'add',
      btnIcon: 'icon-xt-add_default',
      btnText: '新增设备',
    },
  ];

  const formData = ref([
    {
      name: 'name',
      componentType: 'Input',
      placeholder: '请输入设备编号',
      prefix: 'icon-xt-search',
      width: 240,
    },
    {
      name: 'filter',
      componentType: 'IconBtn',
      count: 0,
    },
  ]);

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

  // const tableSort = ref([
  //   {
  //     field: 'create_time',
  //     direction: 'DESC',
  //   },
  // ]) 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;
    });
    if (params?.order) {
      params.orders = [
        {
          field: params.field,
          direction: params.order.substring(0, params.order.length - 3).toUpperCase(),
        },
      ];
      delete params.order;
      delete params.field;
    }
    return {
      ...params,
      queryType: activeKey.value == '0' ? '0' : activeKey.value,
      name: formValue.name,
      ...sift,
    };
  }

  function handleAfterFetch(data) {
    return data;
  }

  // 详情按钮事件
  function handleView(record: Recordable) {
    router.push({
      path: '/bizArchives/detail',
      query: {
        id: record.id,
        accessId: record.accessId,
        name: record.name,
        gender: formatDictValue(bizDictOptions.gender, record.gender),
        age: record.age,
      },
    });
  }

  // 弹窗回调事件
  async function callSuccess({ 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') {
      openModal(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 callSift(data) {
    siftData.value = [];
    for (const i in data) {
      if (data[i]) {
        siftFormSchema.forEach(ele => {
          // console.log('🚀 ~ file: index.vue:280 ~ obj ~ ele:', ele);
          if (ele.field == i) {
            siftData.value.push({
              field: ele.field,
              label: ele.label,
              value: ele.component.includes('Api')
                ? formatDictValue(bizDictOptions.gender, data[i])
                : data[i],
              isDict: ele.component.includes('Api'),
              dict: ele.component.includes('Api') ? data[i] : '',
            });
          }
          formData.value[formData.value.length - 1]['count'] = siftData.value.length;
        });
      }
    }
    await reload();
  }

  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;
      });
    }
    formData.value[formData.value.length - 1]['count'] = siftData.value.length;
    await reload();
  }
</script>

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

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

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

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

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