<template>
  <div class="app-container">
    <div class="screen2-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="2" :lg="3" style="opacity: 0;">.</el-col>

        <el-col :xs="24" :sm="20" :lg="18">
          <el-form ref="form" :model="screenForm" label-width="80px">
            <div class="search">
              <el-input v-model="screenForm.keyword" placeholder="想快速搜索什么商品呢？输入商品名称，商品id，商品分类都可快速找到" class="input-with-select" clearable @change="getListByScreen">
                <el-button slot="append" icon="el-icon-search" @click="getListByScreen"></el-button>
              </el-input>
            </div>
            <div class="screen clearfix">
              <el-row :gutter="20">
                <el-col :xs="12" :sm="12" :lg="4">
                  <el-form-item label-width="0">
                    <el-cascader
                      v-model="screenForm.classify"
                      :options="classifyList"
                      :props="{ label: 'name', value: 'categoryId' }"
                      size="small"
                      @change="getListByScreen">
                    </el-cascader>
                    <!-- <el-select v-model="screenForm.classify" placeholder="全部" size="small" @change="getListByScreen">
                      <el-option label="商品分类" value=""></el-option>
                      <el-option :label="item.name" :value="item.categoryId" v-for="item in classifyList" :key="item.categoryId"></el-option>
                    </el-select> -->
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :lg="4">
                  <el-form-item label-width="0">
                    <el-select v-model="screenForm.status" placeholder="全部" size="small" @change="getListByScreen">
                      <el-option label="上下架状态" value=""></el-option>
                      <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_status" :key="index"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :lg="8">
                  <el-form-item label="销售价格：" label-width="90px">
                    <el-input v-model="screenForm.price1" size="small" @change="getListByScreen" clearable ></el-input>
                    <span>至</span>
                    <el-input v-model="screenForm.price2" size="small" @change="getListByScreen" clearable ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :lg="8">
                  <el-form-item label="分销金额：" label-width="90px">
                    <el-input v-model="screenForm.amount1" size="small" @change="getListByScreen" clearable ></el-input>
                    <span>至</span>
                    <el-input v-model="screenForm.amount2" size="small" @change="getListByScreen" clearable ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </el-col>

        <el-col :xs="24" :sm="2" :lg="3" style="opacity: 0;">.</el-col>
      </el-row>
    </div>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="addOrEdit('add')">添加商品</el-button>
          <el-button size="small" @click="batchOperation('on')">批量上架</el-button>
          <el-button size="small" @click="batchOperation('off')">批量下架</el-button>
          <el-button size="small" @click="batchOperation('module')">批量设置模块</el-button>
          <el-button size="small" @click="batchOperation('freight')">批量设置运费</el-button>
        </div>
      </div>

      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe @selection-change="handleTableSelection">
          <el-table-column align="center" type="selection" width="55" fixed></el-table-column>
          <el-table-column align="center" label="商品图片" prop="imgUrl" width="85">
            <template slot-scope="scope">
              <el-image style="width: 60px; height: 60px; display: block;" :src="scope.row.imgUrl" :preview-src-list="[scope.row.imgUrl]" fit="cover"></el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag size="small" :type="scope.row.status ? 'success':'danger'">{{ scope.row.status ? '上架':'下架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="参与产品数量" prop="goodsNums" min-width="130" sortable></el-table-column>
          <el-table-column align="center" label="最低销售价" prop="packageMinAmount" min-width="120" sortable></el-table-column>
          <el-table-column align="center" label="最低分佣金额" prop="packageMinShareAmount" min-width="130" sortable></el-table-column>
          <el-table-column align="center" label="使用优惠券" prop="useCoupon" min-width="110">
            <template slot-scope="scope">
              {{scope.row.useCoupon | couponFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="适用范围" prop="packageUserType" min-width="110">
            <template slot-scope="scope">
              {{scope.row.packageUserType | rangeFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="订单数量" prop="orderNums" min-width="110" sortable></el-table-column>
          <el-table-column align="center" label="订单总金额" prop="orderPayAmount" min-width="120" sortable></el-table-column>

          <el-table-column align="center" label="商户" prop="companyName" min-width="120"></el-table-column>

          <el-table-column align="center" label="操作" width="280" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrEdit('edit', scope.row.goodsId)">编辑</el-button>
              <el-popconfirm style="margin: 0 10px;" title="确定删除吗？" @onConfirm="delItem(scope.row.goodsId, scope.row.goodsSpecId)" >
                <el-button slot="reference" type="text" style="color: #F56C6C;">删除</el-button>
              </el-popconfirm>
              <el-button type="text" @click="openOrderDetail(scope.row.goodsId)">订单详情</el-button>
              <el-button type="text" @click="handleExport(scope.row.goodsId)">导出订单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 批量设置模块 -->
    <el-dialog :title="'设置模块 (已选择' + tableSelection.length + '件商品)'" :visible.sync="setModuleVisible" :show-close="false" width="30%" :close-on-click-modal="false">
      <el-form ref="setModuleForm" :model="setModuleForm" :rules="setModuleFormRules" label-position="left" label-width="80px">
        <el-form-item label="说明模块" prop="module">
          <el-select v-model="setModuleForm.module" placeholder="请选择说明模块" style="width: 250px;">
            <el-option v-for="item in moduleList" :key="item.commonTemplateId" :label="item.name" :value="item.commonTemplateId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSetModuleForm">取 消</el-button>
        <el-button type="primary" @click="submitSetModuleForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量设置运费 -->
    <el-dialog :title="'设置运费 (已选择' + tableSelection.length + '件商品)'" :visible.sync="setFreightVisible" :show-close="false" width="30%" :close-on-click-modal="false">
      <el-form ref="setFreightForm" :model="setFreightForm" :rules="setFreightFormRules" label-position="left" label-width="80px">
        <el-form-item label="运费模版" prop="freight">
          <el-select v-model="setFreightForm.freight" placeholder="请选择运费模版" style="width: 250px;">
            <el-option v-for="item in freightList" :key="item.freightTemplateId" :label="item.name" :value="item.freightTemplateId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSetFreightForm">取 消</el-button>
        <el-button type="primary" @click="submitSetFreightForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情 -->
    <el-dialog title="订单详情" :visible.sync="orderDialog" :show-close="false" width="70%" :close-on-click-modal="false">
      <div class="table" style="margin: 10px 0 20px;">
        <el-table 
          v-loading="orderTable_listLoading" 
          :data="orderTable_dataList" 
          element-loading-text="Loading" 
          tooltip-effect="dark" 
          style="width: 100%" 
          max-height="400">
          <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
          <el-table-column align="center" prop="orderId" label="订单编号" min-width="180" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="orderTitle" label="商品名称" min-width="200" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="totalNum" label="件数" min-width="100"></el-table-column>
          <el-table-column align="center" prop="payAmount" label="订单金额" min-width="100"></el-table-column>
          <el-table-column align="center" prop="totalShareAmount" label="佣金金额" min-width="100"></el-table-column>
          <el-table-column align="center" prop="orderStatus" label="订单状态" min-width="100">
            <template slot-scope="scope">
              {{scope.row.orderStatus | statusFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="下单时间" min-width="160"></el-table-column>
          <el-table-column align="center" label="操作" min-width="80">
            <template slot-scope="scope">
              <el-button type="text" @click="toOrderDetail(scope.row.orderId)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @current-change="orderTableCurrentChange"
            :current-page="orderTable_currentPage"
            :page-size="orderTable_pageSize"
            background
            layout="prev, pager, next"
            :total="orderTable_listTotal">
          </el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { deleteGoods, getClassifyList, getGoodsStateCount, goodsPutOn, goodsPutOff, checkSeckill, getModuleList, setCommomModule, setFreight, getFreightList } from '@/api/goods'
import { getGoodsList, getOrderList } from '@/api/package'
import { downloadFiles } from '@/utils/util'

export default {
  filters: {
    couponFilter(val) {
      const MAP = {
        0: '不可使用',
        1: '所有优惠券',
        2: '满减券',
        3: '商品券',
      }
      return MAP[val];
    },
    rangeFilter(val) {
      const MAP = {
        0: '指定人员',
        1: '所有人',
        2: '普通用户',
        3: '业务员',
      }
      return MAP[val];
    },
    statusFilter(val) {
      const MAP = {
        NOPAY: '待付款',
        DFH: '待发货',
        YFH: '已发货',
        OVER: '已完成',
        CLOSE: '已关闭',
        REFUND: '售后',
      }
      return MAP[val];
    }
  },

  data() {
    return {
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数

      screenForm: {
        type: '',
        keyword: '',
        classify: '',
        status: '',
        price1: '',
        price2: '',
        amount1: '',
        amount2: '',
      },
      select_status: [ // 筛选字段 - 状态
        { label: '上架', value: true },
        { label: '下架', value: false }
      ],
      classifyList: [],
      goodsStateCount: {
        total: 0,
        csz: 0,
        ysq: 0,
        ckz: 0,
        hdz: 0,
      },

      tableSelection: [],

      setModuleVisible: false,
      moduleList: [],
      setModuleForm: {
        module: '',
      },
      setModuleFormRules: {
        module: [
          { required: true, message: '请选择说明模块', trigger: 'change' }
        ],
      },

      setFreightVisible: false,
      freightList: [],
      setFreightForm: {
        freight: '',
      },
      setFreightFormRules: {
        freight: [
          { required: true, message: '请选择运费模块', trigger: 'change' }
        ],
      },

      detailId: '',
      orderDialog: false, // 订单详情 - 弹窗
      orderTable_dataList: null, // 订单详情 - 列表数据
      orderTable_listLoading: true, // 订单详情 - 列表加载loading
      orderTable_currentPage: 1, // 订单详情 - 当前页码
      orderTable_pageSize: 10, // 订单详情 - 每页数量
      orderTable_listTotal: 0, // 订单详情 - 列表总数

    }
  },
  created() {
    this.getList();

    this.getClassifyList();
  },
  methods: {

    getClassifyList() {
      let params = {
        name: '',
        status: true
      };
      getClassifyList(params).then(res => {
        res.data.unshift({
          name: '全部',
          categoryId: '',
          children: null,
        });
        this.classifyList = res.data;
      })
    },

    getList() {
      this.listLoading = true;

      let categoryId = '';
      if(this.screenForm.classify) {
        categoryId = this.screenForm.classify[1];
      }

      let params = {
        goodsTypes: 'PACKAGE',
        flag: this.screenForm.type,
        keyword: this.screenForm.keyword,
        categoryId: categoryId,
        status: this.screenForm.status,
        startPrice: this.screenForm.price1,
        endPrice: this.screenForm.price2,
        startShare: this.screenForm.amount1,
        endShare: this.screenForm.amount2,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getGoodsList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })

      getGoodsStateCount({}).then(res => {
        this.goodsStateCount = res.data;
      })
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 筛选后重新获取列表
    getListByScreen() {
      this.currentPage = 1;
      this.getList();
    },

    // 切换类型
    changeType(type) {
      this.screenForm.type = type;
      this.getListByScreen();
    },

    // 删除商品
    delItem(goodsId, goodsSpecId) {
      deleteGoods({
        goodsId,
        goodsSpecId
      }).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 添加商品
    addOrEdit(type, id) {
      if(type == 'add') {
        this.$router.push({
          path: '/activity/package_add',
          query: {}
        })
      }else {
        this.$router.push({
          path: '/activity/package_add',
          query: {
            id
          }
        })
      }
    },

    // 表格选择列
    handleTableSelection(val) {
      this.tableSelection = val;
    },

    // 批量操作
    batchOperation(type) {
      if(this.tableSelection.length < 1) {
        return this.$errorMsg('至少选择一个商品');
      }
      const typeMap = {
        on: '上架',
        off: '下架',
        module: '设置模块',
        freight: '设置运费'
      };

      // 批量上架/批量下架
      if(['on', 'off'].includes(type)) {
        this.$confirm('您确定要批量'+typeMap[type]+'选中商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let goodsIds = [];
          this.tableSelection.forEach(item => {
            goodsIds.push(item.goodsId);
          });
          // 批量上架
          if(type == 'on') {
            goodsPutOn(goodsIds).then(res => {
              this.$successMsg();
              this.getList();
            })
          }
          // 批量下架
          else if(type == 'off') {
            checkSeckill(goodsIds).then(res => {
              if(res.data && res.data.length > 0) {
                let goodsNames = [];
                res.data.forEach(item => {
                  let index = this.$findElem(this.tableSelection, 'goodsId', item);
                  goodsNames.push('【' + this.tableSelection[index].goodsName + '】');
                })
                this.$confirm('你所选中的商品'+goodsNames.join('、')+'正在参与秒杀活动，是否确定下架？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  goodsPutOff(goodsIds).then(res => {
                    this.$successMsg();
                    this.getList();
                  })
                }).catch(() => {});
              }else {
                goodsPutOff(goodsIds).then(res => {
                  this.$successMsg();
                  this.getList();
                })
              }
            })
          }

        }).catch(() => {});
      }
      // 批量设置模块
      else if(type == 'module') {
        this.getModuleList();
        this.setModuleVisible = true;
      }

      // 批量设置运费
      else if(type == 'freight') {
        this.getFreightList();
        this.setFreightVisible = true;
      }

    },

    // 获取模块列表
    getModuleList() {
      getModuleList({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.moduleList = res.data.records;
      })
    },

    // 取消 设置模块
    cancelSetModuleForm(){
      this.setModuleVisible = false;
      this.$refs.setModuleForm.resetFields();
    },

    // 提交 设置模块
    submitSetModuleForm() {
      let goodsIds = [];
      this.tableSelection.forEach(item => {
        goodsIds.push(item.goodsId);
      });
      setCommomModule({
        goodsIdList: goodsIds,
        templateId: this.setModuleForm.module
      }).then(res => {
        this.cancelSetModuleForm();
        this.$successMsg();
        this.getList();
      })
    },

    // 获取运费模版列表
    getFreightList() {
      getFreightList({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.freightList = res.data.records;
      })
    },

    // 取消 设置运费
    cancelSetFreightForm(){
      this.setFreightVisible = false;
      this.$refs.setFreightForm.resetFields();
    },

    // 提交 设置运费
    submitSetFreightForm() {
      let goodsIds = [];
      this.tableSelection.forEach(item => {
        goodsIds.push(item.goodsId);
      });
      setFreight({
        goodsIdList: goodsIds,
        freightTemplateId: this.setFreightForm.freight
      }).then(res => {
        this.cancelSetFreightForm();
        this.$successMsg();
        this.getList();
      })
    },

    // 订单详情 - 获取列表
    getOrderList() {
      getOrderList({
        pageNum: this.orderTable_currentPage,
        pageSize: this.orderTable_pageSize,
        goodsId: this.detailId
      }).then(res => {
        this.orderTable_dataList = res.data.records;
        this.orderTable_listTotal = res.data.total;
        this.orderTable_listLoading = false;
      })
    },

    // 订单详情 - 打开弹窗
    openOrderDetail(id) {
      this.detailId = id;
      this.orderDialog = true;
      this.orderTable_currentPage = 1;
      this.getOrderList();
    },

    // 订单详情 - 更改列表当前页
    orderTableCurrentChange(val) {
      this.orderTable_currentPage = val;
      this.getOrderList();
    },

    // 订单详情
    toOrderDetail(orderId) {
      let {href} = this.$router.resolve({path: `/order/detail?orderId=${orderId}`});
      window.open(href, '_blank');
    },

    // 导出
    handleExport(id) {
      let screenData = {
        goodsId: id
      };
      downloadFiles('order/export', screenData);
    },

  }

}

</script>

<style scoped lang="scss">
  .tab-container {
    .tab-list {
      .item {
        float: left;
        font-size: 14px;
        margin-right: 20px;
        cursor: pointer;
        line-height: 32px;
        &.current {
          color: #409EFF;
        }
      }
    }
  }

  .screen2-container {
    .search {
      margin-top: 30px;
    }
    .screen {
      margin-top: 20px;
      .el-input {
        width: 40%;
      }
      span {
        width: 20%;
        display: inline-block;
        text-align: center;
        color: #666666;
      }
    }
  }

  .pointer {
    cursor: pointer;
    color: #409EFF;
  }
</style>

<style lang="scss">
  .screen2-container {
    .el-form-item__label {
      line-height: 32px;
    }
    .el-form-item__content {
      line-height: 32px;
    }
  }

  .el-image-viewer__wrapper .el-icon-circle-close {
    color: #ffffff !important;
    font-size: 60px;
  }
</style>
