<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 === 'useDate'">
            {{ record.useDate ? dayjs(record.useDate).format('YYYY-MM-DD') : '' }}
          </template>
          <template v-if="column.key === 'produceDate'">
            {{ record.produceDate ? dayjs(record.produceDate).format('YYYY-MM-DD') : '' }}
          </template>
          <template v-if="column.key === 'pumpType'">
            {{ formatDictValue(bizDictOptions.pumpType, record.pumpType) }}
          </template>
          <template v-if="column.key === 'deviceType'">
            <span
              :class="['table-dot']"
              :style="{
                backgroundColor: formatDictPreColor(bizDictOptions.deviceType, record.deviceType),
              }"
            />
            {{ formatDictValue(bizDictOptions.deviceType, record.deviceType) }}
          </template>
          <template v-if="column.key === 'infectiousDiseases'">
            <div class="flex">
              <div
                :style="{
                  backgroundColor: formatDictColor(
                    bizDictOptions.infectiousDiseases,
                    record.infectiousDiseases,
                  ),
                  color: formatDictFontColor(
                    bizDictOptions.infectiousDiseases,
                    record.infectiousDiseases,
                  ),
                  padding: '1px 6px',
                  borderRadius: '2px',
                  marginRight: '4px',
                }"
              >
                {{ formatDictValue(bizDictOptions.infectiousDiseases, record.infectiousDiseases) }}
              </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,
    formatDictPreColor,
  } 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: 'pumpType', dictCode: 'bm_pump' },
    // 设备类型
    { key: 'deviceType', dictCode: 'bm_det' },
    // 传染病类型
    { key: 'infectiousDiseases', dictCode: 'pb_epidemic' },
  ]);
  // 路由跳转
  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: '/bizEngineer/dialysisDevices/details',
      query: {
        id: record.id,
        name: record.name,
      },
    });
  }

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

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