<template>
  <div class="order pagePadding">
    <ex-table
      v-loading="loading"
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
      :table="table"
      :data="tableData"
      :columns="columns"
      :page="pageInfo"
      :size="size"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        pageInfo.curr = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        searchList();
      "
    >
      <template #table-header="{}">
        <div style="width: 100%">
          <el-row>
            <el-col :span="24">
              <el-col :span="4" style="width: 110px">
                <el-select
                  :size="searchSize"
                  v-model="parmValue.status"
                  filterable
                  clearable
                  @change="(pageInfo.curr = 1), searchList()"
                  placeholder="订单状态"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in statusList"
                    :key="'status' + item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-col>

              <el-col :span="4" style="width: 312px; padding: 0 0 0 10px">
                <PeriodDatePicker
                  :start="parmValue.order_low"
                  :end="parmValue.order_up"
                  :type="1"
                  :size="searchSize"
                  :width="'140px'"
                  @timeReturned="timeReturned($event)"
                />
              </el-col>
              <el-col :span="4" style="width: 292px; padding: 0 0 0 10px">
                <el-input
                  :size="searchSize"
                  v-model="input"
                  :maxlength="40"
                  @blur="(pageInfo.curr = 1), searchList()"
                  placeholder="关键字"
                >
                  <el-select
                    v-model="select"
                    slot="prepend"
                    style="width: 88px"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in selectList"
                      :label="item.name"
                      :value="item.code"
                      :key="index + 'se'"
                    ></el-option>
                  </el-select>
                </el-input>
              </el-col>
              <el-col
                :span="3"
                v-if="powers.some((item) => item == '002')"
                style="width: 66px; padding: 0 0 0 10px; float: right"
              >
                <el-button
                  :size="searchSize"
                  type="primary"
                  style="float: right"
                  @click="searchList"
                >
                  刷新
                </el-button>
              </el-col>
              <el-col
                :span="3"
                style="width: 90px; padding: 0 0 0 10px; float: right"
              >
                <el-button
                  :size="searchSize"
                  :disabled="loading"
                  type="primary"
                  style="float: right"
                  @click="batchExport"
                  >订单导出
                </el-button>
              </el-col>
              <el-col
                :span="3"
                style="width: 90px; padding: 0 0 0 10px; float: right"
              >
                <el-button
                  :size="searchSize"
                  :disabled="loading"
                  type="primary"
                  style="float: right"
                  @click="postModel = true"
                  >批量发货
                </el-button>
              </el-col>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #status="{ scope }">
        <el-tag
          :size="tablebtnSize"
          :type="scope.row.status == '1' ? 'warning' : ''"
          v-text="
            (statusList.find((item) => item.id == scope.row.status) || {})
              .label || '--'
          "
        ></el-tag>
      </template>

      <template #operation="{ scope }">
        <el-tooltip
          v-if="powers.some((item) => item == '007')"
          class="item"
          effect="dark"
          content="详情"
          placement="top"
        >
          <i
            class="el-icon-view tb-icon"
            @click="openModal(scope.row, '007')"
          ></i>
        </el-tooltip>

        <el-tooltip
          v-if="
            powers.some((item) => item == '009') && scope.row.status === '1'
          "
          class="item"
          effect="dark"
          content="填写物流"
          placement="top"
        >
          <i
            class="el-icon-truck tb-icon"
            @click="openModal(scope.row, '009')"
          ></i>
        </el-tooltip>
      </template>
    </ex-table>
    <no-auth v-else></no-auth>
    <!-- 弹窗 新增/修改 -->
    <add-edit
      :id="modelId"
      :isDetail="isDetail"
      :show-model="showModel"
      @refresh="searchList"
      @cancel="showModel = false"
    />
    <in-post-model
      :show-model="postModel"
      @cancel="postModel = false"
      @refresh="postRefresh"
    />
  </div>
