<template>
  <div class="app-container">
    <div class="header" style="width: 100%">
      <el-row class="row" :gutter="12">
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>今日新增订单</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.AllOrder : 0 }} 个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>待接单</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.waitOrderCount : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>账期待审核</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.waitAuditOrderCount : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>待发货</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.waitDelivery : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>未发货待退款</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.waitDeliveryRefund : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>待处理售后</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.afterSalesOrder : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>到账金额</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.divideSuccessPrice : 0 }}个
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>冻结金额</span>
            </div>
            <div class="count">
              {{ orderStatistics ? orderStatistics.divideWaitPrice : 0 }}元
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>账期待付款</span>
            </div>
            <div class="count">
              {{
                orderStatistics.divideWaitPayPrice
                  ? orderStatistics.divideWaitPayPrice
                  : 0
              }}元
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="item">
            <div class="title">
              <span>账期逾期金额</span>
            </div>
            <div class="count">
              {{
                orderStatistics.divideOverduePrice
                  ? orderStatistics.divideOverduePrice
                  : 0
              }}元
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="radio">
      <el-radio-group
        v-model="queryParams.queryOrderStatus"
        @change="radioChange"
      >
        <el-radio-button size="medium" label="0" name="0">
          全部
        </el-radio-button>
        <el-radio-button
          size="medium"
          :label="item.value"
          :name="item.value"
          v-for="item in dict.type.sys_order_query_orderStatus"
          :key="item.value"
        >
          {{ item.label }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="关键字" prop="key" label-width="100px">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入订单编号/商品ID/商品名称/买家手机号/买家ID搜索"
          clearable
          style="width: 420px"
        />
      </el-form-item>

      <el-form-item label="下单时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="date"
          placeholder="请选择下单时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="配送方式" prop="deliveryType">
        <el-select
          v-model="queryParams.deliveryType"
          placeholder="请选择配送方式"
          style="width: 180px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_deliveryType"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatusKey">
        <el-select
          v-model="queryParams.orderStatusKey"
          placeholder="请选择订单状态"
          style="width: 220px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_orderStatusKey"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentType" label-width="100px">
        <el-select
          v-model="queryParams.paymentType"
          placeholder="请选择支付方式"
          style="width: 22 0px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_paymentType"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="先用后付支付状态"
        prop="paymentType"
        label-width="140px"
      >
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="请选择支付状态"
          style="width: 180px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_payStatus"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="售后状态" prop="afterSaleStatus">
        <el-select
          v-model="queryParams.afterSaleStatus"
          placeholder="请选择售后状态"
          style="width: 180px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_aftersalestatus"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="先用后付审核" prop="paymentType" label-width="140px">
        <el-select
          v-model="queryParams.paymentType"
          placeholder="请选择支付方式"
          style="width: 180px"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in dict.type.sys_order_audit"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="printOrderBtn"
          :disabled="!selectList.length > 0"
          >批量接单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="printOrderBtn"
          :disabled="!selectList.length > 0"
          >批量发货</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="printOrderBtn"
          :disabled="!selectList.length > 0"
          >订单打印</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-dropdown :hide-on-click="false" trigger="click">
          <el-button type="primary" plain size="mini">
            更多批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native=""
              >批量先用后付审核</el-dropdown-item
            >
            <el-dropdown-item @click.native=""
              >批量确认是否线下支付</el-dropdown-item
            >
            <el-dropdown-item @click.native="handleExport"
              >批量导出</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :span-method="objectSpanMethod"
      :data="spuList"
      :border="true"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="carPayNo"
        width="230"
      />

      <el-table-column
        label="商品名称"
        align="center"
        prop="skuName"
        width="200"
      >
        <template slot-scope="scope">
          {{
            scope.row.goodsInfo
              ? JSON.parse(scope.row.goodsInfo)[0].skuName
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="price">
        <template slot-scope="scope">
          <span>
            {{
              scope.row.goodsInfo
                ? JSON.parse(scope.row.goodsInfo)[0].price + "元"
                : ""
            }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="数量" align="center" prop="price">
        <template slot-scope="scope">
          <span>
            {{
              scope.row.goodsInfo
                ? JSON.parse(scope.row.goodsInfo)[0].quantity
                : ""
            }}{{
              scope.row.goodsInfo ? JSON.parse(scope.row.goodsInfo)[0].unit : ""
            }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        label="交易金额(元)"
        align="center"
        prop="paymentAmount"
        width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.goodsAmount.toFixed(2) }}元
        </template>
      </el-table-column>

      <el-table-column label="订单状态" align="center" width="120">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_order_orderStatus_table"
            :value="scope.row.orderStatus"
          />
        </template>
      </el-table-column>

      <el-table-column label="售后状态" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_order_aftersalestatus"
            :value="scope.row.afterSaleStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="下单人ID"
        align="center"
        prop="userId"
        width="100"
      />
      <el-table-column
        label="下单时间"
        align="center"
        prop="createTime"
        width="160"
      />
      <el-table-column label="支付方式" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_order_paymentType"
            :value="scope.row.paymentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_order_payStatus"
            :value="scope.row.paymentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="配送方式"
        align="center"
        prop="paymentType"
        width="120"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_order_deliveryType"
            :value="scope.row.deliveryType"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handlePrior(scope.row)"
            v-if="
              scope.row.paymentType == 'firstuse' &&
              scope.row.auditFirstUse != 0
            "
            >先用后付审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleOffline(scope.row)"
            v-if="
              scope.row.paymentStatus == '2' &&
              scope.row.confirmOfflinePayment != 0
            "
            >确认是否已线下支付</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            v-hasPermi="['manage:order:detail']"
            >订单详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <dialogOrder
      ref="orderDialogRef"
      @orderDialogReturn="orderReturn"
    ></dialogOrder>
  </div>
</template>

<script>
import { statisticsOrderNum, queryUserOrderByShopId } from "@/api/manage/order";
import Utils from "@/utils/derive";
import dialogOrder from "../common/orderDialog.vue";
export default {
  name: "wholesale",
  components: {
    dialogOrder,
  },
  dicts: [
    "sys_order_deliveryType",
    "sys_order_orderStatusKey",
    "sys_order_paymentType",
    "sys_order_aftersalestatus",
    "sys_order_payStatus",
    "sys_order_orderStatus_table",
    "sys_order_query_orderStatus",
    "sys_order_audit",
  ],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      total: 0,
      // 参数表格数据
      spuList: [],
      // 弹出层标题
      title: "订单详情",
      // 查询参数
      queryParams: {
        queryOrderStatus: "0",
        spuType: 0,
        userId: "",
        pageNo: 1,
        pageSize: 10,
        spuName: "",
        userOrderSn: "",
        userPhone: "",
        createTime: "",
        orderStatusKey: "",
        afterSaleStatus: "",
        paymentType: "",
        deliveryType: "",
      },
      printForm: {
        sn: "",
      },
      column: [
        { header: "订单编号", key: "userOrderSn", width: 20 },
        { header: "买家姓名", key: "userNick", width: 20 },
        { header: "买家手机号", key: "userPhone", width: 20 },
        { header: "商品名称", key: "skuName", width: 20 },
        { header: "商品类型", key: "categoryName", width: 20 },
        { header: "商品价格", key: "price", width: 20 },
        { header: "包装方式", key: "packageType", width: 20 },
        { header: "规格名称", key: "specsName", width: 20 },
        { header: "规格值", key: "specsValue", width: 20 },
        { header: "实付金额(元)", key: "goodsAmount", width: 20 },
        { header: "商品数量", key: "goodsDetails", width: 20 },
        { header: "运费", key: "freightFee", width: 20 },
        { header: "订单状态", key: "orderStatus", width: 20 },
        { header: "售后状态", key: "afterSaleStatus", width: 20 },
        { header: "下单时间", key: "createTime", width: 20 },
        { header: "付款时间 ", key: "paymentTime", width: 20 },
      ],
      // 表单参数
      form: {},
      // 表单校验
      orderStatistics: {},
      selectList: [],
      selectListDC: [],
      queryOrderStatus: 0,
    };
  },
  mounted() {
    this.getList();
    this.getstatisticsOrder();
  },
  methods: {
    radioChange() {
      this.getList();
    },
    orderReturn(type) {
      switch (type) {
        case "print":
          this.$refs.multipleTable.clearSelection();
          this.getList();
        case "prior":
          this.getList();
        case "offline":
          this.getList();
      }
    },
    handleOffline(record) {
      this.$refs.orderDialogRef.openDialog("offline", record);
    },
    handlePrior(record) {
      this.$refs.orderDialogRef.openDialog("prior", record);
    },
    printOrderBtn() {
      this.$refs.orderDialogRef.openDialog("print", this.selectList);
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        if (
          rowIndex === 0 ||
          row.carPayNo != this.spuList[rowIndex - 1].carPayNo
        ) {
          let rowspan = 0;
          this.spuList.forEach((element) => {
            if (element.carPayNo === row.carPayNo) {
              rowspan++;
            }
          });
          return [rowspan, 1];
        } else {
          return [0, 0];
        }
      }
    },

    getstatisticsOrder() {
      statisticsOrderNum({ spuType: 0 }).then((res) => {
        if (res.code == 200) {
          this.orderStatistics = res.data;
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },

    /** 查询参数列表 */
    getList() {
      this.selectList = [];
      this.loading = true;
      queryUserOrderByShopId(this.queryParams).then((response) => {
        if (response.code == 200) {
          let list = response.data.records;
          let infoList = [];
          for (let index = 0; index < list.length; index++) {
            let e = list[index];
            if (e.dxUserOrderVOList) {
              for (let i = 0; i < e.dxUserOrderVOList.length; i++) {
                let a = e.dxUserOrderVOList[i];
                let c = { ...e, ...a };
                infoList.push(c);
              }
            } else {
              infoList.push(e);
            }
          }
          let totalList = [];
          for (let index = 0; index < infoList.length; index++) {
            let e = infoList[index];
            if (e.goodsInfo) {
              try {
                var goods = JSON.parse(e.goodsInfo);
                e = { ...e, ...goods[0] };
              } catch (error) {
                console.error("解析 JSON 时出错:", error);
                // 跳出当前循环，继续处理下一个元素
                continue;
              }
            }
            if (e.specsValue) {
              for (let i = 0; i < e.specsValue.length; i++) {
                let a = e.specsValue[i];
                e = { ...e, ...a };
              }
            }

            totalList.push(e);
          }

          totalList.forEach((e) => {
            try {
              let goos = JSON.parse(e.goodsInfo);
              let detail = "";
              if (goos && goos.length > 0) {
                // 检查 goos 是否为空
                goos.forEach((a) => {
                  detail += `${a.skuName}(${a.specsValue[0]?.specsName})-数量：${a.quantity}${a.unit};`;
                });
              }
              e.goodsDetails = detail;
            } catch (error) {
              console.error("解析 goodsInfo 时出错:", error);
            }
          });

          this.spuList = totalList;
          this.total = response.data.total;
          this.loading = false;
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectList = selection.map((item) => item.carPayNo);
      this.selectListDC = selection.map((item) => item);
    },

    /** 导出按钮操作 */
    handleExport() {
      let lists = [];
      for (let index = 0; index < this.spuList.length; index++) {
        for (let a = 0; a < this.selectListDC.length; a++) {
          if (this.spuList[index].id == this.selectListDC[a].id) {
            lists.push(this.spuList[index]);
          }
        }
      }
      Utils.exportExcel(this.column, lists, "订单列表"); //导出方法
    },
  },
};
</script>
<style scoped lang="scss">
.header {
  .item {
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    line-height: 40px;
  }
  .row {
    background: #f4f4f4;
    padding: 10px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .title {
      text-align: center;
    }
    .count {
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      color: rgb(64, 158, 255);
    }
    .zz {
      font-size: 14px;
      color: red;
      padding: 0px 10px;
    }
  }
}
.radio {
  margin: 20px 0px;
}
</style>
<style>
.el-radio-button__inner {
  width: 150px;
}
</style>
