<template>
  <div class="m-4">
    <div>
      <XTTitle title="个人排班" />
      <div class="flex justify-between my-4">
        <XTTab
          type="illness"
          :width="170"
          :selected="activeKey"
          :data="tabData"
          @item-click="callTab"
        />
        <XTForm :form-data="formData" @change="callFormChange" />
      </div>
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'patientName'">
            <span :class="['table-dot', 'table-dot--' + record.status]" />
            <span :title="record.patientName">{{ record.patientName }}</span>
          </template>
          <template v-if="column.key === 'patientGender'">
            <span
              :style="{
                backgroundColor: formatDictColor(bizDictOptions.gender, record.patientGender),
                color: formatDictFontColor(bizDictOptions.gender, record.patientGender),
                padding: '1px 6px',
                borderRadius: '2px',
                marginRight: '4px',
              }"
            >
              {{ formatDictValue(bizDictOptions.gender, record.patientGender) }}
            </span>
          </template>
          <template v-if="column.key === 'patientType'">
            {{ formatDictValue(bizDictOptions.type, record.patientType) }}
          </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',
                }"
              >
                {{ formatDictValue(bizDictOptions.infectiousDiseases, item) }}
              </div>
            </div>
          </template> -->
          <template v-if="column.key === 'frequency'">
            <span v-if="record.frequency">
              {{ record.frequency?.times }}次/{{ record.frequency?.week }}周
            </span>
            <span v-else> 无 </span>
          </template>
          <template v-if="column.key === 'machine' && record.machine.length">
            <div class="flex">
              <div v-for="(item, index) in record.machine" :key="item" class="inline-flex">
                <i
                  v-if="item == 'pump_dual'"
                  class="mr-1 iconfont icon-xt-dual-pump_default color-man"
                />
                {{ formatDictValue(bizDictOptions.pump, item) }}
                <span v-if="index < record.machine.length - 1">、</span>
              </div>
            </div>
          </template>
          <template v-if="column.key === 'specialNeed'">
            <div class="flex table-special">
              <div class="inline-flex">
                {{ record.specialNeedWeek }}
              </div>
              <div class="divider" v-if="record.specialNeedSailingSorts?.length" />
              <div class="inline-flex"> {{ record.specialNeedSailingSorts }} </div>
            </div>
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  auth: 'bed:scheduledPerson:edit',
                  icon: 'icon-xt-details_edit_default|iconfont',
                  tooltip: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  auth: 'bed:scheduledPerson:query',
                  disabled: !record.frequency,
                  icon: 'icon-xt-bed_default|iconfont',
                  tooltip: '排班',
                  onClick: handleDetail.bind(null, record),
                },
                // {
                //   auth: 'sys:log:query',
                //   icon: 'icon-xt-details_delete_default|iconfont',
                //   tooltip: '删除',
                //   popConfirm: {
                //     title: '是否确认删除',
                //     placement: 'left',
                //     confirm: handleDelete.bind(null, record),
                //   },
                // },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
    <FormModalDetail @register="registerModalDetail" @success="callSuccess" />
  </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 { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import { BasicTab, BasicTabActive, BasicWeekEnum, columns } from './data';
  import { ref } from 'vue';
  import {
    bedScheduledPersonQueryPage,
    bedScheduledPersonStats,
    // bedScheduledPersonRemove,
  } from '/@/api/biz/bed/scheduledPersonApi';
  import { listDictModelBatch } from '@/api/common';
  import { formatDictColor, formatDictFontColor, formatDictValue } from '/@/utils';
  import { onMounted, reactive } from 'vue';
  import { useModal } from '/@/components/Modal';
  import FormModal from './FormModal.vue';
  import FormModalDetail from './FormModalDetail.vue';
  import { getSailings } from '/@/api/biz/management/working';

  // import { useMessage } from '@/hooks/web/useMessage';
  const bizDictOptions = reactive<any>({});
  const bizDictData = ref([
    { key: 'gender', dictCode: 'pb_sex' },
    { key: 'type', dictCode: 'pb_type' },
    { key: 'pump', dictCode: 'bm_pump' },
  ]);
  const activeKey = ref(BasicTabActive);
  const tabData = ref(BasicTab);
  const allSailings = ref([]);
  const [registerModal, { openModal }] = useModal();
  const [registerModalDetail, { openModal: openModalDetail }] = useModal();
  // const { createMessage } = useMessage();

  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 bedScheduledPersonStats();
    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.noneScheduled;
      }
      return ele;
    });

    // console.log('🚀 ~ file: index.vue:173 ~ onMounted ~ allSailings.value:', allSailings.value);
  });
  const [registerTable, { reload }] = useTable({
    api: bedScheduledPersonQueryPage,
    rowKey: 'id',
    columns,
    showIndexColumn: true,
    bordered: true,
    actionColumn: {
      width: 100,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
  });
  // 筛选数据
  const formData = ref([
    {
      name: 'tableSort',
      componentType: 'Select',
      placeholder: '请选择',
      width: 120,
      defaultValue: 'archivesCreateTime',
      dicts: [
        { label: '建档时间', value: 'archivesCreateTime' },
        { label: '按姓氏', value: 'patientNamePinyin' },
      ],
    },
    {
      name: 'patientName',
      componentType: 'Input',
      placeholder: '请输入患者姓名',
      prefix: 'icon-xt-search',
      width: 240,
    },
  ]);

  const formValue = reactive({
    patientName: '',
    tableSort: 'archivesCreateTime',
  }) as any;

  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    return {
      ...params,
      queryType: activeKey.value == '0' ? '0' : activeKey.value,
      patientName: formValue.patientName,
      orders: [{ field: formValue.tableSort, direction: 'DESC' }],
    };
  }

  async function handleAfterFetch(data) {
    console.log('🚀 ~ file: index.vue:238 ~ handleAfterFetch ~ data:', data);
    if (!allSailings.value.length) {
      allSailings.value = await getSailings();
    }
    const res = data.map(ele => {
      ele.specialNeedWeek = '';
      for (const i in ele.specialNeed) {
        if (ele.specialNeed[i] && i != 'sailingSorts') {
          ele.specialNeedWeek = ele.specialNeedWeek.concat('、', BasicWeekEnum[i]);
        }
      }
      ele.specialNeedWeek = ele.specialNeedWeek.substring(1);
      // ele.specialNeedSailingSorts = ele.specialNeed?.sailingSorts;
      // 班次需要请求
      ele.specialNeedSailingSorts = allSailings.value
        .filter(eleA => {
          return ele.specialNeed?.sailingSorts.includes(eleA.sort);
        })
        .map(sEle => {
          return sEle.name;
        })
        .join('、');
      return ele;
    });
    return res;
  }

  // 详情按钮事件
  function handleEdit(record: Recordable) {
    console.log('🚀 ~ file: index.vue:206 ~ handleView ~ record:', record);
    record.gender = formatDictValue(bizDictOptions.gender, record.patientGender);
    openModal(true, {
      isUpdate: true,
      record,
    });
  }
  function handleDetail(record: Recordable) {
    console.log('🚀 ~ file: index.vue:206 ~ handleView ~ record:', record);
    record.gender = formatDictValue(bizDictOptions.gender, record.patientGender);
    openModalDetail(true, {
      record,
    });
  }
  // 删除按钮事件
  // async function handleDelete(record: Recordable) {
  //   await bedScheduledPersonRemove([record.id]);
  //   createMessage.success('删除成功！');
  //   await reload();
  // }

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

  async function callFormChange(data) {
    formValue.patientName = data.patientName ? data.patientName : '';
    formValue.tableSort = data.tableSort ? data.tableSort : '';
    await reload();
  }
</script>

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

  .table-dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-right: 6px;
    border-radius: 50%;

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

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

  .divider {
    height: 16px;
    width: 1px;
    background-color: #ccc;
    margin: 4px 6px 0;
  }

  .table-special {
    width: 100%;
    white-space: break-spaces;
  }

  .table-special .table-special-item:last-of-type {
    color: red;
  }
</style>
