<template>
  <ContainerQuery>
    <div v-if="$accessCheck($Access.saleOrderListSearch)" slot="more">
      <el-form size="small" :inline="true" :model="search_form">
        <el-form-item>
          <el-input
            v-model="searchDate.keyword"
            clearable
            style="width: 260px"
            placeholder="订单编号/商品名称/备注"
            @keyup.enter.native="pageChange(1)"
            @clear="pageChange(1)"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="pageChange(1)"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <SelectCustomer
            v-model="customer_name"
            @clear="customerClear"
            @change="customerSel"
          />
        </el-form-item>

        <el-form-item>
          <el-date-picker
            v-model="search_form.time"
            clearable
            type="daterange"
            value-format="timestamp"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="orderDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchDate.customerType"
            clearable
            style="width: 150px"
            placeholder="客户类型"
            @change="customerTypes"
          >
            <el-option
              v-for="(item, index) in customerType"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <SelectShop
            v-model="searchDate.shopId"
            width="150"
            placeholder="选择商铺"
            @clear="clearShop"
            @change="selShop"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="staffName"
            clearable
            style="width: 150px"
            placeholder="业务员"
            @clear="staffClear"
            @blur="staffName = ''"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="staff_show = true"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="left">
      <el-dropdown
        v-if="
          $accessCheck($Access.addSaleOrder) && $route.name !== 'CashierOrder'
        "
        split-button
        type="primary"
        @click="goAddOrder"
      >
        新建订单
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <div class="dropdown-div" @click="getData(1)">导出</div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button v-else type="primary" plain size="small" @click="getData(1)">
        导出
      </el-button>
    </div>
    <el-table :data="order_list" @row-dblclick="goDetail">
      <el-table-column
        prop="id"
        label="ID"
        fixed="left"
        width="80"
      ></el-table-column>
      <el-table-column prop="no" label="订单号" min-width="180">
        <template slot-scope="scope">
          <span
            v-if="$accessCheck($Access.saleOrderListGetOrderInfoById)"
            class="click-div"
            @click="goDetail(scope.row)"
          >
            {{ scope.row.no }}
          </span>
          <span v-else>{{ scope.row.no }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="customerName"
        show-overflow-tooltip
        label="客户"
        min-width="140"
      >
        <template slot-scope="scope">
          <el-popover
            v-if="$route.name !== 'CashierOrder'"
            placement="right"
            width="400"
            trigger="hover"
          >
            <div>
              <p class="order-info-p">
                <span class="order-info-label">收货人：</span>
                {{ scope.row.receiveData.realName }}
              </p>
              <p class="order-info-p">
                <span class="order-info-label">联系电话：</span>
                {{ scope.row.receiveData.mobile }}
              </p>
              <p v-if="scope.row.receiveData.area" class="order-info-p">
                <span class="order-info-label">联系地址：</span>
                {{ scope.row.receiveData.area.provinceName
                }}{{ scope.row.receiveData.area.cityName
                }}{{ scope.row.receiveData.area.districtName
                }}{{ scope.row.receiveData.address }}
              </p>
            </div>
            <span slot="reference" class="click-div">
              {{ scope.row.customerName }}
            </span>
          </el-popover>
          <span v-else>{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="moneyFlag"
        prop="payAmount"
        label="订单金额"
        min-width="100"
      ></el-table-column>
      <el-table-column
        v-if="stateFlag"
        prop="orderMsg"
        label="订单状态"
        min-width="100"
      >
        <template slot-scope="scope">
          <span
            :class="[
              scope.row.orderMsg === '待审核'
                ? 'warning-status'
                : scope.row.orderMsg === '已关闭'
                ? 'info-status'
                : scope.row.orderMsg === '已出库'
                ? 'primary-status'
                : scope.row.orderMsg === '已完成'
                ? 'success-status'
                : scope.row.orderMsg === '待出库'
                ? 'danger-status'
                : 'primary-status',
            ]"
          >
            {{ scope.row.orderMsg }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="salesmanFlag"
        prop="salesManName"
        label="业务员"
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.salesManName || "未分配" }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="remarkFlag"
        prop="remark"
        label="备注"
        show-overflow-tooltip
        min-width="160"
      >
        <template slot-scope="scope">
          {{ scope.row.remark || "无" }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="storeFlag"
        prop="shopName"
        label="店铺"
        min-width="100"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        v-if="codeFlag"
        prop="verifyCode"
        label="自提码"
        min-width="100"
      >
        <template slot-scope="scope">
          <p
            v-if="scope.row.verifyCode"
            style="font-weight: bold; color: #67c23a"
          >
            {{ scope.row.verifyCode }}
          </p>
          <p v-else>--</p>
        </template>
      </el-table-column>
      <el-table-column
        v-if="timeFlag"
        prop="createTime"
        label="创建时间"
        min-width="160"
      >
        <template slot-scope="scope">
          {{ $_common.formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="85">
        <template slot="header" slot-scope="scope">
          <span v-if="false">{{ scope.$index }}</span>
          <span class="operation">操作</span>
          <el-popover popper-class="custom-table-checkbox" trigger="click">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="(item, index) in columns"
                :key="index"
                :label="item.label"
                @change="change"
              ></el-checkbox>
            </el-checkbox-group>
            <el-button
              slot="reference"
              icon="el-icon-setting"
              type="text"
            ></el-button>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <el-button-group class="table-btn-group">
            <el-popconfirm
              v-if="accessDetail"
              title="请选择要打印的单据"
              confirm-button-text="小票打印机"
              cancel-button-text="网页打印"
              @onConfirm="toPrint(scope.row)"
              @onCancel="openUrl(scope.row)"
            >
              <el-button slot="reference" type="text">打印</el-button>
            </el-popconfirm>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <FooterPage
      :page-size="pageSize"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    ></FooterPage>
    <staffListModal
      v-if="staff_show"
      :is-show="staff_show"
      :is-check="false"
      @cancel="staff_show = false"
      @confirm="staffSel"
    />
  </ContainerQuery>
</template>

<script>
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import staffListModal from "@/component/common/staffListModal";
  import { getAllCustomerSource } from "@/api/System";
  import {
    getAllOrder,
    exportGetAllOrder,
    searchOrder,
    exportSearchOrder,
    updateOrderStatus,
  } from "@/api/Order";
  import { toPrint } from "@/api/common";

  export default {
    name: "NewOrderList",
    components: {
      SelectCustomer,
      SelectShop,
      staffListModal,
    },
    data() {
      return {
        staff_show: false,
        customerType: [],
        customer_name: "",
        searchDate: {
          keyword: "",
          orderStatus: "",
          payType: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          start: "",
          end: "",
          customerId: "",
          customerType: "",
          salesManId: "",
          shopId: "",
          source: "",
        },
        staffName: "",
        customer_show: false,
        order_list: [],
        total: 0,
        page: 1,
        pageSize: 10,
        search_form: {
          time: [],
          customType: "",
          customer: "",
        },
        // 权限
        accessAdd: true,
        accessAudit: true,
        accessCancel: true,
        accessDetail: true,
        orderType: 23,
        checkList: [
          "订单金额",
          "订单状态",
          "业务员",
          "备注",
          "店铺",
          "自提码",
          "创建时间",
        ],
        columns: [
          {
            label: "订单金额",
          },
          {
            label: "订单状态",
          },
          {
            label: "业务员",
          },
          {
            label: "备注",
          },
          {
            label: "店铺",
          },
          {
            label: "自提码",
          },
          {
            label: "创建时间",
          },
        ],
        moneyFlag: true,
        stateFlag: true,
        salesmanFlag: true,
        remarkFlag: true,
        storeFlag: true,
        codeFlag: true,
        timeFlag: true,
      };
    },
    async mounted() {
      this.orderType = this.$route.name === "CashierOrder" ? 24 : 23;
      await this.getAllOrder();
      await this.getAllCustomerSource();
      // 判断企业是否到期
      this.enterExpireTime();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      clearShop() {
        this.searchDate.shopId = "";
        this.pageChange(1);
      },
      selShop(val) {
        this.pageChange(1);
      },
      // 选择员工
      staffSel(val) {
        const row = val[0];
        this.searchDate.salesManId = row.id;
        this.staffName = row.staffName;
        this.pageChange(1);
      },
      // 清除员工输入框
      staffClear() {
        this.searchDate.salesManId = "";
        this.staffName = "";
        this.pageChange(1);
      },
      // 客户类型
      async getAllCustomerSource() {
        if (!this.customerType.length) {
          const data = await getAllCustomerSource({
            page: 1,
            pageSize: 99,
          });
          this.customerType = data.data;
        }
      },
      customerTypes(val) {
        this.searchDate.customerType = val;
        this.pageChange(1);
      },
      // 获取列表
      async getAllOrder(exports) {
        let search = {
          orderType: this.orderType,
        };
        if (this.$route.name === "CashierOrder") {
          search.isAll = 5;
        }
        let params = {
          page: this.page,
          pageSize: this.pageSize,
          search: search,
        };
        if (exports) {
          params.export = 1;
          const target = await exportGetAllOrder({
            ...params,
          });
        } else {
          const data = await getAllOrder({
            ...params,
          });

          this.order_list = data.data;
          this.total = data.pageTotal;
        }
      },
      // 订单搜索searchOrder
      async searchOrder(exports) {
        const params = {
          keyword: this.searchDate.keyword,
          payType: this.searchDate.payType,
          provinceCode: this.searchDate.provinceCode,
          cityCode: this.searchDate.cityCode,
          districtCode: this.searchDate.districtCode,
          start: this.searchDate.start,
          end: this.searchDate.end,
          customerId: this.searchDate.customerId,
          customerType: this.searchDate.customerType,
          salesManId: this.searchDate.salesManId,
          source: this.searchDate.source,
          page: this.page,
          pageSize: this.pageSize,
          shopId: this.searchDate.shopId,
          orderType: this.orderType,
        };
        if (this.$route.name === "CashierOrder") {
          params.isAll = 5;
        }
        if (exports) {
          params.export = 1;
          const target = await exportSearchOrder({
            ...params,
          });
        } else {
          const data = await searchOrder({
            ...params,
          });

          this.order_list = data.data;
          this.total = data.pageTotal;
        }
      },

      //  判断
      getData(exports) {
        const obj = {
          keyword: this.searchDate.keyword,
          // 'orderStatus': this.searchDate.orderStatus,
          payType: this.searchDate.payType,
          provinceCode: this.searchDate.provinceCode,
          cityCode: this.searchDate.cityCode,
          districtCode: this.searchDate.districtCode,
          start: this.searchDate.start,
          end: this.searchDate.end,
          customerId: this.searchDate.customerId,
          customerType: this.searchDate.customerType,
          salesManId: this.searchDate.salesManId,
          shopId: this.searchDate.shopId,
          source: this.searchDate.source,
        };
        const isKey = this.$_common.isSerch(obj);
        if (isKey) {
          this.searchOrder(exports);
        } else {
          this.getAllOrder(exports);
        }
      },
      // 选择客户
      customerSel(val, list) {
        this.searchDate.customerId = list[0].id;
        this.pageChange(1);
      },
      customerClear() {
        this.searchDate.customerId = "";
        this.customer_name = "";
        this.pageChange(1);
      },
      //  订单时间
      orderDate(val) {
        if (val && val.length) {
          this.searchDate.start = val[0] / 1000;
          this.searchDate.end = val[1] / 1000 + 86399;
        } else {
          this.searchDate.start = "";
          this.searchDate.end = "";
        }
        this.pageChange(1);
      },
      // 切页
      pageChange(val) {
        this.page = val;
        this.getData();
      },
      // 每页数据大小改变
      sizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },
      goAddOrder() {
        this.$router.push({
          path: "/order/saleO/AddSaleOrder",
        });
      },
      goDetail(row) {
        if (!this.$accessCheck(this.$Access.saleOrderListGetOrderInfoById)) {
          return;
        }
        this.$router.push({
          path: `/order/manageO/OrderDetails/${row.userCenterId}/${row.id}`,
        });
      },
      openUrl(row) {
        let routeData = this.$router.resolve({
          path: `/OrderPrinting/${row.userCenterId}/${row.id}`,
        });
        window.open(routeData.href, "_blank");
      },
      // 单据小票打印
      async toPrint(row) {
        const data = await toPrint({
          objectId: row.id,
          objectType: 23, // 销售单
        });

        this.$message({
          type: "success",
          message: "操作成功",
        });
      },
      // 取消订单
      async updateOrderStatus(row) {
        this.$confirm("确定要取消该订单吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await updateOrderStatus(row.userCenterId, {
            orderId: row.id,
          });

          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.getData();
        });
      },
      change() {
        this.moneyFlag = this.checkList.some((item) => item === "订单金额");
        this.stateFlag = this.checkList.some((item) => item === "订单状态");
        this.salesmanFlag = this.checkList.some((item) => item === "业务员");
        this.remarkFlag = this.checkList.some((item) => item === "备注");
        this.storeFlag = this.checkList.some((item) => item === "店铺");
        this.codeFlag = this.checkList.some((item) => item === "自提码");
        this.timeFlag = this.checkList.some((item) => item === "创建时间");
      },
    },
  };
