<template>
  <div>
    <div class="flex justify-between mb-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>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'maintainCompany'">
          <span>{{ formatDictValue(bizDictOptions.dmc, record.maintainCompany) }}</span>
        </template>
        <template v-if="column.key === 'schedule'">
          <span>{{ formatDictValue(bizDictOptions.rp, record.schedule) }}</span>
        </template>
        <template v-if="column.key === 'picture'">
          <Image
            v-if="record.files && record.files.length > 0"
            :src="record.files[0].absolutePath"
            :width="60"
          />
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: 'archives:patrolWard:edit',
                icon: 'icon-xt-details_edit_default|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: 'archives:patrolWard:remove',
                icon: 'icon-xt-details_delete_default|iconfont',
                tooltip: '删除',
                popConfirm: {
                  title: '是否取消删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record, column),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="callSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, onMounted, reactive, ref } from 'vue';
  import { XTForm } from '/@/components/XTForm/index';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormModal from '../upkeepFormModal.vue';
  import Icon from '/@/components/Icon/index';
  import { columns } from './data';
  import { listDictModelBatch } from '/@/api/common';
  import { upkeepQueryPage, upkeepRemove } from '/@/api/biz/engineer/otherUpkeepApi';
  import { useModal } from '/@/components/Modal';
  import { Image } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { formatDictValue } from '/@/utils';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });

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

  const dictsOption = ref([]) as any;
  // formdata
  const formData = [
    {
      label: '保养厂商',
      name: 'maintainCompany',
      componentType: 'Select',
      dicts: dictsOption.value,
      placeholder: '请选择维修方',
      prefix: 'icon-xt-search',
      width: 280,
    },
    {
      name: 'patrolTime',
      label: '保养时间',
      componentType: 'RangePicker',
      placeholder: '请选择保养时间',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
  ];
  const formValue = reactive({
    patrolTime: [],
    maintainCompany: '',
  });

  const [registerTable, { reload }] = useTable({
    api: upkeepQueryPage,
    rowKey: 'id',
    columns,
    showIndexColumn: false,
    bordered: true,
    striped: false,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    sortFn: handleSortFn,
  });
  const bizDictData = ref([
    { key: 'dmc', dictCode: 'dmc' },
    { key: 'rp', dictCode: 'rp' },
  ]);

  const bizDictOptions = reactive<any>({});
  onBeforeMount(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 types = bizDictOptions.dmc;
    dictsOption.value.push({
      label: '全部',
      value: '',
    });
    types.forEach(item => {
      dictsOption.value.push({
        label: item.label,
        value: item.value,
      });
    });
  });
  onMounted(async () => {
    // callForm({
    //   patrolTime: [
    //     dayjs().subtract(3, 'month').format('YYYY-MM-DD'),
    //     dayjs().add(1, 'day').format('YYYY-MM-DD'),
    //   ],
    // });
  });
  // 新增按钮事件
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
      record: { id: props.info.id },
    });
  }

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

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    await upkeepRemove([record.id]);
    createMessage.success('删除成功！');
    await reload();
  }
  // 表格点击字段排序
  function handleSortFn(sortInfo) {
    if (sortInfo?.order && sortInfo?.columnKey) {
      // 默认单列排序
      tableSort.value = [
        {
          field: sortInfo.columnKey,
          direction: sortInfo.order.replace(/(\w+)(end)/g, '$1').toUpperCase(),
        },
      ];
    }
  }

  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    return {
      ...params,
      orders: tableSort.value,
      deviceId: props.info?.id,
      maintainTime:
        formValue.patrolTime && formValue.patrolTime.length > 0
          ? [
              formValue.patrolTime[0],
              dayjs(formValue.patrolTime[1]).add(1, 'day').format('YYYY-MM-DD'),
            ]
          : undefined,
      maintainCompany: formValue.maintainCompany,
    };
  }

  // 弹窗回调事件
  async function callSuccess() {
    await reload();
  }

  // 查询回调
  async function callForm(data) {
    formValue.maintainCompany = data.maintainCompany || '';
    formValue.patrolTime = data.patrolTime || [];
    await reload();
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }

  ::v-deep(.ant-input) {
    border-color: #c2ccd4;
    border-radius: 4px;
  }

  ::v-deep(.ant-input-affix-wrapper) {
    border-color: #c2ccd4;
    border-radius: 4px;
  }

  ::v-deep(.ant-picker) {
    border-color: #c2ccd4;
    border-radius: 4px;
  }

  ::v-deep(.ant-table-tbody > tr > td) {
    border-right: 0 !important;
    border-left: 0 !important;
    border-bottom: 1px solid #f0f0f0;
  }

  ::v-deep(.ant-table-wrapper table) {
    border: 0;
  }

  ::v-deep(.ant-table-cell-fix-right-first::after, .ant-table-cell-fix-right-last::after) {
    content: '';
    top: auto;
    width: 0;
  }

  .btn-add {
    width: 120px;
    border-radius: 4px;
  }
</style>
