<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" :size="ELsize" label-width="auto">
      <el-form-item label="平台商品分类" prop="merchantCategoryId">
        <el-cascader v-model="queryParams.merchantCategoryId" :options="merchantCategoryList" :props="{
          expandTrigger: 'hover',
          label: 'categoryName',
          value: 'categoryId',
          children: 'childrenList',
          checkStrictly: true,
        }" :show-all-levels="false" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="商家商品分类" prop="productCategoryId">
        <el-cascader v-model="queryParams.productCategoryId" :options="shopTypeList" :props="{
          expandTrigger: 'hover',
          label: 'categoryName',
          value: 'categoryId',
          children: 'childrenList',
          checkStrictly: true,
        }" :show-all-levels="false" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="商品名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品类型" prop="productUseType">
        <el-select v-model="queryParams.productUseType" placeholder="请选择商品类型" clearable style="width: 240px">
          <el-option label="商城商品" :value="0" />
          <el-option label="店铺商品" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择状态" clearable>
          <el-option v-for="item in AuditStatusOption" :key="item.value" :label="item.label" :value="item.value" />
          <!-- <el-option label="待审核" :value="0" />
          <el-option label="审核拒绝" :value="5" />
          <el-option label="审核通过" :value="10" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="shelvedStatus">
        <el-select v-model="queryParams.shelvedStatus" placeholder="请选择状态" clearable>
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime" 
          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" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" :size="ELsize" @click="handleAdd">新增</el-button>
        <!-- <el-button type="primary" plain :size="ELsize" @click="handleExport"
          >导出商品</el-button
        > -->
        <!-- <el-button type="primary" plain :size="ELsize" @click="handleImport"
          >导入商品</el-button
        > -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-tabs v-model="productPaymentMode" @tab-click="handleClick">
        <el-tab-pane label="普通商品" name="0"></el-tab-pane>
        <el-tab-pane label="积分商品" name="1"></el-tab-pane>
      </el-tabs>
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" @sort-change="sortChange"
      :border="TableBorder" :size="ELTableSize">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="{$index}">
          {{ $getTableIndex(queryParams, $index + 1) }}
        </template>
      </el-table-column>
      <el-table-column label="平台商品分类" align="center" prop="merchantCategoryName" show-overflow-tooltip />
      <el-table-column label="商家商品分类" align="center" prop="productCategoryList" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <template v-if="row.productCategoryList">
            <span v-for="(v, index) in row.productCategoryList" :key="v.categoryId">{{
              `${v.categoryName}${index != row.productCategoryList.length - 1 ? "," : ""
              }`
            }}</span>
          </template>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="供应商" align="center" prop="supplierName" show-overflow-tooltip>
        <template slot-scope="{ row }">
          {{ row.supplierName | TableItemEmpty }}
        </template>
      </el-table-column>
      <el-table-column label="初始销量" align="center" prop="initialSales" />
      <el-table-column label="真实销量" align="center" prop="realSales" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="商品类型" align="center" prop="productUseType">
        <template slot-scope="{ row }">
          <span v-if="row.productUseType == '0'">商城商品</span>
          <span v-if="row.productUseType == '1'">店铺商品</span>
          <!-- <span v-if="row.productPaymentMode == '2'">积分抵扣</span> -->
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="{ row }">
          <el-tag v-if="row.auditStatus == 0">待审核</el-tag>
          <el-tag type="danger" v-if="row.auditStatus == 5">拒绝</el-tag>
          <el-tag type="success" v-if="row.auditStatus == 10">通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒绝理由" align="center" prop="auditRemark" width="100" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <span style="cursor: pointer" v-if="row.auditRemark && row.auditStatus == 5">{{ row.auditRemark }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="shelvedStatus">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.shelvedStatus">上架</el-tag>
          <el-tag type="danger" v-if="!row.shelvedStatus">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" sortable="orderIndex" prop="orderIndex" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="140">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button :size="ELTableSize" type="text" @click="handleUpdate(scope.row, 'show')">查看</el-button>
          <el-button :size="ELTableSize" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row, 'edit')">修改</el-button>
          <el-button :size="ELTableSize" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
          <el-button :size="ELTableSize" type="text" @click="setStatus(scope.row)">{{
            scope.row.shelvedStatus ? "下架" : "上架"
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 导入商品 -->
    <importGoods ref="importGoodsRef" />
  </div>
</template>

<script>
import { productCategoryTree } from "@/api/goodsClassify";
import { merchantCategoryTree } from "@/api/platformClass";
import {
  shopProductPage,
  shopProductStatus,
  shopProductDel,
} from "@/api/goods.js";
import importGoods from "./components/importGoods";
import { AuditStatusOption } from "@/utils/statusEnum";

export default {
  components: { importGoods },
  data() {
    return {
      AuditStatusOption,
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      productPaymentMode: "0",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantCategoryId: undefined,
        productCategoryId: undefined,
        title: undefined,
        auditStatus: undefined,
        shelvedStatus: undefined,
      },
      daterangeCreateTime: [],
      shopTypeList: [], // 商家商品类型
      merchantCategoryList: [], // 平台商品类型
      // shopList: [],
      codeTypeList: [
        {
          label: "券码库",
          value: 1,
        },
        {
          label: "第三方系统",
          value: 2,
        },
        {
          label: "商家自建券码库",
          value: 3,
        },
      ],
    };
  },
  created() {
    let queryParams = localStorage.getItem("queryParams");
    if (queryParams) {
      this.queryParams = JSON.parse(queryParams);
      localStorage.setItem("queryParams", "");
    }
    // this.getShopList();
    this.getList();
    this.getGoodsTypeList();
    this.getPlatformCategoryTree();
  },
  methods: {
    // getShopList () {
    //   let param = {
    //     shelvedStatus: true
    //   }
    //   businessList(param).then(res => {
    //     this.shopList = res.data
    //   })
    // },
    handleImport() {
      this.$refs.importGoodsRef.open();
    },
    //  导出商品
    handleExport() {
      const queryParams = {
        ...this.queryParams,
      };
      if (this.queryParams.productCategoryId) {
        queryParams.productCategoryId =
          this.queryParams.productCategoryId[
          this.queryParams.productCategoryId.length - 1
          ];
      }
      if (this.queryParams.merchantCategoryId) {
        queryParams.merchantCategoryId =
          this.queryParams.merchantCategoryId[
          this.queryParams.merchantCategoryId.length - 1
          ];
      }
      this.download(
        "/shop/product/export",
        {
          ...queryParams,
          productPaymentMode: this.productPaymentMode,
        },
        `商品_${new Date().getTime()}.xlsx`
      );
    },
    // 平台商品分类
    getPlatformCategoryTree() {
      merchantCategoryTree().then((res) => {
        if (res.code == 200) {
          this.merchantCategoryList = res.data;
        }
      });
    },
    sortChange(e) {
      console.log("e = ", e)
      const Asc = {
        "descending": "desc",
        "ascending": "asc"
      }
      // this.queryParams.sortOrder = Boolean(e.order == "ascending"); /desc
      // this.queryParams.orderByColumn = e.prop;
      // this.queryParams.isAsc = Asc[e.order] || undefined;
      // this.handleQuery();
      if (Asc[e.order]) {
        this.queryParams.orderByColumn = e.prop ? "tp.order_index" : "";
      } else {
        this.queryParams.orderByColumn = "";
      }
      this.queryParams.isAsc = Asc[e.order] || undefined;

      this.handleQuery();
    },
    /** 上下架按钮操作 */
    setStatus(row) {
      const ids = row.productId || this.ids;
      let statusText = row.shelvedStatus ? "下架" : "上架";
      this.$modal
        .confirm(
          "是否确认" + statusText + '商品名称为"' + row.title + '"的数据项？'
        )
        .then(() => {
          this.loading = true;
          return shopProductStatus(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess(statusText + "成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getGoodsTypeList() {
      productCategoryTree().then((res) => {
        if (res.code == 200) {
          this.shopTypeList = res.data;
        }
      });
    },
    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];
      }
      const Params = {
        ...this.queryParams,
        productPaymentMode: this.productPaymentMode,
      };
      if (this.queryParams.productCategoryId) {
        Params.productCategoryId =
          this.queryParams.productCategoryId[
          this.queryParams.productCategoryId.length - 1
          ];
      }
      if (this.queryParams.merchantCategoryId) {
        Params.merchantCategoryId =
          this.queryParams.merchantCategoryId[
          this.queryParams.merchantCategoryId.length - 1
          ];
      }
      shopProductPage(Params).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCnAreaTree() {
      cnAreaTree().then((res) => {
        this.areaTrea = res.data?.children;
      });
    },
    // 省市区选择
    handleChange(value) {
      this.queryParams.provinces = value;
      this.queryParams.provinceCode = value[0];
      this.queryParams.provinceName =
        this.$refs["refSubCat"].getCheckedNodes()[0].pathLabels[0];
      this.queryParams.cityCode = value[1];
      this.queryParams.cityName =
        this.$refs["refSubCat"].getCheckedNodes()[0].pathLabels[1];
      this.queryParams.areaCode = value[2];
      this.queryParams.areaName =
        this.$refs["refSubCat"].getCheckedNodes()[0].pathLabels[2];
    },
    handleAdd() {
      this.$router.push({
        path: "/goods/details",
      });
    },
    goCouponCodeDatabase(row) {
      if (row.codeType == 1) {
        this.$router.push({
          path: "/goods/couponCodeDatabase",
          query: {
            productId: row.productId,
            title: row.title,
            queryParams: JSON.stringify(this.queryParams),
          },
        });
      }
    },
    handleUpdate(row, type) {
      this.$router.push({
        path: "/goods/details",
        query: {
          productId: row.productId,
          type: type || "edit",
          queryParams: JSON.stringify(this.queryParams),
        },
      });
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        shelvedStatus: undefined,
        orderIndex: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.productId || this.ids;
      this.$modal
        .confirm('是否确认删除商品名称为"' + row.title + '"的数据项？')
        .then(() => {
          this.loading = true;
          return shopProductDel(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleClick(tab, event) {
      this.handleQuery();
    },
  },
};
</script>

<style lang="scss" scoped>
.active {
  color: #1890ff;
  cursor: pointer;
}
</style>
