<template>
  <div class="order-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" size="small" placeholder="请输入订单编号"></el-input>
      </el-form-item>
      <!-- <el-form-item label="支付订单号" prop="paymentNo">
        <el-input v-model="queryParams.paymentNo" size="small" placeholder="请输入支付订单号"></el-input>
      </el-form-item> -->
      <el-form-item label="收货人" prop="receiverName">
        <el-input v-model="queryParams.receiverName" size="small" placeholder="请输入收货人姓名"></el-input>
      </el-form-item>
      <el-form-item label="收货人手机号" prop="receiverPhone">
        <el-input v-model="queryParams.receiverPhone" size="small" placeholder="请输入收货人手机号"></el-input>
      </el-form-item>
      <el-form-item label="物流单号" prop="expressNo">
        <el-input v-model="queryParams.expressNo" size="small" placeholder="请输入物流单号"></el-input>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <!-- <el-input v-model="queryParams.supplierName" size="small" placeholder="请输入供应商名称"></el-input> -->
        <el-select v-model="queryParams.supplierId" size="small" filterable placeholder="请选择所属供应商" clearable>
          <el-option v-for="(v,i) in supplierList" :key="i" :label="v.supplierName" :value="v.supplierId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </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-divider></el-divider> -->
    <el-radio-group v-model="queryParams.queryStatus" style="margin-bottom: 30px;" @input="queryStatusChange">
      <el-radio-button v-for="(v,i) in queryStatusList" :key="i" :label="v.value">{{v.label}}</el-radio-button>
    </el-radio-group>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleExport">导出订单</el-button>
        <el-button type="primary" plain size="mini" @click="handleWaitExport">导出待发货订单</el-button>
        <el-button type="primary" plain size="mini" @click="openBatchDelivery()">批量发货</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="order-list">
      <div v-for="item in list" :key="item.orderNo" class="order-item">
        <div class="order-header">
          <div class="order-info">
            <span>
              <label>订单号：</label>
              <span>{{ item.orderNo }}</span>
            </span>
            <!-- <span>
              <label>支付订单号：</label>
              <span>{{ item.paymentNo }}</span>
            </span> -->
            <span>
              <label>供应商名称：</label>
              <span>{{ item.orderDetails[0].supplierName }}</span>
            </span>
            <div class="order-status">
              <el-tag type="success" size="small">{{dealPaymentMethod(item.paymentMethod)}}</el-tag>
            </div>
          </div>
          <div class="header-right">
            <div class="order-actions">
              <el-button type="text" style="color: #666" size="small" @click="handleDetail(item)">查看</el-button>
              <el-button v-if="item.orderStatus === 10" type="text" size="small" @click="handleExpress(item)">发货</el-button>
              <el-button v-if="item.orderStatus != 10&&item.orderStatus != 30" type="text" size="small" @click="handleExpress(item)">修改发货</el-button>
              <el-button v-if="item.orderStatus === 20||item.orderStatus === 30" type="text" size="small" @click="handleExpressDetail(item)">发货明细</el-button>
            </div>
          </div>
        </div>
        <div class="order-content">
          <div class="goods-info">
            <el-image :src="item.orderDetails[0].productCover" class="goods-image"></el-image>
            <div class="goods-detail">
              <div class="goods-name" :title="item.goodsName">
                {{ item.orderDetails[0].productTitle }}
              </div>
              <div class="goods-price">
                <span class="price-symbol">¥</span>
                <span class="price-value">{{ item.orderDetails[0].productPrice }}</span>
              </div>
              <div class="goods-count">{{ item.orderDetails[0].productNum }}{{item.orderDetails[0].productUnit}}</div>
            </div>
          </div>
          <div class="orderInfo">
            <div>{{ item.orderDetails[0].pointsPerProduct }}兑换豆</div>
            <!-- <div>（1/{{ item.unit || "盒" }}）</div> -->
          </div>
          <div class="orderInfo">
            <div>{{ item.shopOrderAddress.receiverName }}</div>
            <div>{{ item.shopOrderAddress.receiverPhone }}</div>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(item.orderStatus)">{{
              getStatusText(item)
            }}</el-tag>
          </div>
          <div class="order-time">{{ item.createTime }}</div>
        </div>
        <div class="order-footer">
          <span>免运费</span>
          <span class="total-amount">实付兑换豆：{{ item.paymentPoints }}</span>
        </div>
      </div>
    </div>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 发货弹窗 -->
    <el-dialog title="物流发货" :visible.sync="expressDialogVisible" width="650px" @close="close">
      <el-form :model="expressForm" label-width="100px" size="small">
        <el-form-item label="快递公司" required>
          <el-select v-model="expressForm.expressCode" placeholder="请选择快递公司" style="width: 100%" @change="expressChange">
            <el-option v-for="(v, i) in expressCompanyList" :key="i" :value="v.companyCode" :label="v.companyName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" required>
          <el-input v-model="expressForm.expressNo" placeholder="请输入快递单号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="expressDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleExpressSubmit">确 定</el-button>
      </div>
      <!-- 在发货弹窗后面添加物流详情弹窗 -->
    </el-dialog>

    <!-- 物流详情弹窗 -->
    <el-dialog title="物流明细" :visible.sync="expressDetailVisible" width="650px" @close="expressDetailVisible=false">
      <div class="express-detail">
        <div class="express-info">
          <div class="info-item">
            <span class="label">配送企业：</span>
            <span class="value">{{ expressDetail.expressCompany }}</span>
          </div>
          <div class="info-item">
            <span class="label">快递单号：</span>
            <span class="value">{{ expressDetail.expressNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">发货人：</span>
            <span class="value">{{ expressDetail.shipPerson }}</span>
          </div>
        </div>
        <div class="express-timeline">
          <el-timeline>
            <el-timeline-item v-for="(item, index) in expressDetail.expressContentJson.list" :key="index" :timestamp="item.time" :type="index === 0 ? 'primary' : ''">
              {{ item.status }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
    <batchDelivery ref="batchDeliveryRef" @result="getList()" />
  </div>
</template>

<script>
import { shopOrderPage, simpleShip, simpleShipEdit, shopOrderPackageInfo, supplierList } from "@/api/pointsMall";
import { expressCompanyList } from "@/api/operating.js"
import batchDelivery from "./batchDelivery.vue"
export default {
  name: "OrderList",
  components: { batchDelivery },
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      list: [],
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transactionId: undefined,
        orderNo: undefined,
        receiverName: undefined,
        receiverPhone: undefined,
        expressNo: undefined,
        supplierName: undefined,
      },
      paymentMethodList: [
        { label: "微信支付", value: 1 },
        { label: "支付宝支付", value: 2 },
        { label: "积分兑换", value: 3 },
        { label: "微信支付+积分", value: 13 },
        { label: "支付宝支付+积分", value: 23 },
      ],
      expressForm: {
        expressContent: undefined,
        expressCompany: undefined,
        expressNo: undefined,
        orderId: undefined
      },
      expressDialogVisible: false,
      expressDetail: {
        expressContentJson: {
          list: []
        },
      },
      expressDetailVisible: false,
      expressCompanyList: [],
      btnLoading: false,
      queryStatusList: [
        { label: '全部订单', value: undefined },
        { label: '待发货', value: 0, value1: 10, name: 'orderStatus' },
        { label: '待收货', value: 1, value1: 20, name: 'orderStatus' },
        { label: '待评价', value: 2, value1: 0, name: 'commentStatus' },
        { label: '已完成', value: 3, value1: 20, name: 'commentStatus' },
      ],
      supplierList: []
    };
  },
  mounted () {
    if (this.$route.query.orderStatus) {
      this.queryParams.queryStatus = this.$route.query.orderStatus == 10 ? 0 : undefined
      this.queryParams.orderStatus = Number(this.$route.query.orderStatus)
    }
    this.getList();
    this.getExpressCompanyList();
    this.getSupplierList()
  },
  methods: {
    getSupplierList () {
      supplierList().then(res => {
        this.supplierList = res.data
      })
    },
    queryStatusChange (e) {
      this.queryParams.commentStatus = undefined;
      this.queryParams.orderStatus = undefined;
      if (e !== undefined) {
        let index = this.queryStatusList.findIndex(item => item.value == e);
        this.queryParams[this.queryStatusList[index].name] = this.queryStatusList[index].value1;

      }
      this.handleQuery()
    },
    dealPaymentMethod (value) {
      for (let i = 0; i < this.paymentMethodList.length; i++) {
        if (this.paymentMethodList[i].value == value) {
          return this.paymentMethodList[i].label
        }
      }
    },
    openBatchDelivery () {
      this.$refs.batchDeliveryRef.open()
    },
    expressChange (e) {
      if (e) {
        this.expressCompanyList.map(v => {
          if (v.companyCode == e) {
            this.expressForm.expressCompany = v.companyName
          }
        })
      } else {
        this.expressForm.expressCompany = ''
      }
    },
    getList () {
      this.loading = true;
      this.queryParams["startTime"] = undefined;
      this.queryParams["endTime"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["startTime"] = this.daterangeCreateTime[0];
        this.queryParams["endTime"] = this.daterangeCreateTime[1];
      }
      shopOrderPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getStatusType (status) {
      const map = {
        0: "info",
        10: "warning",
        20: "success",
        30: "success",
        100: "warning",
        [-1]: "danger",
      };
      return map[status] || "info";
    },
    getStatusText (item) {
      const map = {
        0: "待支付",
        10: "待发货",
        // 20: "已发货待收货",
        20: "待收货",
        // 30: "交易完成",
        100: "已取消",
      };
      if (item.orderStatus == 30) {
        return item.commentStatus == 0 ? '待评价' : item.commentStatus == 20 ? '已评价' : ''
      }
      return map[item.orderStatus] || item.orderStatus;
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetail (row) {
      this.$router.push({
        path: "/pointsMall/order/detail",
        query: {
          orderId: row.orderId,
        },
      });
    },
    handleExpress (row) {
      this.expressDialogVisible = true;
      this.expressForm.orderId = row.orderId;
      this.expressForm.expressCompany = "";
      this.expressForm.expressContent = "";
      this.expressForm.expressNo = "";
      this.expressForm.orderStatus = row.orderStatus;
      shopOrderPackageInfo(row.orderId).then(res => {
        this.expressForm.expressCode = res.data.expressCode;
        this.expressForm.expressNo = res.data.expressNo;
      })
    },
    // 获取快递公司列表
    getExpressCompanyList () {
      expressCompanyList().then(res => {
        this.expressCompanyList = res.data;
      })
    },
    //  导出订单
    handleExport () {
      // /shoporder/shopOrder/export
      this.download('/shoporder/shopOrder/export', {
        ...this.queryParams
      }, `积分订单_${new Date().getTime()}.xlsx`)
    },
    // 导出待发货订单
    handleWaitExport () {
      this.download('/shoporder/shopOrder/exportWaitShip', { ...this.queryParams }, `待发货订单_${new Date().getTime()}.xlsx`)
    },
    close () {
      this.expressForm = {
        expressContent: undefined,
        expressCompany: undefined,
        expressNo: undefined,
        orderId: undefined
      }
      this.expressDialogVisible = false;
    },
    handleExpressSubmit () {
      if (!this.expressForm.expressCode) {
        this.$message.error("请选择快递公司");
        return;
      }
      if (!this.expressForm.expressNo) {
        this.$message.error("请输入快递单号");
        return;
      }
      let apiFun = simpleShip
      if (this.expressForm.orderStatus && this.expressForm.orderStatus != 10 && this.expressForm.orderStatus != 30) {
        apiFun = simpleShipEdit
      }
      this.btnLoading = true;
      apiFun(this.expressForm).then(res => {
        this.$message.success("发货成功");
        this.getList(); // 刷新列表
        this.close();
      }).finally(() => {
        this.btnLoading = false
      })
    },
    handleExpressDetail (row) {
      this.expressDetailVisible = true;
      shopOrderPackageInfo(row.orderId).then(res => {
        if (!res.data.expressContentJson) {
          res.data.expressContentJson = {
            list: []
          }
        }
        this.expressDetail = res.data
      }).catch(v => {
        this.$message.error("发货信息异常，请检查发货信息是否录入正确！");
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.order-container {
  padding: 20px;
  background: #fff;

  .order-list {
    .order-item {
      margin-bottom: 20px;

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 20px;
        background-color: #e5e5e5;
        border: 1px solid #c5c5c5;

        .order-info {
          display: flex;
          align-items: center;
          flex: 1;

          span {
            margin-right: 20px;
            font-size: 14px;

            label {
              color: #333;
            }

            span {
              color: #666;
              margin-right: 0;
            }
          }

          .order-status {
            margin-left: 10px;
          }
        }

        .header-right {
          display: flex;
          align-items: center;
          margin-left: 20px;

          .status-tag {
            margin-right: 15px;
          }

          .order-actions {
            .el-button {
              margin: 0 5px;

              &:first-child {
                margin-left: 0;
              }

              &:last-child {
                margin-right: 0;
              }
            }
          }
        }
      }

      .order-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px;

        .goods-info {
          display: flex;
          align-items: center;
          width: 380px;

          .goods-image {
            width: 60px;
            height: 60px;
            margin-right: 15px;
            border-radius: 4px;
          }

          .goods-detail {
            flex: 1;
            overflow: hidden;
            .goods-name {
              font-size: 14px;
              color: #303133;
              margin-bottom: 8px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .goods-price {
              color: #f56c6c;
              margin-bottom: 5px;
              font-size: 14px;

              .price-symbol {
                font-size: 12px;
                margin-right: 2px;
              }

              .price-value {
                font-weight: bold;
              }
            }

            .goods-count {
              color: #909399;
              font-size: 12px;
            }
          }
        }
        .orderInfo {
          width: 240px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          font-size: 15px;
          color: #444;
          div {
            &:nth-child(1) {
              margin-bottom: 6px;
            }
          }
        }

        .goods-unit {
          width: 80px;
          text-align: left;
          color: #606266;
          font-size: 14px;
        }

        .receiver-info {
          width: 200px;
          margin: 0 20px;

          span {
            display: block;
            color: #606266;
            font-size: 14px;
            line-height: 1.5;

            &:first-child {
              margin-bottom: 5px;
            }
          }
        }

        .order-status {
          width: 80px;
          text-align: center;
          margin: 0 20px;
        }

        .order-time {
          width: 160px;
          text-align: center;
          color: #606266;
          font-size: 14px;
        }
      }

      .order-footer {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 12px 20px;
        border-top: 1px solid #ebeef5;
        font-size: 15px;

        span {
          margin-left: 20px;
          color: #606266;

          &.total-amount {
            color: #f56c6c;
            font-weight: bold;
          }
        }
      }
    }
  }
  .express-detail {
    padding: 0 20px;

    .express-info {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      .info-item {
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: #606266;
        }

        .value {
          color: #303133;
          margin-left: 5px;
        }
      }
    }

    .express-timeline {
      max-height: 400px;
      overflow-y: auto;
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
