<template>
  <div class="m-4 modals">
    <div>
      <div class="flex items-center justify-between my-4">
        <div>
          <a-button type="primary" size="large" class="btn-add" @click="handleCreate"
            ><template #icon> <Icon icon="icon-xt-add_default|iconfont" /> </template
            >新增检测</a-button
          >
        </div>
        <div>
          <XTForm :form-data="formData" @change="callForm" />
        </div>
      </div>
    </div>
    <BasicTable @register="registerTable">
      <template #headerCell="{ column }">
        <template v-if="column.key === 'deviceUniqueCode'">
          <span>设备编号</span>
        </template>
        <template v-if="column.key === 'deviceManufacturer'">
          <span>设备厂家</span>
        </template>
        <template v-if="column.key === 'deviceSerialNumber'">
          <span>设备型号</span>
        </template>
        <template v-if="column.key === 'detectionTime'">
          <span>检测时间</span>
        </template>

        <template v-if="column.key === 'intakeBacteria'">
          <span>进水口细菌(cfu/ml)<br />正常值≤100<br />干预值＞50</span>
        </template>
        <template v-if="column.key === 'intakeEndotoxin'">
          <span>进水口内毒素(Eu/ml)<br />正常值≤0.5<br />干预值＞0.25</span>
        </template>
        <template v-if="column.key === 'outletBacteria'">
          <span>出水口细菌(cfu/ml)<br />正常值≤100<br />干预值＞50</span>
        </template>
        <template v-if="column.key === 'outletEndotoxin'">
          <span>出水口内毒素(Eu/ml)<br />正常值≤0.5<br />干预值＞0.25</span>
        </template>
        <template v-if="column.key === 'action'">
          <span>操作</span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'disable'">
          <span
            :class="['table-dot']"
            :style="{ backgroundColor: formatDictPreColor(responseTypeOptions, record.disable) }"
          />
          <span> {{ formatDictValue(responseTypeOptions, record.disable) }}</span>
        </template>
        <template v-if="column.key === 'supplierCategory'">
          <span>
            {{ formatDictValue(responsesupplierCategoryOptions, record.supplierCategory) }}</span
          >
        </template>
        <template v-if="column.key === 'intakeBacteria'">
          <span v-if="record.intakeBacteriaStatus === '0'">{{ record.intakeBacteria }}</span>
          <span v-else :class="record.intakeBacteriaStatus === '2' ? 'upStatus' : 'downStatus'">{{
            record.intakeBacteria
          }}</span>
        </template>
        <template v-if="column.key === 'intakeEndotoxin'">
          <span v-if="record.intakeEndotoxinStatus === '0'">{{ record.intakeEndotoxin }}</span>
          <span v-else :class="record.intakeEndotoxinStatus === '2' ? 'upStatus' : 'downStatus'">{{
            record.intakeEndotoxin
          }}</span>
        </template>
        <template v-if="column.key === 'outletBacteria'">
          <span v-if="record.outletBacteriaStatus === '0'">{{ record.outletBacteria }}</span>
          <span v-else :class="record.outletBacteriaStatus === '2' ? 'upStatus' : 'downStatus'">{{
            record.outletBacteria
          }}</span>
        </template>
        <template v-if="column.key === 'outletEndotoxin'">
          <span v-if="record.outletEndotoxinStatus === '0'">{{ record.outletEndotoxin }}</span>
          <span v-else :class="record.outletEndotoxinStatus === '2' ? 'upStatus' : 'downStatus'">{{
            record.outletEndotoxin
          }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: 'biz:consumable:edit',
                icon: 'icon-xt-details_edit_default|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="callSuccess" @cancel="handleCancel" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import FormModal from './formModal.vue';
  import Icon from '/@/components/Icon';
  import { formatDictValue, formatDictPreColor } from '/@/utils';
  import { columns } from './data';
  import { microbialDetectionWaterQueryPage } from '/@/api/biz/bio/microbialDetectionWaterApi';
  import { listDictModel } from '/@/api/common';
  import { useModal } from '/@/components/Modal';
  import { XTForm } from '/@/components/XTForm/index';
  import dayjs from 'dayjs';

  // formdata
  const formData = [
    {
      label: '检测时间：',
      name: 'shiftDate',
      componentType: 'RangePicker',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      placeholder: '请选择日期',
      width: 240,
    },
    {
      name: 'searchNames',
      componentType: 'Input',
      prefix: 'icon-xt-search',
      placeholder: '请输入设备编号',
      width: 240,
    },
  ];
  // tab 切换选中
  const tabSelected = ref();
  // 操作名称
  const searchNames = ref('');
  const shiftDate = ref([]);

  const responseTypeOptions = ref();
  const responsesupplierCategoryOptions = ref();
  onBeforeMount(async () => {
    responseTypeOptions.value = await listDictModel({ dictCode: 'sys_disable_type' });
    responsesupplierCategoryOptions.value = await listDictModel({ dictCode: 'pht' });
  });

  const [registerModal, { openModal }] = useModal();

  const tableSort = ref([
    {
      field: 'create_time',
      direction: 'DESC',
    },
  ]) as any;

  const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
    api: microbialDetectionWaterQueryPage,
    rowKey: 'id',
    columns,
    showIndexColumn: false,
    bordered: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    sortFn: handleSortFn,
  });
  // 详情按钮事件
  function handleEdit(record) {
    openModal(true, {
      isUpdate: true,
      record,
    });
  }

  // 表格点击字段排序
  function handleSortFn(sortInfo) {
    if (sortInfo?.order && sortInfo?.columnKey) {
      // 默认单列排序
      tableSort.value = [
        {
          field: sortInfo.columnKey,
          direction: sortInfo.order.replace(/(\w+)(end)/g, '$1').toUpperCase(),
        },
      ];
    }
  }

  // 表格请求之前，对参数进行处理, 添加默认 排序
  async function handleBeforeFetch(params) {
    const shiftTimes = [];
    if (shiftDate.value && shiftDate.value.length > 0) {
      shiftTimes.push(shiftDate.value[0]);
      shiftTimes.push(shiftDate.value[1]);
      shiftTimes[1] = dayjs(shiftTimes[1]).add(1, 'day').format('YYYY-MM-DD');
    }
    return {
      ...params,
      orders: tableSort.value,
      name: searchNames.value == '' ? undefined : searchNames.value,
      status: tabSelected.value == '' ? undefined : tabSelected.value,
      time: shiftTimes.length <= 0 ? undefined : shiftTimes,
    };
  }

  // 新增按钮事件
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  //取消按钮事件
  async function handleCancel() {
    clearSelectedRowKeys();
    await reload();
  }

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

  // 查询组件回调
  async function callForm(data) {
    shiftDate.value = data.shiftDate ? data.shiftDate : '';
    searchNames.value = data.searchNames ? data.searchNames : '';
    console.log('callForm:::', searchNames.value);
    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: #3d4155;
  }

  ::v-deep(.ant-input-prefix) {
    color: #8a99ac;
  }

  .colUpdateAvatar {
    display: flex;
    justify-content: center;
    text-align: center;
    line-height: 28px;
  }

  .colImg {
    width: 28px;
    height: 28px;
    margin-right: 5px;
  }

  .upStatus {
    color: #ff5d39;
  }

  .downStatus {
    color: #ffad26;
  }
</style>
