<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="`80%`"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑订单' : '订单详情'"
    :body-style="{ paddingBottom: '8px', background: '#f3f3f3' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    :footer="null"
    @ok="save"
  >
    <a-card class="order-card" :bordered="false">
      <a-steps
        :current="active"
        direction="horizontal"
        :responsive="styleResponsive"
      >
        <template v-for="(item, index) in steps" :key="index">
          <a-step
            :title="item.title"
            :description="timeAgo(item.description)"
          />
        </template>
      </a-steps>
    </a-card>
    <a-card title="订单操作" class="order-card">
      <a-space>
        <a-button>发货</a-button>
        <a-button>商家备注</a-button>
        <a-button>打印小票</a-button>
      </a-space>
      <a-row :gutter="16" style="margin-top: 34px">
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="订单编号" name="orderNo">
            <span>{{ data.orderNo }}</span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="实付款金额" name="payPrice">
            <span class="ele-text-warning">￥{{ formatNumber(data.payPrice) }}</span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="支付方式" name="payMethod">
            <Tag dict-code="payMethod" v-model:value="data.payMethod" />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="配送方式" name="deliveryType">
            <Tag dict-code="deliveryType" v-model:value="data.deliveryType" />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="运费金额" name="deliveryType">
            <span>￥{{ formatNumber(data.expressPrice) }}</span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="订单状态" name="orderStatus">
            <Tag dict-code="orderStatus" v-model:value="data.orderStatus" />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="买家信息" name="deliveryType">
            <router-link :to="'/system/user/details?id=' + data.userId">
              <span class="ele-text-primary">{{ data.nickname }}</span>
            </router-link>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="第三方交易号" name="tradeId">
            <span>{{ data.tradeId }}</span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="设备编号" name="equipmentCode">
            <span>
              {{ bindEquipmentCode }}
              <copy-outlined
                style="padding-left: 4px"
                @click="copyText(bindEquipmentCode)"
              />
            </span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="下单时间" name="createTime">
            {{ data.createTime }}
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="到期时间" name="expirationTime">
            {{ data.expirationTime }}
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="买家留言" name="buyerRemark">
            <span>{{ data.buyerRemark }}</span>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="订单备注" name="comments">
            <span>{{ data.comments }}</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-card>
    <a-card title="订单商品" class="order-card">
      <a-spin :spinning="loading">
        <a-table
          :data-source="EquipmentOrderGoodsList"
          :columns="columns"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'goodsName'">
              <a-image
                v-if="record.image"
                :src="record.image"
                :preview="false"
                :width="50"
              />
              <span>{{ record.goodsName }}</span>
            </template>
            <template v-if="column.key === 'batteryRent'">
              <div>电池租金：￥{{ record.batteryRent }}</div>
              <div>电池押金：￥{{ record.batteryDeposit }}</div>
              <div>电池保险：￥{{ record.batteryInsurance }}</div>
            </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 === '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>
        </a-table>
      </a-spin>
    </a-card>
    <a-card title="换电记录" class="order-card">
      <a-spin :spinning="loading">
        <a-table
          :data-source="equipmentRecordList"
          :columns="columns3"
          ref="tableRef3"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'batteryModel'">
              <div>电池租金：￥{{ record.batteryDeposit }}</div>
              <div>电池押金：￥{{ record.batteryDeposit }}</div>
              <div>电池保险：￥{{ record.batteryInsurance }}</div>
            </template>
            <template v-if="column.key === 'expirationDay'">
              <span class="ele-text-danger">{{ expirationDay(record) }}</span>
            </template>
          </template>
        </a-table>
      </a-spin>
    </a-card>
    <a-card title="续费订单" class="order-card">
      <a-spin :spinning="loading">
        <a-table
          :data-source="renewOrderList"
          :columns="columns2"
          ref="tableRef2"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'batteryModel'">
              <div>电池租金：￥{{ record.batteryDeposit }}</div>
              <div>电池押金：￥{{ record.batteryDeposit }}</div>
              <div>电池保险：￥{{ record.batteryInsurance }}</div>
            </template>
            <template v-if="column.key === 'expirationTime'">
              <div>{{ record.startTime }}</div>
              <div>{{ record.expirationTime}}</div>
            </template>
            <template v-if="column.key === 'expirationDay'">
              <span class="ele-text-danger">{{ expirationDay(record) }}</span>
            </template>
          </template>
        </a-table>
      </a-spin>
    </a-card>
    <a-card title="订单附件" class="order-card">
      <a-spin :spinning="loading">
        <ele-image-upload
          v-model:value="files"
          disabled
          :item-style="{ width: '150px', height: '99px' }"
        />
      </a-spin>
    </a-card>
    <a-card title="买家收货地址" class="order-card">
      <a-row :gutter="16">
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="收货人姓名" name="orderNo">
            <router-link :to="'/system/user/details?id=' + data.userId">
              <span class="ele-text-primary">{{ data.nickname }}</span>
            </router-link>
          </a-form-item>
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="联系电话" name="payPrice" />
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="所在地区" name="payMethod" />
        </a-col>
        <a-col
          v-bind="
            styleResponsive
              ? { xl: 8, lg: 12, md: 12, sm: 24, xs: 24 }
              : { span: 8 }
          "
        >
          <a-form-item label="详细地址" name="payMethod" />
        </a-col>
      </a-row>
    </a-card>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form } from 'ant-design-vue';
  import { assignObject, EleProTable, timeAgo } from 'ele-admin-pro';
  import { useThemeStore } from '@/store/modules/theme';
  import { formatNumber } from 'ele-admin-pro/es';
  import { storeToRefs } from 'pinia';
  import { copyText } from '@/utils/common';
  import { Order } from '@/api/order/model';
  import { listEquipmentOrderGoods } from '@/api/apps/equipment/order/goods';
  import { EquipmentOrderGoods } from '@/api/apps/equipment/order/goods/model';
  import * as EquipmentApi from '@/api/apps/equipment';
  import * as EquipmentRecordApi from '@/api/apps/equipment/record';
  import { ColumnItem } from 'ele-admin-pro/es/ele-pro-table/types';
  import { listOrder } from '@/api/order';
  import { CopyOutlined } from '@ant-design/icons-vue';
  import { EquipmentRecord } from '@/api/apps/equipment/record/model';

  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Order | null;
  }>();

  export interface step {
    title?: String | undefined;
    subTitle?: String | undefined;
    description?: String | undefined;
  }

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const EquipmentOrderGoodsList = ref<EquipmentOrderGoods[]>([]);
  const renewOrderList = ref<Order[]>([]);
  const equipmentRecordList = ref<EquipmentRecord[]>([]);
  const bindEquipmentCode = ref<string>();
  const files = ref<any[]>();

  // 步骤条
  const steps = ref<step[]>([
    {
      title: '下单',
      description: undefined
    },
    {
      title: '付款',
      description: undefined
    },
    {
      title: '发货',
      description: undefined
    },
    {
      title: '收货',
      description: undefined
    },
    {
      title: '完成',
      description: undefined
    }
  ]);
  const active = ref(2);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 订单信息
  const order = reactive<Order>({
    orderId: undefined,
    orderNo: '',
    userId: undefined,
    orderSourceData: ''
  });

  // 请求状态
  const loading = ref(true);

  const { resetFields } = useForm(order);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const columns = ref<ColumnItem[]>([
    // {
    //   title: '商品ID',
    //   dataIndex: 'goodsId'
    // },
    {
      title: '商品信息',
      dataIndex: 'goodsName',
      key: 'goodsName'
    },
    {
      title: '下单方式',
      dataIndex: 'equipmentCategory',
      key: 'equipmentCategory'
    },
    {
      title: '电池型号',
      dataIndex: 'batteryModel',
      key: 'batteryModel'
    },
    {
      title: '电池价格',
      dataIndex: 'batteryPrice',
      key: 'batteryPrice',
      customRender: ({ text }) => '￥' + text
    },
    {
      title: '电池租金',
      dataIndex: 'batteryRent',
      key: 'batteryRent',
      customRender: ({ text }) => '￥' + text
    },
    {
      title: '分期方案',
      dataIndex: 'more',
      key: 'more'
    },
    {
      title: '购买数量',
      dataIndex: 'num',
      key: 'num',
      customRender: ({}) => 1
    }
  ]);

  // 表格实例
  const tableRef2 = ref<InstanceType<typeof EleProTable> | null>(null);
  const columns2 = ref<ColumnItem[]>([
    {
      title: '当前期数',
      dataIndex: 'index',
      key: 'index',
      customRender: ({ index }) => {
        return '第' + (index + 1) + '期';
      }
    },
    {
      title: '订单金额',
      dataIndex: 'orderPrice',
      key: 'orderPrice',
      customRender: ({ text }) => '￥' + text
    },
    {
      title: '设备租金',
      dataIndex: 'batteryModel',
      key: 'batteryModel'
    },
    {
      title: '有效期限',
      dataIndex: 'expirationTime',
      key: 'expirationTime'
    },
    {
      title: '付款时间',
      dataIndex: 'payTime',
      key: 'payTime'
    },
    {
      title: '逾期状态',
      dataIndex: 'expirationDay',
      key: 'expirationDay'
    }
  ]);
  const columns3 = ref<ColumnItem[]>([
    {
      title: '设备编号',
      dataIndex: 'equipmentCode',
      key: 'equipmentCode'
    },
    {
      title: '所属门店',
      dataIndex: 'merchantName',
      key: 'merchantName'
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      key: 'eventType'
    },
    {
      title: '使用电池',
      dataIndex: 'use'
    },
    {
      title: '操作人',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      key: 'createTime'
    }
  ]);

  /* 制作步骤条 */
  const loadSteps = (order) => {
    steps.value = [];
    steps.value.push({
      title: '下单'
    });
    steps.value.push({
      title: '付款'
    });
    steps.value.push({
      title: '发货'
    });
    steps.value.push({
      title: '收货'
    });
    steps.value.push({
      title: '完成'
    });

    // 下单
    if (order.payStatus == 10) {
      active.value = 0;
      steps.value[0].description = order.createTime;
    }
    // 付款
    if (order.payStatus == 20) {
      active.value = 1;
      steps.value[0].description = order.createTime;
      steps.value[1].description = order.payTime;
    }
    // 发货
    if (order.payStatus == 20 && order.deliveryStatus == 20) {
      active.value = 2;
      steps.value[0].description = order.createTime;
      steps.value[1].description = order.payTime;
      steps.value[2].description = order.deliveryTime;
    }
    // 收货
    if (order.payStatus == 20 && order.receiptStatus == 20) {
      active.value = 3;
      steps.value[0].description = order.createTime;
      steps.value[1].description = order.payTime;
      steps.value[2].description = order.deliveryTime;
      steps.value[3].description = order.receiptTime;
    }
    // 完成
    if (order.payStatus == 20 && order.orderStatus == 30) {
      active.value = 4;
      steps.value[0].description = order.createTime;
      steps.value[1].description = order.payTime;
      steps.value[2].description = order.deliveryTime;
      steps.value[3].description = order.receiptTime;
    }
    // 已取消
    if (order.orderStatus == 20) {
      active.value = 4;
    }
  };

  const getEquipmentOrderGoods = () => {
    const orderId = props.data?.orderId;
    const goodsId = props.data?.goodsId;
    listEquipmentOrderGoods({ orderId,goodsId }).then((data) => {
      EquipmentOrderGoodsList.value = data;
    });
  };

  const getEquipment = () => {
    EquipmentApi.listEquipment({ orderId: order.orderId }).then((data) => {
      if (data.length > 0) {
        bindEquipmentCode.value = data[0].equipmentCode;
      }
    });
  };

  const getRenewOrder = () => {
    loading.value = true;
    listOrder({
      rentOrderId: order.orderId,
      payStatus: 20
    }).then((data) => {
      renewOrderList.value = data;
      loading.value = false;
    });
  };

  const getEquipmentRecordList = () => {
    EquipmentRecordApi.listEquipmentRecord({
      orderId: order.orderId,
      userId: order.userId
    }).then((data) => {
      equipmentRecordList.value = data;
    });
  };

  const expirationDay = (order) => {
    const setTime = new Date(order.expirationTime);
    const nowTime = new Date(order.payTime);
    const restSec = setTime.getTime() - nowTime.getTime();
    // 剩余天数
    const day = parseInt(String(restSec / (60 * 60 * 24 * 1000)));
    if (day < 0) {
      return '逾期' + Math.abs(day) + '天';
    }
  };

  const getFiles = () => {
    if (order.orderSourceData != '') {
      const array = JSON.parse(<string>order.orderSourceData);
      files.value = array.map((url, id) => {
        return {
          id: id,
          url: url,
          status: 'done'
        };
      });
    }
  };

  /* 保存编辑 */
  const save = () => {};

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignObject(order, props.data);
          loadSteps(props.data);
          getFiles();
          getEquipmentOrderGoods();
          getRenewOrder();
          getEquipment();
          getEquipmentRecordList();
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less" scoped>
  .order-card {
    margin-bottom: 20px;
  }
  .ant-form-item {
    margin-bottom: 5px;
  }
</style>
