<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="id"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @update="handleStatus"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'nickname'">
              {{ record.nickname }}
            </template>
            <template v-if="column.key === 'checkDate'">
              <span
                :style="{color: record.checkDate ? (dayjs().diff(dayjs(record.checkDate), 'day') < 30 ? 'red' : 'black') : 'black'}">
                {{ record.checkDate }}</span>
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 0" color="green">闲置</a-tag>
              <a-tag v-if="record.status === 1" color="red">报废</a-tag>
              <a-tag v-if="record.status === 2" color="purple">注销</a-tag>
              <a-tag v-if="record.status === 3" color="orange">转卖</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此记录吗？"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <FallEdit v-model:visible="showEdit" :company-list="companys" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
import { createVNode, ref } from "vue";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import type { EleProTable } from "ele-admin-pro";
import type {
  DatasourceFunction,
  ColumnItem
} from "ele-admin-pro/es/ele-pro-table/types";
import { toDateString } from "ele-admin-pro";
import Search from "./components/search.vue";
import FallEdit from "./components/fall-edit.vue";
import {
  pageTowerFall,
  removeBatchTowerFall,
  updateBatchTowerFall
} from "@/api/tower/fall";
import { TowerFall, TowerFallParam } from "@/api/tower/fall/model";
import { pageCompany } from "@/api/system/company";
import { Customer } from "@/api/oa/customer/model";
import { Company } from "@/api/system/company/model";
import dayjs from "dayjs";

defineProps<{
  activeKey?: boolean;
  data?: any;
}>();

// 表格实例
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

// 表格列配置
const columns = ref<ColumnItem[]>([
  {
    key: "index",
    width: 48,
    align: "center",
    fixed: "left",
    hideInSetting: true,
    customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
  },
  // {
  //   title: '设备状态',
  //   dataIndex: 'status',
  //   key: 'status',
  //   customRender: ({ text }) => ['闲置', '报废', '注销', '转卖'][text]
  // },
  {
    title: "防坠器编号",
    dataIndex: "code",
    key: "code"
  },
  {
    title: "防坠器型号",
    dataIndex: "model",
    key: "model"
  },
  {
    title: "制造厂商",
    dataIndex: "factory",
    key: "factory"
  },
  {
    title: "产权单位",
    dataIndex: "companyName",
    key: "companyName"
  },
  {
    title: "出厂日期",
    dataIndex: "factoryDate",
    key: "factoryDate"
  },
  {
    title: "报废日期",
    dataIndex: "discardDate",
    key: "discardDate"
  },
  {
    title: "检测日期",
    dataIndex: "checkDate",
    key: "checkDate"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    align: "center",
    sorter: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: "操作",
    key: "action",
    width: 200,
    align: "center",
    hideInSetting: true
  }
]);

// 表格选中数据
const selection = ref<TowerFall[]>([]);
// 当前编辑数据
const current = ref<TowerFall | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
const companys = ref<Company[] | undefined>();
pageCompany({
  companyTypeMultiple: "产权单位"
}).then((res) => {
  companys.value = res?.list;
});
// 表格数据源
const datasource: DatasourceFunction = ({
                                          page,
                                          limit,
                                          where,
                                          orders,
                                          filters
                                        }) => {
  // 搜索条件
  if (filters.payMethod) {
    where.payMethod = filters.payMethod;
  }
  if (filters.deliveryType) {
    where.deliveryType = filters.deliveryType;
  }
  if (filters.payStatus) {
    where.payStatus = filters.payStatus;
  }
  if (filters.orderSource) {
    where.orderSource = filters.orderSource;
  }
  where.tenantId = localStorage.getItem("tenantId");
  where.payStatus = 20;
  return pageTowerFall({
    ...where,
    ...orders,
    page,
    limit
  });
};

/* 搜索 */
const reload = (where?: TowerFallParam) => {
  selection.value = [];
  tableRef?.value?.reload({ where: where });
};

/* 打开编辑弹窗 */
const openEdit = (row?: TowerFall) => {
  current.value = row ?? null;
  showEdit.value = true;
};
/* 删除单个 */
const remove = (row: TowerFall) => {
  const hide = message.loading("请求中..", 0);
  removeBatchTowerFall([row.id])
    .then((msg) => {
      hide();
      message.success(msg);
      reload();
    })
    .catch((e) => {
      hide();
      message.error(e.message);
    });
};
/* 批量修改 */
const handleStatus = (status) => {
  if (!selection.value.length) {
    message.error("请至少选择一条数据");
    return;
  }
  const data = selection.value.map((d) => {
    return {
      fallId: d.id,
      status
    };
  });
  console.log(data);
  updateBatchTowerFall(data).then((msg) => {
    message.success(msg);
    reload();
  });
};

/* 批量删除 */
const removeBatch = () => {
  if (!selection.value.length) {
    message.error("请至少选择一条数据");
    return;
  }
  Modal.confirm({
    title: "提示",
    content: "确定要删除选中的记录吗?",
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: () => {
      const hide = message.loading("请求中..", 0);
      removeBatchTowerFall(selection.value.map((d) => d.id))
        .then((msg) => {
          hide();
          message.success(msg);
          reload();
        })
        .catch((e) => {
          hide();
          message.error(e.message);
        });
    }
  });
};

/* 自定义行属性 */
const customRow = (record: TowerFall) => {
  return {
    // 行点击事件
    onClick: () => {
      // console.log(record);
    },
    // 行双击事件
    onDblclick: () => {
      openEdit(record);
    }
  };
};

reload();
</script>

<script lang="ts">
export default {
  name: "TowerFallIndex"
};
</script>

<style lang="less" scoped>
p {
  line-height: 0.8;
}

.sys-org-table :deep(.ant-table-body) {
  overflow: auto !important;
  overflow: overlay !important;
}

.sys-org-table :deep(.ant-table-pagination.ant-pagination) {
  padding: 0 4px;
  margin-bottom: 0;
}

.price-edit {
  padding-right: 5px;
}

.comments {
  max-width: 200px;
}
</style>
