<template>
  <div class="terrace pagePadding">
    <ex-table
      v-loading="loading"
      v-if="powers.some((i) => i == '001')"
      :table="table"
      :data="tableData"
      :columns="columns"
      :page="pageInfo"
      :size="size"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
    >
      <template #table-header="{}">
        <div style="width: 100%">
          <el-row style="padding: 0 0 10px 80px">
            <el-col :span="4" style="width: 293px">
              <period-date-picker
                :type="1"
                :width="'135px'"
                :size="searchSize"
                :start="parmValue.start"
                :end="parmValue.end"
                @timeReturned="handleTime"
              />
            </el-col>
            <el-col :span="4" style="width: 160px; padding: 0 0 0 10px">
              <el-select
                v-model="parmValue.status"
                size="mini"
                clearable
                @change="pageInfo.curr = 1;  parmValue.page = 1; searchList();"
              >
                <el-option label="未转单" value="1"></el-option>
                <el-option label="已转单" value="2"></el-option>
              </el-select>
            </el-col>

            <el-col :span="3" style="margin-left:10px">
              <el-switch
                v-model="parmValue.use_type"
                :active-value="usetypeOtions[1].value"
                :inactive-value="usetypeOtions[0].value"
                :active-text="usetypeOtions[1].label"
                :inactive-text="usetypeOtions[0].label"
                @change="
                   pageInfo.curr = 1;
                   parmValue.page = 1;
                   searchList();
                 "
              />
            </el-col>

            <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
              <el-button type="primary" :size="searchSize" @click="searchList">刷新</el-button>
            </el-col>
            <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
              <el-button type="warning" :size="searchSize" @click="restSearch">重置</el-button>
            </el-col>
            <!-- <el-col
              :span="3"
              class="fr"
              style="width: 66px; padding: 0 0 0 10px"
              v-if="powers.includes('003') && !isSupertube"
            >
              <el-button type="success" :size="searchSize" @click="openModal({}, '003')"
                >添加</el-button
              >
            </el-col>-->
          </el-row>
          <el-row>
            <el-col :span="6" style="width: 373px">
              <search-customer
                size="mini"
                :value="parmValue.customer"
                :names="customerName"
                @searchChange="handleCustomerChange"
                placeholder="客户公司"
              />
            </el-col>

            <el-col :span="2" style="padding-left:10px">
              <search-terrace
                :value="parmValue.platform_id"
                :size="'mini'"
                :is-detail="false"
                style="width:115%"
                :is_show="'0'"
                :placeholder="'平台名称'"
                @searchChange="platform_codesearchChange"
              />
            </el-col>

            <el-col span="2" style="padding-left:25px">
              <el-input
                size="mini"
                style="width:110%"
                placeholder="商品名称"
                clearable
                v-model="parmValue.good_name"
                @change="
                   pageInfo.curr = 1;
                   parmValue.page = 1;
                   searchList();
                 "
              />
            </el-col>

            <el-col
              :span="3"
              class="fr"
              style="width: 116px; padding: 0 0 0 10px"
              v-if="powers.includes('013') && !isSupertube"
            >
              <el-button
                class="fr"
                type="primary"
                :size="searchSize"
                @click="downloadTemplate"
              >下载导入模板</el-button>
            </el-col>
            <el-col :span="3" class="fr" style="width: 116px; padding: 0 0 0 10px">
              <el-button
                type="primary"
                class="fr"
                :size="searchSize"
                @click="() => (templateModalVisible = true)"
              >导入订单数据</el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #status="{ scope }">
        <el-tag
          :size="tablebtnSize"
          :type="scope.row.status + '' == '1' ? 'warning' : ''"
          v-text="scope.row.status + '' === '1' ? '未转单' : '已转单'"
        ></el-tag>
      </template>

      <template #order_type="{ scope }">
        <el-tag
          :size="tablebtnSize"
          v-text="
            (xs_order_type_options.find((item) => item.id == scope.row.order_type) || {})
              .label || '--'
          "
        ></el-tag>
      </template>

      <template #order_source="{ scope }">
        <el-tag
          :size="tablebtnSize"
          v-text="
            (
              xs_order_source_options.find((item) => item.id == scope.row.order_source) ||
              {}
            ).label || '--'
          "
        ></el-tag>
      </template>

      <template #operation="{ scope }">
        <el-tooltip
          v-if="((powers.some((i) => i == '007') && !isSupertube) || isSupertube) && Number(scope.row.status) === 2"
          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((i) => i == '005') && !isSupertube) && Number(scope.row.status) === 2"
          effect="dark"
          content="修改"
          placement="top"
        >
          <i class="el-icon-edit tb-icon" @click="openModal(scope.row, '005')"></i>
        </el-tooltip>
      </template>
    </ex-table>
    <no-auth v-else></no-auth>

    <import-template-modal :visible.sync="templateModalVisible" @refresh="() => searchList()" />

    <!-- 弹窗 新增/修改 -->
    <add-edit
      :id="modelId"
      :show-model="showModel"
      :sitem="sitem"
      @refresh="searchList"
      @cancel="showModel = false"
    />
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/netOrderEntry/prestoreRecordingOrders";
import { statusList } from "@/assets/js/statusList";
import mixinPage from "@/mixins/elPaginationHandle";
import roleLevel from "@/assets/js/roleLevel";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import addEdit from "./addEdit";
import companyHelper from "@/mixins/companyHelper";
import { utils, writeFile } from "xlsx";
import importTemplateModal from "./importTemplateModal.vue";
import { usetypeOtions } from "@/assets/js/statusList";
import { template } from "./template";

