<template>
  <div>
    <div class="btn">
      <el-button type="primary">同步订单</el-button>
    </div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单日期">
              <el-date-picker
                v-model="advancedForm.goodsExchange_time_range"
                type="daterange"
                align="center"
                :editable="false"
                unlink-panels
                :clearable="false"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                :picker-options="{
                  disabledDate(time) {
                    return (
                      time.getTime() - 1 >=
                      new Date(
                        new Date().getFullYear(),
                        new Date().getMonth(),
                        new Date().getDate()
                      ).getTime() +
                        86400000 -
                        1
                    );
                  },
                  shortcuts: MixinPickerShortcuts,
                }"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="advancedForm.warehouse_id" clearable>
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号">
              <el-input
                v-model="advancedForm.sn"
                placeholder="请输入订单编号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button @click="advancedSearchEvent"> 搜索 </el-button>
    </div>
    <en-table-layout
      toolbar
      pagination
      :loading="loading"
      :tableData="tableData"
      @selection-change="handleSelectionChange"
    >
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button
            size="mini"
            type="primary"
            v-if="checkPermission(['order:add'])"
            @click="handleAdd"
            >新增</el-button
          >
          <!-- <el-button size="mini" type="primary" v-if="checkPermission(['order:outbound'])"
            @click="batchOutbound">批量出库</el-button> -->
        </div>
        <!-- <div class="toolbar-search">
          <en-table-search
            @search="searchEvent"
            @advancedSearch="advancedSearchEvent"
            advanced
            advancedWidth="465"
            placeholder="请输入订单编号或会员名称"
          >
            <template slot="advanced-content">
              <el-form
                ref="advancedForm"
                :model="advancedForm"
                label-width="80px"
              >
                <el-form-item label="订单时间">
                  <el-date-picker
                    v-model="advancedForm.order_time"
                    type="daterange"
                    align="center"
                    :default-time="['00:00:00', '23:59:59']"
                    :editable="false"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="仓库">
                  <el-select v-model="advancedForm.status" clearable>
                    <el-option label="待提交" value="WAIT_SUBMIT" />
                    <el-option label="待审核" value="WAIT_AUDIT" />
                    <el-option label="审核驳回" value="AUDIT_REJECT" />
                    <el-option label="待出库" value="WAIT_WAREHOUSE_OUT" />
                    <el-option label="待发货" value="WAIT_SHIP" />
                    <el-option label="已发货" value="SHIPPED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="订单编号">
                  <el-select v-model="advancedForm.payment_status" clearable>
                    <el-option label="未支付" value="NOT_PAY" />
                    <el-option label="已支付" value="PAY" />
                  </el-select>
                </el-form-item>
              </el-form>:selectable="canWarehouseOut"
            </template>
          </en-table-search>
        </div> -->
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="订单编号">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column label="客户">
          <template slot-scope="scope">{{
            memberType(scope.row.member_id)
          }}</template>
        </el-table-column>
        <el-table-column label="下单时间">
          <template slot-scope="scope">{{
            scope.row.order_time | unixToDate
          }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_id" label="仓库名称">
          <template slot-scope="scope">
            {{ warehouseName(scope.row.warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="send_type" label="配送方式">
          <template slot-scope="scope">{{
            deliveryType(scope.row.send_type)
          }}</template>
        </el-table-column>
        <el-table-column prop="pay_type" label="付款方式">
          <template slot-scope="scope">{{
            payType(scope.row.pay_type)
          }}</template>
        </el-table-column>
        <el-table-column prop="status" label="实付金额">
          <template slot-scope="scope">{{
            "￥" + scope.row.pay_price
          }}</template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态">
          <template slot-scope="scope">
            {{ typeName(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="延期次数">
          <template slot-scope="scope">
            {{ scope.row.extension }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单类型">
          <template slot-scope="scope">{{ scope.row.type=='TO_B'?'销售订单':'租赁订单' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleAudit(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.status === 'TO_BE_COMMIT'"
              @click="handleSubmit(scope.row.id)"
              >确认</el-button
            >
            
            <el-button
              size="mini"
              @click="handleEdit(scope.row)"
              v-if="scope.row.status === 'TO_BE_COMMIT'"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" v-if="scope.row.type === 'TO_C'"
                       @click="handleWithdraw(scope.row.id)">延期</el-button>
            <!-- <el-button size="mini" type="primary" v-if="scope.row.allowable.payment && checkPermission(['order:payment'])"
                       @click="handlePayment(scope.row.id)">设为已支付</el-button> -->
          </template>
        </el-table-column>
      </template>
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total"
      >
      </el-pagination>
    </en-table-layout>
  </div>
</template>

<script>
import * as API_order from "@/api/order";
import Storage from "@/utils/storage";
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_Setting from "@/api/setting";
import * as API_CollectingAccount from "@/api/collectingAccount";
export default {
  name: "orderList",
  data() {
    return {
      warehouseList: [],
      /** 列表loading状态 */
      loading: false,

      /** 列表参数 */
      params: {
        page_no: 1,
        page_size: 10,
        ...this.$route.query,
      },
      cancelpopup: false,
      cancelLister: "",
      /** 列表数据 */
      tableData: [],

      /** 列表分页数据 */
      pageData: [],

      /** 高级搜索数据 */
      advancedForm: {},

      /** 表格最大高度 */
      tableMaxHeight: document.body.clientHeight - 54 - 34 - 50 - 15,

      accessToken: Storage.getItem("seller_access_token"),
      multipleSelection: [],
      orderType: [],
      collectingAccountList: [], // 支付方式列表
      deliveryTypeList: [
      ],
      customerList: [],
    };
  },
  mounted() {
    this.GET_OrderList();
    this.GET_WarehouseList();
    this.GET_CollectingAccountList();
    this.GET_CustomerList();
  },
  activated() {
    delete this.params.market_enable;
    this.params = {
      ...this.params,
      ...this.$route.query,
    };
    this.GET_OrderList();
    window.onresize = this.countTableHeight;
  },
  beforeRouteUpdate(to, from, next) {
    delete this.params.market_enable;
    this.params = {
      ...this.params,
      ...this.$route.query,
    };
    this.GET_OrderList();
    next();
  },
  methods: {
    memberType(val) {
      let name = "";
      this.customerList.map((el) => {
        if (el.id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    //获取客户列表
    GET_CustomerList() {
      API_BasicSetting.customer(this.params)
        .then((response) => {
          this.customerList = response.data;
        })
        .catch(() => {});
    },
    //配送方式查看
    deliveryType(val) {
      let name = "";
      this.deliveryTypeList.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    //获取付款方式
    payType(val) {
      let name = "";
      this.collectingAccountList.map((el) => {
        if (el.id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    /** 获取支付方式列表 */
    GET_CollectingAccountList() {
      API_CollectingAccount.getList({
        page_no: 1,
        page_size: -1,
        enable_flag: true,
      }).then((response) => {
        this.collectingAccountList = response.data;
      });
    },
    //获取订单状态大小写转换.toUpperCase()
    typeName(val) {
      let name = "";
      this.orderType.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    //获取仓库名称
    warehouseName(val) {
      let name = [];
      this.warehouseList.map((el) => {
        val.map((e) => {
          if (el.id == e) {
            return name.push(el.name)
          }
        });
      });
      return name.join('/');
    },
    batchOutbound() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择订单!");
        return;
      }

      const orderIds = this.multipleSelection.map((order) => order.id);
      this.$router.push({
        name: "orderOutbound",
        params: { orderIds: orderIds },
      });
    },
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
      API_Setting.getPage({ dictType: "order_status" }).then((res) => {
        this.orderType = res.data;
      });
      API_Setting.getPage({ dictType: "order_send_type" }).then((res) => {
        this.deliveryTypeList = res.data;
      });
    },
    /** 计算高度 */
    countTableHeight() {
      this.tableHeight = document.body.clientHeight - 54 - 35 - 50;
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 新增 */
    handleAdd() {
      this.$router.push({
        name: "orderAdd",
        params: { callback: this.GET_OrderList },
      });
    },
    /** 是否可以出库 */
    /*  canWarehouseOut(row) {
      return row.allowable.warehouse_out;
    }, */

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_OrderList();
    },
    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_OrderList();
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keywords: data,
      };
      this.params.page_no = 1;
      delete this.params.order_status;
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key]);
      this.GET_OrderList();
    },

    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      this.params.page_no = 1;
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.order_time) {
        this.advancedForm.order_time[0] =
          this.advancedForm.order_time[0].getTime() / 1000;
        this.advancedForm.order_time[1] =
          this.advancedForm.order_time[1].getTime() / 1000;
      }
      delete this.params.keywords;
      this.GET_OrderList();
    },

    /** 编辑订单 */
    handleEdit(order) {
      this.$router.push({
        name: "orderEdit",
        params: { id: order.id, callback: this.GET_OrderList },
      });
    },
    /** 查看订单 */
    handleAudit(order) {
      this.$router.push({
        name: "orderDetail",
        params: { id: order.id, callback: this.GET_OrderList,type:'check' },
      });
    },
    /** 订单设为已支付 */
    async handlePayment(id) {
      // 二次确认
      await this.$confirm(`确认要设为已支付吗?`, "提示");
      // 发起修改
      await API_order.payment(id);
      this.$message.success("操作成功！");
      // 刷新列表
      this.GET_OrderList();
    },
    /** 提交订单 */
    async handleSubmit(id) {
      // 发起修改
      await API_order.submit(id);
      this.$message.success("操作成功！");
      // 刷新列表
      this.GET_OrderList();
    },
    /** 延期 */
    async handleWithdraw(id) {
      this.$router.push({
        name: "orderEdit",
        params: { id: id,type:'pone' },
      });
    },

    GET_OrderList() {
      this.loading = true;
      API_order.getOrderList(this.params).then((response) => {
        this.loading = false;
        this.tableData = response.data;
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total,
        };
      }).catch(() => { 
        this.loading = false;
      })
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.btn {
  display: flex;
  justify-content: flex-end;
  padding: 30px 20px 5px;
  border-radius: 5px;
  background-color: #fff;
  .el-button {
    width: 100px;
  }
}
.search {
  display: flex;
  align-items: center;
  background: #fff;
  overflow: hidden;
  padding: 30px 10px 10px 10px;
  /deep/ .el-form-item {
    .el-form-item__content {
      .el-input {
        width: 200px;
      }
    }
  }
  .el-button {
    margin-top: -19px;
    margin-left: 20px;
  }
}
/* .container {
  padding: 10px 10px 0 10px;
} */

/deep/ .el-table {
  min-height: auto !important;
}

/deep/ div.toolbar {
  height: 70px;
  padding: 20px 0;
}

/* 工具条*/
.inner-toolbar {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 0 20px;
}

.empty-block {
  position: relative;
  min-height: 60px;
  line-height: 60px;
  text-align: center;
  width: 262%;
  font-size: 14px;
  color: #606266;
}

/*表格信息*/
.my-table-out {
  white-space: nowrap;
  overflow-y: scroll;
  overflow-x: hidden;
  text-overflow: ellipsis;
  width: 100%;
  max-height: 800px;
  margin: 0 10px;
  min-height: 480px !important;
  background: #fff;
}

.my-table {
  width: 100%;
  margin-bottom: 40px;
  background: #fff;
  border-collapse: collapse;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, Arial, sans-serif;
  font-size: 14px;
  font-bold: 700;

  .bg-order {
    background: #fafafa;
  }

  thead {
    th {
      padding: 10px 0;
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      color: #909399;
    }

    th.shoplist-header {
      padding: 10px 20px;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
    }
  }

  tbody {
    margin-top: 10px;

    td {
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      text-align: center;
      padding: 0;
    }

    td:first-child {
      text-align: left;
    }

    td:not(:first-child) {
      padding: 3px;
    }

    td.shoplist-content-out {
      padding-left: 20px;
    }

    /*商品信息*/
    p.shoplist-content:not(:last-child) {
      border-bottom: 1px solid #ebeef5;
      border-collapse: collapse;
    }

    p.shoplist-content {
      margin: 0;
      padding: 0 20px;
      box-sizing: padding-box;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;

      .goods-info {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 0;

        img {
          display: block;
          margin-right: 10px;
        }

        a {
          display: block;
          color: #409eff;
        }
      }
    }

    div.order-money {
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;

      span {
        display: inline-block;
        padding: 5px;
      }

      span.order-amount {
        color: red;
      }
    }
  }

  /* 商品图片 */
  .goods-image {
    width: 50px;
    height: 50px;
  }

  /** 交易快照 */
  .trade-record {
    display: inline-block;
    margin-right: 50px;
  }
}

/*分页信息*/
section > div {
  position: relative;
}

.el-pagination {
  text-align: right;
  width: 100%;
  background: #ffffff;
  height: 100px;
  padding: 5px 20px;
  margin: 0 10px;
}

.exprot-tip {
  margin-left: 5px;
  color: red;
  font-size: 12px;
}
</style>