</script>
<style scoped lang="scss">
  .order-table-out {
    padding: 14px;
    height: calc(100vh - 380px);
    overflow-y: auto;
    overflow-x: hidden;
    border-bottom: 1px solid #ebeef5;
  }
  .order-table-head th {
    text-align: center;
    font-size: 13px;
    height: 40px;
    background-color: #f7f7f7;
  }
  .order-empty {
    height: 14px;
  }
  .order-time-no {
    font-size: 13px;
    border: 1px solid #ebeef5;
  }
  .tbody-view .order-time-no td {
    padding: 10px 14px;
  }
  .order-time-text {
    padding-right: 24px;
  }
  .tbody-view tr td {
    padding: 8px 0;
  }
  .tbody-view .order-detail-tr td {
    text-align: center;
    font-size: 13px;
    border: 1px solid #ebeef5;
  }
  .tbody-view .order-detail-tr .goods-td {
    text-align: left;
    padding: 10px 14px;
  }
  .goods-img {
    width: 72px;
    height: 72px;
    margin-right: 10px;
    object-fit: cover;
  }
  .goods-info .goods-tit {
    line-height: 30px;
  }
  .goods-info .goods-spec {
    color: #666;
  }
  .order-payAmount {
    font-weight: 600;
    font-size: 16px;
    color: #ff4040;
  }
  .order-info-p {
    padding-bottom: 4px;
  }
  .order-info-label {
    color: #888;
  }
  .tbody-view .table-handel-div {
    /*transform: translateX(400px);*/
    transition: 0.2s;
    opacity: 0;
  }
  .tbody-view:hover .table-handel-div {
    /*transform: translateX(0);*/
    opacity: 1;
  }
  .custom-table-checkbox {
    .el-checkbox {
      display: block !important;
      margin: 0 0 $base-padding/4 0;
    }
  }
</style>
