<template>
  <div class="page">
    <a-page-header :ghost="false" title="商品管理">
      <div class="ele-text-secondary"> 商品管理，云芯威电池管理定制模块。 </div>
    </a-page-header>
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="goodsId"
          :columns="columns"
          :height="tableHeight"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
        >
          <template #toolbar>
            <search
              :selection="selection"
              @search="reload"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'equipmentCode'">
              <span>{{ record.equipmentCode }}</span>
            </template>
            <template v-if="column.key === 'goodsName'">
              <a-image :src="record.image" :preview="false" :width="50" />
              {{ record.goodsName }}
            </template>
            <template v-if="column.key === 'merchantName'">
              <div style="display: flex; flex-direction: column">
                <span>{{ record.merchantName }}</span>
                <span class="ele-text-placeholder">
                  {{ record.merchantCode }}
                </span>
              </div>
            </template>
            <template v-if="column.key === 'qrcode'">
              <a-image :src="record.qrcode" :width="50" />
            </template>
            <!--            <template v-if="column.key === 'batteryPrice'">-->
            <!--              <strong class="ele-text-danger">-->
            <!--                ￥{{ record.batteryPrice }}-->
            <!--              </strong>-->
            <!--            </template>-->
            <template v-if="column.key === 'batteryDeposit'">
              <strong class="ele-text-danger">
                ￥{{ record.batteryDeposit }}
              </strong>
            </template>
            <template v-if="column.key === 'batteryInsurance'">
              <strong class="ele-text-danger">
                ￥{{ record.batteryInsurance }}
              </strong>
            </template>
            <template v-if="column.key === 'isOnline'">
              <a-tag v-if="record.status === 0" color="green">正常</a-tag>
              <a-tag v-if="record.status === 1" color="orange">异常</a-tag>
            </template>
            <template v-if="column.key === 'equipmentCategory'">
              <a-tag
                v-if="Number(record.equipmentCategory) === 10"
                color="success"
                >销售</a-tag
              >
              <a-tag v-if="Number(record.equipmentCategory) === 20" color="red"
                >分期</a-tag
              >
              <a-tag
                v-if="Number(record.equipmentCategory) === 30"
                color="orange"
                >以租代购</a-tag
              >
              <a-tag v-if="Number(record.equipmentCategory) === 40" color="blue"
                >租赁</a-tag
              >
            </template>
            <template v-if="column.key === 'comments'">
              <a-tooltip :title="record.comments" placement="topLeft">
                {{ record.comments }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'sellingPoint'">
              <a-tooltip :title="record.sellingPoint" placement="topLeft">
                {{ record.sellingPoint }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'userId'">
              <a-tag v-if="record.userId > 0" color="green">已绑定</a-tag>
              <a-tag v-else color="orange">未绑定</a-tag>
            </template>
            <template v-if="column.key === 'createTime'">
              <a-tooltip :title="`${toDateString(record.createTime)}`">
                {{ timeAgo(record.createTime) }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'batteryPrice'">
              <div class="ele-text-placeholder">
                价格：<span class="ele-text-heading"
                  >￥{{ record.batteryPrice }}</span
                >
              </div>
              <div class="ele-text-placeholder">
                租金：<span class="ele-text-heading"
                  >￥{{ record.batteryRent }}</span
                >
              </div>
              <div class="ele-text-placeholder">
                押金：<span class="ele-text-heading"
                  >￥{{ record.batteryDeposit }}</span
                >
              </div>
              <div class="ele-text-placeholder">
                保险：<span class="ele-text-heading"
                  >￥{{ record.batteryInsurance }}</span
                >
              </div>
            </template>
            <template v-if="column.key === 'more'">
              <div v-if="record.periodsType > 0">
                <span class="ele-text-placeholder">分期方式：</span>
                {{ record.periodsType === 0 ? '周' : '月' }}
              </div>
              <div v-if="record.periods > 0">
                <span class="ele-text-placeholder">分期期数：</span>
                {{ record.periods }}
              </div>
              <div v-if="record.downPayment">
                <span class="ele-text-placeholder">首付款：</span>
                {{ record.downPayment }}
              </div>
              <div v-if="record.repayment > 0">
                <span class="ele-text-placeholder">每期还款：</span>
                {{ record.repayment }}
              </div>
              <div v-if="record.serviceCharges > 0">
                <span class="ele-text-placeholder">手续费：</span>
                {{ record.serviceCharges }}
              </div>
            </template>
            <template v-if="column.key === 'status'">
              <a-button
                type="link"
                @click="onStatus(record.goodsId, 1)"
                v-if="record.status === 0"
                class="ele-text-success"
                >已上架</a-button
              >
              <a-button type="link" @click="onStatus(record.goodsId, 0)" v-else
                >已下架</a-button
              >
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button @click="openEdit(record)">修改</a-button>
                <!--                <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>
      <!-- 编辑弹窗 -->
      <equipment-goods-edit
        v-model:visible="showEdit"
        :data="current"
        @done="reload"
      />
    </div>
  </div>
</template>

<!--suppress TypeScriptValidateTypes -->
<script lang="ts" setup>
  import { timeAgo } from 'ele-admin-pro';
  import { createVNode, computed, 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 EquipmentGoodsEdit from './components/equipment-goods-edit.vue';
  import {
    pageEquipmentGoods,
    removeBatchEquipmentGoods,
    updateEquipmentGoods
  } from '@/api/apps/equipment/goods';
  import type {
    EquipmentGoods,
    EquipmentGoodsParam
  } from '@/api/apps/equipment/goods/model';

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

  // 当前用户信息
  // const brand = getDictionaryOptions('serverBrand');

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    // {
    //   key: 'index',
    //   width: 48,
    //   align: 'center',
    //   fixed: 'left',
    //   hideInSetting: true,
    //   customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    // },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'left',
      align: 'center',
      hideInSetting: true
    },
    {
      title: '商品ID',
      dataIndex: 'goodsId',
      key: 'goodsId',
      width: 70,
      fixed: 'left'
    },
    {
      title: '下单方式',
      dataIndex: 'equipmentCategory',
      width: 100,
      key: 'equipmentCategory'
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 180,
      ellipsis: true,
      key: 'goodsName',
      fixed: 'left'
    },
    // {
    //   title: '商品图片',
    //   dataIndex: 'image',
    //   key: 'image'
    // },
    // {
    //   title: '二维码',
    //   dataIndex: 'qrcode',
    //   key: 'qrcode'
    // },
    {
      title: '所属商户',
      dataIndex: 'merchantName',
      key: 'merchantName'
    },
    {
      title: '电池型号',
      dataIndex: 'batteryModel',
      sorter: true,
      ellipsis: true
    },
    {
      title: '电池价格',
      dataIndex: 'batteryPrice',
      sorter: true,
      key: 'batteryPrice'
    },
    // {
    //   title: '电池租金',
    //   dataIndex: 'batteryRent',
    //   key: 'batteryRent'
    // },
    // {
    //   title: '电池押金',
    //   dataIndex: 'batteryDeposit',
    //   sorter: true,
    //   key: 'batteryDeposit'
    // },
    // {
    //   title: '电池保险',
    //   dataIndex: 'batteryInsurance',
    //   sorter: true,
    //   key: 'batteryInsurance'
    // },
    {
      title: '分期方案',
      dataIndex: 'more',
      key: 'more'
    },
    {
      title: '商品卖点',
      dataIndex: 'sellingPoint',
      key: 'sellingPoint',
      ellipsis: true,
      hideInTable: true
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      align: 'center',
      sorter: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      sorter: true,
      align: 'center',
      key: 'status',
      fixed: 'right',
      customRender: ({ text }) => ['上架', '下架'][text]
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    }
  ]);

  // 表格选中数据
  const selection = ref<EquipmentGoods[]>([]);
  // 当前编辑数据
  const current = ref<EquipmentGoods | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 树形数据
  // const data = ref<Category[]>([]);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // if (filters) {
    //   where.brand = filters.brand;
    // }
    return pageEquipmentGoods({ ...where, ...orders, ...filters, page, limit });
  };

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

  // 搜索是否展开
  const searchExpand = ref(false);

  // 表格固定高度
  const fixedHeight = ref(false);

  // 表格高度
  const tableHeight = computed(() => {
    return fixedHeight.value
      ? searchExpand.value
        ? 'calc(100vh - 618px)'
        : 'calc(100vh - 562px)'
      : void 0;
  });

  /* 打开编辑弹窗 */
  const openEdit = (row?: EquipmentGoods) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const onStatus = (goodsId, status) => {
    updateEquipmentGoods({ goodsId, status }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

  /* 打开用户详情弹窗 */
  // const openInfo = (row?: EquipmentGoods) => {
  //   current.value = row ?? null;
  //   showEdit.value = true;
  // };

  /* 删除单个 */
  // const remove = (row: EquipmentGoods) => {
  //   const hide = message.loading('请求中..', 0);
  //   removeEquipmentGoods(row.equipmentId)
  //     .then((msg) => {
  //       hide();
  //       message.success(msg);
  //       reload();
  //     })
  //     .catch((e) => {
  //       hide();
  //       message.error(e.message);
  //     });
  // };

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

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

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

<style lang="less" scoped>
  // 文字超出隐藏(两行)
  // 需要设置文字容器的宽度
  .twoline-hide {
    width: 320px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    white-space: normal;
  }
</style>