import {
  xs_order_type_options,
  xs_order_source_options
} from "@/assets/js/statusList";

export default {
  name: "netOrderEnter",
  mixins: [mixinPage, resToken, companyHelper],
  components: {
    addEdit,
    importTemplateModal
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size", "isSupertube"]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran =
        btnList.find(i => i.menu_route == "prestoreRecordingOrders") || {};
      const { action } = tran ?? {};
      return action ?? [];
    }
  },
  data() {
    const mapSelectValue2Query = {
      orderCode: "销售订单编号",
      cgdNo: "采购单编号"
    };

    return {
      usetypeOtions,
      templateModalVisible: false,
      xs_order_type_options,
      xs_order_source_options,
      statusList: statusList,
      roleLevel: roleLevel,
      loading: true,
      showModel: false,
      modelId: "000",
      select: "orderCode",
      sitem: {},
      customerName: "",
      mapSelectValue2Query,
      value: "",
      parmValue: {
        page: 1, // 页码
        size: 15, // 每页显示条数
        use_type: "1",
        platform_id: "",
        start: "",
        end: "",
        customer: "",
        status: ""
      },
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"]
      },
      statusOptions: [
        { id: "0", label: "待发货" },
        { id: "1", label: "待发货完成" },
        { id: "2", label: "发货已完成" },
        { id: "3", label: "订单已取消" }
      ],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0
      },
      columns: [
        {
          prop: "interNo",
          label: "录单编号",
          width: "175px"
        },
        {
          prop: "orderCode",
          label: "订单编号",
          width: "175px"
        },
        {
          prop: "good_name",
          label: "商品名称",
          width: "150"
        },
        {
          prop: "good_num",
          label: "商品数量"
        },
        {
          prop: "sale_price",
          label: "销售单价"
        },
        {
          prop: "sale_total",
          label: "销售总价"
        },
        {
          prop: "status",
          label: "状态",
          _slot_: "status"
        },
        {
          prop: "platform_name",
          label: "平台名称",
          width: "125px"
        },
        {
          prop: "supplierNo",
          label: "供应商公司编号",
          width: "155px"
        },
        {
          prop: "supplierName",
          label: "供应商公司名称",
          width: "125px"
        },
        {
          prop: "customerNo",
          label: "购买方公司编号",
          width: "155px"
        },
        {
          prop: "customerName",
          label: "购买方公司名称",
          width: "125px"
        },
        {
          prop: "companyNo",
          label: "销售方公司编码",
          width: "125px"
        },
        {
          prop: "companyName",
          label: "销售方公司名称",
          width: "125px"
        },
        // {
        //   prop: "company_name",
        //   label: "订单创建人部门",
        //   minWidth: "120px",
        // },
        {
          prop: "apply_name",
          label: "创建人",
          width: "85px"
        },
        // {
        //   prop: "cgder",
        //   label: "供应商负责人",
        //   width: "95",
        // },
        // {
        //   prop: "good_creater",
        //   label: "商品创建人",
        //   width: "85px",
        // },
        {
          prop: "addtime",
          label: "创建时间",
          width: "145px"
        },
        {
          prop: "",
          label: "操作",
          fixed: "right",
          _noset_: true,
          width: "80px",
          _slot_: "operation"
        }
      ]
    };
  },
  mounted() {
    this.searchList();
  },
  methods: {
    downloadTemplate() {
      const workBook = new utils.book_new();
      const workSheet = new utils.json_to_sheet(template);
      utils.book_append_sheet(workBook, workSheet, "sheet");
      writeFile(workBook, "采销订单补录.xlsx", {
        bookType: "xlsx"
      });
    },
    restSearch() {
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0
      };
      this.parmValue = {
        page: 1, // 页码
        size: 15, // 每页显示条数
        start: "",
        end: "",
        customer: "",
        supplierNo: "",
        good_name: ""
      };
      this.value = "";
      this.searchList();
    },
    platform_codesearchChange(e) {
      const { id } = e;
      this.parmValue.platform_id = id || "";
      this.searchList();
    },
    // 新建/编辑/详情
    openModal(row, type) {
      if (type === "003" && !this.currentCompany) {
        this.$message.warning("请选择一家业务公司");
        return;
      }

      this.sitem = row;
      this.modelId = type;
      this.showModel = true;
    },
    // 时间
    async handleTime(e) {
      this.parmValue.start = e.startTime || "";
      this.parmValue.end = e.endTime || "";

      if (
        (this.parmValue.start !== "" && this.parmValue.end !== "") ||
        (this.parmValue.start === "" && this.parmValue.end === "")
      ) {
        this.pageInfo.curr = 1;
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    handleCustomerChange(e) {
      this.parmValue.customer = e.code ? [e.code] : "";
      this.customerName = e.label;
      this.searchList();
    },
    handleSupplierChange(e) {
      this.parmValue.supplierNo = e.code ? [e.code] : "";
      this.searchList();
    },
    /**
     * 启用/禁用
     * @param {String} id id
     * @param {String} status 0-禁用 1-启用
     */
    async changeStatus(id, status) {
      await this.$confirm(`确定要改为${status === "1" ? "禁用" : "启用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.loading = true;
          const model = {
            id: id,
            status: status === "1" ? "0" : "1"
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: ""
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.loading = false;
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 刷新表格
    async searchList() {
      const vm = this;
      if (
        (vm.parmValue.start !== "" && vm.parmValue.end === "") ||
        (vm.parmValue.start == "" && vm.parmValue.end != "")
      ) {
        vm.$message.warning("开始时间和结束时间不能为空");
        return;
      }

      vm.loading = true;
      const res = await asyncRequest.list({
        ...vm.parmValue,
        ...(vm.value ? { [vm.select]: vm.value } : {}),
        ...(vm.parmValue.customer
          ? { customer: vm.parmValue.customer[0] }
          : {}),
        ...(vm.parmValue.supplierNo
          ? { supplierNo: vm.parmValue.supplierNo[0] }
          : {})
      });

      if (res && res.code === 0 && res.data) {
        vm.tableData = res.data.list;
        vm.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await vm.logout();
      } else {
        vm.tableData = [];
        vm.pageInfo.total = 0;
      }
      vm.loading = false;
    }
  }
};
</script>

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