<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-hasPermi="['platform:retail:store:people:list']">
        <div class="container">
          <el-form size="small" label-width="100px">
            <div class="category-name">
              <el-form-item label="商品分类">
                <el-cascader
                  v-model="searchCondition.categoryId"
                  :options="categoryList"
                  :props="props1"
                  @change="searchList">
                </el-cascader>
              </el-form-item>
              <el-form-item label="商户类别">
                <el-select v-model="searchCondition.isSelf" placeholder="请选择" @change="searchList">
                  <el-option label="全部" :value="-1"></el-option>
                  <el-option label="非自营" :value="0"></el-option>
                  <el-option label="自营" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商户名称">
                <el-input
                  v-model.trim="searchCondition.merchantName"
                  placeholder="请输入商户名称"
                  class="selWidth"
                  size="small"
                  clearable
                >
                  <el-button
                    v-hasPermi="['platform:retail:store:people:list']"
                    slot="append"
                    icon="el-icon-search"
                    size="small"
                    @click="searchList"
                  />
                </el-input>
              </el-form-item>
            </div>
            <div class="keyword-distribution">
              <el-form-item label="商品搜索：">
                <el-input
                  v-model.trim="searchCondition.keywords"
                  placeholder="请输入商品名称、关键字"
                  class="selWidth"
                  size="small"
                  clearable
                >
                  <el-button
                    v-hasPermi="['platform:retail:store:people:list']"
                    slot="append"
                    icon="el-icon-search"
                    size="small"
                    @click="searchList"
                  />
                </el-input>
              </el-form-item>
              <el-form-item label="参与分销">
                <el-select v-model="searchCondition.isBrokerage" placeholder="请选择" @change="searchList">
                  <el-option label="全部" :value="-1"></el-option>
                  <el-option label="参与" :value="1"></el-option>
                  <el-option label="不参与" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="btns">
        <div class="btn" @click="batchSetCommission">批量设置佣金</div>
        <div class="btn" @click="batchSetDistributionStatus">批量取消分销</div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="goodsList"
        style="width: 100%"
        size="mini"
        class="table"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column label="商品图" min-width="100" align="center">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image :src="scope.row.image" :preview-src-list="[scope.row.avatar]" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="130" align="center" />
        <el-table-column prop="price" label="商品售价" min-width="100" align="center" />
        <el-table-column prop="merchantName" label="商户名称" min-width="130" align="center" />
        <el-table-column prop="" label="参与分销" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.isBrokerage === 1 ? '参与' : '不参与' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="佣金" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.isSub === 1 ? '自定义' : '默认' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="brokerageConfig" label="分佣规则" min-width="150" align="center" />
        <el-table-column label="操作" min-width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openDefautborkerageDialog(scope.row.id, scope.row.name)"
              :disabled="scope.row.isBrokerage !== 1"
              >设置佣金</el-button
            >
            <span style="color: #409eff;">|</span>
            <el-button
              type="text"
              size="small"
              @click="setDistributionStatus(scope.$index, [scope.row.id], scope.row.isBrokerage)"
              >{{ scope.row.isBrokerage === 1 ? '取消分销' : '开启分销' }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="limit"
          :current-page="page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <Defaultbrokerage v-if="visible" :visible.sync="visible" :params="defaultborkerageParams" pageType="merchandise" :productName="productName"></Defaultbrokerage>
  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import { getDistributionGoodsApi, setDistributionStatusApi } from '@/api/distribution';
import { productCategoryApi } from '@/api/product';
import cardsData from '@/components/cards/index';
import Defaultbrokerage from '../config/defaultbrokerage.vue';
import { checkPermi } from '@/utils/permission'; // 权限判断函数

export default {
  name: 'AccountsUser',
  components: { cardsData, Defaultbrokerage },
  data() {
    return {
      listLoading: false,
      visible: false,
      goodsList: [],
      categoryList: [],
      selectionList: [],
      searchCondition: {
        isBrokerage: null,
        isSelf: null,
        categoryId: null,
        keywords: '',
        merchantName: ''
      },
      props1: {
        label: 'name',
        value: 'id',
        children: 'childList',
        multiple: false,
        emitPath: false
      },
      defaultborkerageParams: {
        productId: null
      },
      type: 1,
      page: 1,
      total: 0,
      totalPage: null,
      limit: 20,
      productName: ''
    };
  },
  mounted() {
    this.getCategoryList();
    if (checkPermi(['platform:retail:store:people:list'])) this.getList();
  },
  methods: {
    checkPermi,

    getList() {
      this.listLoading = true;
      let params = {
        page: this.page,
        limit: this.limit,
        type: this.type
      }
      this.searchCondition.categoryId ? params.categoryId = this.searchCondition.categoryId : null; // 搜索商品分类
      this.searchCondition.isSelf >= 0 ? params.isSelf = this.searchCondition.isSelf : null; // 搜索商户类别
      this.searchCondition.merchantName ? params.merchantName = this.searchCondition.merchantName : null; // 搜索商户名
      this.searchCondition.keywords ? params.keywords = this.searchCondition.keywords : null; // 搜索关键字
      this.searchCondition.isBrokerage >= 0 ? params.isBrokerage = this.searchCondition.isBrokerage : null; // 搜索是否参与分销
      
      getDistributionGoodsApi(params)
        .then((res) => {
          let { limit, list, page, total, totalPage } = res;
          this.goodsList = list;
          this.limit = limit;
          this.page = page;
          this.total = total;
          this.totalPage = totalPage;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },

    getCategoryList() {
      productCategoryApi().then(res => {
        this.categoryList = this.changeNodes(res);
      }).catch(() => {});
    },

    /** tree去除 childList=[] 的结构**/
    changeNodes (data) {
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          if (!data[i].isShow) {
            data[i].disabled = true;
          }
          if (!data[i].childList || data[i].childList.length < 1) {
            data[i].childList = undefined;
          } else {
            this.changeNodes(data[i].childList);
          }
        }
      }

      return data;
    },
    
    searchList() {
      this.page = 1;
      this.getList()
    },

    handleSelectionChange(selection) {
      this.selectionList = selection;
    },

    batchSetCommission() {
      if (!this.selectionList.length) {
        this.$message({
          message: '至少选择一个商品进行设置',
          type: 'warning',
          showClse: true
        });
        return;
      }

      let ids = [];
      this.selectionList.forEach(el => {
        ids.push(el.id);
      });
      this.defaultborkerageParams.productId = ids;
      this.visible = true;
    },

    batchSetDistributionStatus() {
      if (!this.selectionList.length) {
        this.$message({
          message: '至少选择一个商品进行设置',
          type: 'warning',
          showClse: true
        });
        return;
      }
      
      let ids = [];
      this.selectionList.forEach(el => {
        ids.push(el.id);
      });
      let params = {
        productIdList: ids,
        isBrokerage: 0
      };

      this.$confirm('确定商品不参与分销', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setDistributionStatusApi(params).then(res => {
          this.getList();
        }).catch(() => {});
      }).catch(() => {});
    },

    openDefautborkerageDialog(id, name) {
      this.defaultborkerageParams.productId = [id];
      this.productName = name;
      this.visible = true;
    },

    setDistributionStatus(index, ids, isBrokerage) {
      let params = {
        productIdList: ids,
        isBrokerage: isBrokerage === 1 ? 0 : 1
      };

      if (isBrokerage) {
        this.$confirm('确定商品不参与分销', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          setDistributionStatusApi(params).then(res => {
            this.goodsList[index].isBrokerage = isBrokerage === 1 ? 0 : 1;
          }).catch(() => {});
        }).catch(() => {});
      } else {
        setDistributionStatusApi(params).then(res => {
          this.goodsList[index].isBrokerage = isBrokerage === 1 ? 0 : 1;
        }).catch(() => {});
      }
    },

    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },

    pageChange(page) {
      this.page = page;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.selWidth {
  width: 350px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}

/* update */
.category-name,
.keyword-distribution {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.btns {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;

  .btn {
    width: 120px;
    height: 30px;
    border: 1px solid #CCCCCC;
    box-sizing: border-box;
    border-radius: 5px;
    font-size: 12px;
    text-align: center;
    line-height: 28px;
  }

  .btn:last-child {
    margin-left: 10px;
  }
}
</style>
