<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="所属商家" prop="businessId">
        <el-select v-model="queryParams.businessId" filterable placeholder="请选择所属商家" size="small" clearable style="width: 100%" @change="businessIdChange">
          <el-option v-for="(v,i) in shopList" :key="i" :label="v.businessName" :value="v.businessId" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="businessProductCategoryId">
        <el-select v-model="queryParams.businessProductCategoryId" placeholder="请选择商品分类" size="small" clearable style="width: 100%">
          <el-option v-for="(v,i) in shopTypeList" :key="i" :label="v.categoryName" :value="v.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="shelvedStatus">
        <el-select v-model="queryParams.shelvedStatus" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <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" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="是否奖励兑换豆" prop="giftPoints" label-width="130px">
        <el-select v-model="queryParams.giftPoints" placeholder="请选择是否奖励兑换豆" clearable size="small" style="width: 240px">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="券码类型" prop="codeType" label-width="130px">
        <el-select v-model="queryParams.codeType" placeholder="请选择券码类型" clearable size="small" style="width: 240px">
          <el-option v-for="(v,i) in codeTypeList" :key="i" :label="v.label" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="mini" @click="handleAdd">新增</el-button>
        <el-button type="primary" plain size="mini" @click="handleExport">导出商品</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="businessProductId" width="120" />
      <el-table-column label="商品分类" align="center" prop="businessProductCategoryName" />
      <el-table-column label="商品名称" align="center" prop="title" />
      <el-table-column label="价格（元）" align="center" prop="sellingPrice" />
      <el-table-column label="所属商家" align="center" prop="businessName" />
      <el-table-column label="可售库存" align="center" prop="stock" />
      <el-table-column label="已售数量" align="center" prop="salesVolume" />
      <el-table-column label="是否分销" align="center" prop="shareMoney">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.shareMoney">是</el-tag>
          <el-tag type="danger" v-if="!row.shareMoney">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="券码类型" align="center" prop="codeType">
        <template slot-scope="{row}">
          <span :class="{active:row.codeType==1}" @click="goCouponCodeDatabase(row)" v-for="(v,i) in codeTypeList" :key="i" v-if="row.codeType==v.value">{{v.label}}</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" prop="createTime" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shelvedTime,'{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" sortable="custom" prop="sortNum" />
      <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">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row,'show')">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'edit')">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" 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" />

  </div>
</template>

<script>
import { businessList, businessProductCategoryList } from "@/api/shop"
import { businessProductPage, businessProductStatus, businessProductDel } from "@/api/goods.js";
export default {
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessName: undefined,
        businessProductCategoryId: undefined,
        shelvedStatus: undefined,
        giftPoints: undefined
      },
      daterangeCreateTime: [],
      shopTypeList: [],
      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()
  },
  methods: {
    getShopList () {
      let param = {
        shelvedStatus: true
      }
      businessList(param).then(res => {
        this.shopList = res.data
      })
    },
    //  导出商品
    handleExport () {
      this.download('/ticket/businessProduct/export', {
        ...this.queryParams
      }, `商品_${new Date().getTime()}.xlsx`)
    },
    sortChange (e) {
      this.queryParams.sortOrder = Boolean(e.order == "ascending");
      this.handleQuery()
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      const ids = row.businessProductId || this.ids;
      let statusText = row.shelvedStatus ? '下架' : '上架';
      this.$modal.confirm('是否确认' + statusText + '商品名称为"' + row.title + '"的数据项？').then(() => {
        this.loading = true;
        return businessProductStatus(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    getGoodsTypeList (businessId) {
      businessProductCategoryList(businessId).then(res => {
        this.shopTypeList = res.data
      })
    },
    businessIdChange (e) {
      this.queryParams.businessProductCategoryId = undefined;
      if (e) {
        this.getGoodsTypeList(e)
      } else {
        this.shopTypeList = []
      }
    },
    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];
      }
      businessProductPage(this.queryParams).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.businessProductId,
            title: row.title,
            queryParams: JSON.stringify(this.queryParams)
          }
        })
      }
    },
    handleUpdate (row, type) {
      this.$router.push({
        path: '/goods/details',
        query: {
          businessProductId: row.businessProductId,
          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.businessProductId || this.ids;
      this.$modal.confirm('是否确认删除商品名称为"' + row.title + '"的数据项？').then(() => {
        this.loading = true;
        return businessProductDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
}
</script>

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