</template>
<script>
import ExTable from "@/components/ExTableNew.vue";
import addEdit from "./addEdit";
import asyncRequest from "@/apis/service/mobile/order";
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import urlConfig from "@/apis/url-config";
import PeriodDatePicker from "@/components/PeriodDatePicker";
import inPostModel from "./inPostModel";
import { columns } from "./columns";
export default {
  name: "order",
  mixins: [mixinPage, resToken],
  components: {
    ExTable,
    addEdit,
    PeriodDatePicker,
    inPostModel,
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "order"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      postModel: false,
      fileUrl: urlConfig.baseURL,
      selectList: [
        { code: "1", name: "账号" },
        { code: "2", name: "姓名" },
        { code: "3", name: "手机号" },
      ],
      select: "1",
      input: "",
      loading: true,
      showModel: false,
      isDetail: "",
      modelId: 0,
      parmValue: {
        username: "", // 账户名
        nickname: "", // 用户名
        status: "", //
        mobile: "",
        order_low: "",
        order_up: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      // 状态
      statusList: [
        { id: 1, label: "待发货" },
        { id: 2, label: "已发货" },
      ],
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        // _defaultHeader_: ["setcol"]
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: columns,
    };
  },
  mounted() {
    this.select = "1";
    this.input = "";
    this.searchList();
  },
  methods: {
    restSearch() {
      this.select = "1";
      this.input = "";
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        username: "", // 账户名
        nickname: "", // 用户名
        status: "", //
        mobile: "",
        order_low: "",
        order_up: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      this.searchList();
    },
    // 新建/编辑/详情
    openModal(id, isDetail) {
      this.showModel = true;
      this.modelId = id;
      this.isDetail = isDetail;
    },

    async timeReturned(e) {
      if (e.startTime !== "") {
        this.parmValue.order_low = e.startTime;
      } else {
        this.parmValue.order_low = "";
      }
      if (e.endTime !== "") {
        this.parmValue.order_up = e.endTime;
      } else {
        this.parmValue.order_up = "";
      }
      console.log(this.parmValue.order_low, this.parmValue.order_up);
    },
    postRefresh(e) {
      console.log(e);
    },
    // 刷新表格
    async searchList() {
      this.loading = true;
      this.parmValue.username = this.select === "1" ? this.input : "";
      this.parmValue.nickname = this.select === "2" ? this.input : "";
      this.parmValue.mobile = this.select === "3" ? this.input : "";
      const res = await asyncRequest.list(this.parmValue);
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list;
        this.tableData.forEach((v1) => {
          let has1 = v1.username.search("TKR");
          let has2 = v1.username.search("TKS");
          v1.order_goods =
            has1 !== -1
              ? "红运稻2Kg*2"
              : has2 !== -1
              ? "悦享泰康2.5Kg*1"
              : "--";
          // v1.order_goods_num =
          //   v1.order_num + v1.unit + "/" + v1.unit_weight + "kg";
          // v1.order_goods_num_t = v1.order_num * 1 * (v1.unit_weight * 1) + "kg";
        });
        // console.log(this.tableData);
        this.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    /**
     * 导出
     */
    async batchExport() {
      if (!this.loading) {
        // let  item=JSON.parse(JSON.stringify(this.parmValue))
        // delete item['page']
        //  delete item['size']
        this.loading = true;
        let httpType = `application/vnd.ms-excel`;
        axios({
          method: "post",
          url: this.fileUrl + "admin/orderupload",
          responseType: "blob",
          data: {
            start: this.parmValue.order_low,
            end: this.parmValue.order_up,
          },
          headers: {
            Accept: httpType,
          },
        })
          .then((res) => {
            if (res && res.status == 200 && res.data) {
              let blob = new Blob([res.data], {
                type: httpType,
              });
              let url = window.URL.createObjectURL(blob);
              let aLink = document.createElement("a");
              aLink.style.display = "none";
              aLink.href = url;
              aLink.setAttribute("download", `未发货订单导出.xls`);
              document.body.appendChild(aLink);
              aLink.click();
              document.body.removeChild(aLink); //下载完成移除元素
              window.URL.revokeObjectURL(url); //释放掉blob对象

              this.$message.success(`未发货订单导出成功！`);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            } else {
              this.$message.error("请稍后再试！");
              setTimeout(() => {
                this.loading = false;
              }, 500);
            }
          })
          .catch((error) => {
            this.$message.error("请稍后再试！");
            this.loading = false;
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
