<template>
  <div class="goods-manage-box" v-loading="loading > 0">
    <Header :title="title"></Header>
    <div class="container">
      <div class="content">
        <!-- 表格 -->
        <div class="filter-box">
          <!-- <div class="btn" @click="toGood('add')">+ 新建商品</div> -->
          <div class="btn-box">
            <div class="label">商品商家：</div>
            <!-- <el-select
              v-model="filter.sid"
              size="small"
              class="select"
              style="width: 153px"
              placeholder="请选择"
            >
              <el-option :value="null" label="全部"> </el-option>
              <el-option
                :value="item.id"
                :label="item.name"
                v-for="item in businessList"
                :key="item.id"
              >
              </el-option>
            </el-select> -->
            <el-input
              class="input"
              v-model="filter.shopName"
              style="width: 153px;"
              placeholder="此框输入商品商家"
              size="small"
            ></el-input>
            <div class="label">商品分类：</div>
            <el-cascader
              v-model="category"
              :options="categoryList"
              placeholder="请选择"
              size="small"
              :props="{
                children: 'second',
                value: 'id',
                label: 'name',
                checkStrictly: true,
              }"
              class="good-input"
              style="width: 153px"
            ></el-cascader>
            <div class="label">商品状态：</div>
            <el-select
              v-model="filter.auditStatus"
              size="small"
              class="select"
              style="width: 153px"
              placeholder="请选择"
            >
              <el-option :value="null" label="全部"> </el-option>
              <el-option :value="0" label="审核通过"> </el-option>
              <el-option :value="1" label="待审核"> </el-option>
              <el-option :value="2" label="驳回"> </el-option>
            </el-select>
            <el-input
              class="input"
              v-model="filter.name"
              style="width: 188px; margin-left: 40px"
              placeholder="此框输入商品名搜索"
              size="small"
            ></el-input>
            <button class="search" @click="search">搜索</button>
            <div class="import-box" style="margin-left: 60px;">
              <!-- <div class="btn" @click="batchRejectShopGoodModal">驳回</div> -->
              <div
                class="btn"
                @click="batchPassShopGood"
                style="margin-left: 20px;"
              >
                通过
              </div>
            </div>
          </div>
        </div>
        <el-table
          :data="goodsList"
          class="table table no-border-table"
          ref="orderTable"
          :header-cell-style="{
            border: 'none',
            color: '#333',
            background: '#f6f6f6',
            borderBottom: '1px solid #E8E8E8',
            height: '54px',
          }"
          :row-style="{
            height: '54px',
          }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :selectable="selectable">
          </el-table-column>
          <el-table-column prop="master_pic" align="center" label="商品主图">
            <div slot-scope="scope">
              <img class="master-pic" :src="scope.row.masterPic" alt="" />
            </div>
          </el-table-column>
          <el-table-column
            prop="gid"
            align="center"
            label="商品ID"
          ></el-table-column>
          <el-table-column
            prop="name"
            align="center"
            label="商品名称"
          ></el-table-column>
          <el-table-column
            prop="minPrice"
            align="center"
            label="价格/元"
          ></el-table-column>
          <el-table-column
            prop="minGoldAmount"
            align="center"
            label="绿通支付金额/元"
          ></el-table-column>
          <el-table-column prop="groupingName" align="center" label="商品分类">
            <div slot-scope="scope">
              {{ scope.row.firstSortName + "/" + scope.row.secondSortName }}
            </div>
          </el-table-column>
          <el-table-column
            prop="shopName"
            align="center"
            label="所属商家"
          ></el-table-column>
          <el-table-column prop="status" align="center" label="审核状态">
            <div slot-scope="scope">
              {{ auditStatusMap[scope.row.auditStatus] }}
            </div>
          </el-table-column>
          <el-table-column
            prop="totalStock"
            align="center"
            label="库存"
          ></el-table-column>
          <!-- <el-table-column prop="twig" align="center" label="排序">
            <template slot-scope="scope">
              <u class="blue" @click="editSort(scope.row)">{{
                scope.row.twig
              }}</u>
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            prop="twig"
            align="center"
            width="200"
            label="会员设置"
          >
            <div slot-scope="scope" style="display: flex">
              <div class="vip-btn" @click="showSetting(scope.row.gid)">
                商品可见用户
              </div>
              <div class="vip-btn" @click="priceSetting(scope.row.gid)">
                会员价格设置
              </div>
            </div>
          </el-table-column> -->
          <el-table-column label="操作" align="center" width="320">
            <div slot-scope="scope">
              <div
                class="table-btn-box"
                style="display: flex;justify-content: center;"
              >
                <button
                  size="mini"
                  class="table-btn"
                  v-if="scope.row.auditStatus !== 1 && scope.row.status === 3"
                  @click="updateStatus(1, scope.row.id)"
                >
                  下架
                </button>
                <button
                  size="mini"
                  class="table-btn"
                  v-if="scope.row.auditStatus !== 1 && scope.row.status === 1"
                  @click="updateStatus(3, scope.row.id)"
                >
                  开售
                </button>
                <button
                  size="mini"
                  class="table-btn"
                  v-if="scope.row.auditStatus === 1"
                  @click="rejectShopGoodModal(scope.row.id)"
                >
                  驳回
                </button>
                <button
                  size="mini"
                  class="table-btn"
                  v-if="scope.row.auditStatus === 1"
                  @click="passShopGood([scope.row.id])"
                >
                  通过
                </button>
                <button
                  size="mini"
                  class="table-btn"
                  @click="toGood(scope.row.gid)"
                >
                  查看详情
                </button>
                <button
                  size="mini"
                  class="table-btn"
                  @click="deleteGood(scope.row.gid)"
                >
                  删除商品
                </button>
              </div>
            </div>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页按钮 -->
      <div class="footer" :key="paginationKey">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          background
          layout="total, prev, pager, next, jumper"
          :page-size="size"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <!-- 修改排序弹窗 -->
    <el-dialog title="更改排序" width="400px" :visible.sync="sortShow">
      <el-form label-width="60px" size="mini" ref="editSort" inline-message>
        <el-form-item label="排序：" prop="tableData" style="margin-top: 15px">
          <el-input v-model="currentSort" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn cancel-btn" @click="sortShow = false"
          >取 消</el-button
        >
        <el-button class="btn confirm-btn" @click="saveSort">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="驳回申请" width="480px" :visible.sync="rejectVisible">
      <!-- <div class="reject-title"><span>*</span>驳回申请</div> -->
      <div style="padding: 0 16px;">
        <div class="remark-box">
          驳回申请
          <textarea
            rows="8"
            class="remark"
            v-model="remark"
            placeholder="驳回理由"
          ></textarea>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click.native="reject()" class="cancel-btn">驳 回</el-button> -->
        <el-button @click.native="rejectVisible = false" class="cancel-btn btn"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click.native="rejectShopGood"
          class="confirm-btn btn"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :show-close="false"
      :close-on-click-modal="false"
      title="生成中..."
      :visible.sync="showProgressDialog"
      width="30%"
      center
    >
      <el-progress
        :percentage="progress"
        :text-inside="true"
        :stroke-width="18"
      ></el-progress>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import dayjs from 'dayjs';
import Header from '../../components/common/header';
import myUtils from '../../components/common/whatever2excel';
export default {
  components: {
    Header
  },
  name: 'goods-manage',
  data() {
    return {
      currentPage: 1, // 当前页码
      size: 20, // 每页条数
      total: 0, // 总页数
      loading: 0, // 加载中
      title: {
        // 页面标题
        firstTitile: '商品管理',
        secondTitle: '商家商品管理'
      },
      filter: {
        name: '',
        // firstSortId: null,
        // secondSortId: null,
        shopName: '',
        auditStatus: null,
      },
      goodsList: [], // 列表
      categoryList: [],
      currentId: null,
      currentSort: null,
      sortShow: false,
      paginationKey: +new Date(),
      category: [],
      businessList: [],
      showProgressDialog: false,
      progress: 0,
      statusMap: {
        1: '仓库中',
        3: '在售'
      },
      genreMap: {
        1: '自营商品',
        2: '供应链'
      },
      businessObj: {},
      auditStatusMap: {
        0: '审核通过',
        1: '待审核',
        2: '驳回'
      },
      rejectVisible: false,
      remark: '',
      id: null,
      ids: [],
      multipleSelection: []
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name !== 'good2') {
      sessionStorage.setItem('goodManage2', '');
    }
    next();
  },
  mounted() {
    let data = sessionStorage.getItem('goodManage2')
      ? JSON.parse(sessionStorage.getItem('goodManage2'))
      : '';
    if (data) {
      this.filter = {
        ...this.filter,
        ...data.filter
      };
      this.currentPage = data.currentPage;
      this.paginationKey = +new Date();
      this.setSearchData();
    }
    // 获取列表
    this.getCategoryList();
    this.getBusinessList();
    this.getGoodsList();
  },
  filters: {
    // 时间格式化
    dateFormat(date) {
      if (!date) return '请选择时间';
      let day = dayjs(date);
      return day.format('YYYY-MM-DD HH:mm:ss');
    }
  },
  computed: {},
  methods: {
    setSearchData() {
      let goodManage = {
        currentPage: this.currentPage,
        filter: this.filter
      };
      sessionStorage.setItem('goodManage2', JSON.stringify(goodManage));
    },
    // 切换页码
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getGoodsList();
    },
    // 获取商品列表
    getGoodsList() {
      this.setSearchData();
      this.loading++;
      this.httpGet(this.$root.getShopGoodsList, {
        page: this.currentPage,
        size: this.size,
        ...this.filter,
        firstSortId: this.category[0] || 0,
        secondSortId: this.category[1] || 0
      }).then(
        (res) => {
          this.loading--;
          this.goodsList = res.list;
          this.total = res.total;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    getBusinessList() {
      this.loading++;
      this.httpGet(this.$root.getBusinessList, {
        size: 9999
      }).then(
        (res) => {
          this.loading--;
          this.businessList = res.list;
          let businessObj = {};
          res.list.forEach(item => {
            businessObj[item.id] = item.name;
          });
          this.businessObj = businessObj;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 获取分类列表
    getCategoryList() {
      this.loading++;
      this.httpGet(this.$root.getGoodsCategoryList, {}).then(
        (res) => {
          this.loading--;
          this.categoryList = res.list.filter((item) => item.second.length);
          this.categoryList.unshift({
            name: '全部',
            id: 0
            // second: [
            //   {
            //     name: '全部',
            //     id: 0,
            //     fid: 0
            //   }
            // ]
          });
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 过滤
    search() {
      console.log(this.filter);
      this.currentPage = 1;
      this.getGoodsList();
    },
    editSort(rowData) {
      // 更改排序
      this.currentId = rowData.id;
      this.sortShow = true;
      this.currentSort = rowData.twig;
    },
    saveSort() {
      // 保存排序
      this.loading++;
      this.httpPut(this.$root.updateGoodsTwig, {
        id: +this.currentId,
        twig: +this.currentSort
      }).then(
        (res) => {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          this.getGoodsList();
          this.loading--;
          this.sortShow = false;
        },
        (err) => {
          this.loading--;
          this.$message.error(err);
        }
      );
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectable(row, index){
      if(row.auditStatus === 1) {
        return true
      } else {
        return false
      };
    },
    updateStatus(status, id) {
      this.$confirm(
        `<p class='title'><i class='icon el-icon-question'></i>提醒</p><p class='text'>确定要将商品${
          status === 1 ? '放入仓库' : '开售'
        }吗</p>`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'cancel-btn',
          confirmButtonClass: 'confirm-btn',
          customClass: 'confirm-box',
          dangerouslyUseHTMLString: true,
          showClose: false,
          type: 'none'
        }
      ).then(() => {
        this.loading++;
        this.httpPut(this.$root.updateGoodsStatus, {
          id,
          status
        }).then(
          (res) => {
            this.loading--;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getGoodsList();
          },
          (res) => {
            this.loading--;
            this.$message.error(res);
          }
        );
      });
    },
    batchPassShopGood(){
      // console.log(this.multipleSelection);
      if(!this.multipleSelection.length){
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
        return;
      }
      this.passShopGood(this.multipleSelection.map(item => item.id))
    },
    passShopGood(ids) {
      this.$confirm(
        `<p class='title'><i class='icon el-icon-question'></i>提醒</p><p class='text'>确认是否通过审核？</p>`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'cancel-btn',
          confirmButtonClass: 'confirm-btn',
          customClass: 'confirm-box',
          dangerouslyUseHTMLString: true,
          showClose: false,
          type: 'none'
        }
      ).then(() => {
        this.loading++;
        this.httpPut(this.$root.passShopGood, {
          list: ids
        }).then(
          (res) => {
            this.loading--;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getGoodsList();
          },
          (res) => {
            this.loading--;
            this.$message.error(res);
          }
        );
      });
    },
    rejectShopGoodModal(id){
      this.remark = '';
      this.rejectVisible = true;
      this.id = id;
    },
    batchRejectShopGoodModal(){
      if(!this.multipleSelection.length){
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
        return;
      }
      this.rejectShopGoodModal(this.multipleSelection.map(item => item.id))
    },
    rejectShopGood(){
      this.loading++;
        this.httpPost(this.$root.rejectShopGood, {
          id: this.id,
          auditRejectReason: this.remark
        }).then(
          (res) => {
            this.loading--;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.rejectVisible = false;
            this.getGoodsList();
          },
          (res) => {
            this.loading--;
            this.$message.error(res);
          }
        );
    },
    // 删除商品
    deleteGood(gid) {
      this.$confirm(
        `<p class='title'><i class='icon el-icon-question'></i>提醒</p><p class='text'>确定要删除商品吗</p>`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'cancel-btn',
          confirmButtonClass: 'confirm-btn',
          customClass: 'confirm-box',
          dangerouslyUseHTMLString: true,
          showClose: false,
          type: 'none'
        }
      ).then(() => {
        this.loading++;
        this.httpDelete(this.$root.deleteGoods, {
          gid
        }).then(
          (res) => {
            this.loading--;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getGoodsList();
          },
          (res) => {
            this.loading--;
            this.$message.error(res);
          }
        );
      });
    },
    // 添加/编辑商品
    toGood(gid) {
      this.$router.push({
        name: 'good2',
        query: {
          gid
        }
      });
    },
    priceSetting(gid) {
      this.$router.push({
        name: 'priceSetting',
        query: {
          gid
        }
      });
    },
    showSetting(gid) {
      this.$router.push({
        name: 'showSetting',
        query: {
          gid
        }
      });
    },
    async order2excel() {
      this.loading++;
      let goodsList = [];
      let totalPage = null;
      let data = {
        page: this.currentPage,
        size: this.size,
        ...this.filter,
        firstSortId: this.category[0] || 0,
        secondSortId: this.category[1] || 0
      };
      await this.httpGet(this.$root.getGoodsImportList, data).then(
        (res) => {
          this.loading--;
          totalPage = Math.ceil(parseInt(res.total) / this.size);
        },
        () => {
          this.loading--;
        }
      );
      this.showProgressDialog = true;
      this.progress = 0;
      await this.getAllPages(totalPage, goodsList).then(
        () => {
          this.showProgressDialog = false;
          this.jsonFormatAndToExcel(goodsList);
        },
        (err) => {
          console.error(err);
          this.showProgressDialog = false;
        }
      );
    },
    async getAllPages(totalPage, list) {
      for (let i = 1; i <= totalPage; i++) {
        let data = {
          page: i,
          size: this.size,
          ...this.filter,
          firstSortId: this.category[0] || 0,
          secondSortId: this.category[1] || 0
        };
        await this.httpGet(this.$root.getGoodsImportList, data).then((res) => {
          list.push(...res.list);
          this.progress = Math.floor((i / totalPage) * 100);
          console.log('page' + i, list.length);
        });
        // console.log(5555, list);
      }
    },
    getAttrs(attrs) {
      return attrs
        .map((item) => {
          return item.keyName + '：' + item.value;
        })
        .join('; ');
    },
    jsonFormatAndToExcel(list) {
      let formatList = [];
      list.forEach((item) => {
        let obj = {
          商品ID: item.gid,
          商品名称: item.name,
          商品分类: item.firstSortName + '-' + item.secondSortName,
          状态: this.statusMap[item.status],
          商品类型: this.genreMap[item.genre],
          '当前月销量（含基础销量）': item.monthlySales,
          商品商家: this.businessObj[item.sid],
          成本: item.cost,
          卖价: item.linePrice,
          总库存: item.skuList.reduce((pre, cur) => {
            return pre + cur.stock;
          }, 0)
        };
        item.skuList.forEach((sku, index) => {
          obj[`规格${index + 1}`] = this.getAttrs(sku.attrs);
          obj[`规格${index + 1} 价格`] = sku.price;
          obj[`规格${index + 1} 库存`] = sku.stock;
          obj[`规格${index + 1} 编码`] = sku.code;
        });
        formatList.push(obj);
      });
      // console.log(formatList);
      myUtils.json2excel(formatList);
    }
  }
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~assets/public.styl';
</style>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~assets/main.styl';

.goods-manage-box {
  height: 100%;
  width: 100%;
  flex-y(flex-start, flex-start);
  overflow-y: hidden;
  background: bg-color;

  .container {
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    overflow-y: auto;
    flex-y(flex-start, flex-start);
    padding: 24px;

    .blue {
      color: btn-color;
      cursor: pointer;
    }

    // content 表格
    .content {
      flex: 1;
      width: 100%;
      font-size: 14px;
      background: white;
      box-sizing: border-box;
      padding: 24px 32px;
      border-radius: 2px;

      .filter-box {
        flex-wrap: wrap;

        .btn-box {
          margin: 5px 0;
          flex-x(flex-start);
          flex-wrap: wrap;

          .label {
            margin-right: 6px;
            margin-left: 12px;
            word(14px, gray3);
          }

          .input {
            margin-right: 8px;
          }

          .search {
            min-width: 65px;
          }
        }
      }

      .import-box {
        flex-x(flex-end);
      }

      // 按钮
      .btn {
        width: 100px;
        height: 32px;
        line-height: 32px;
        confirm-btn();
        font-size: 14px;
        margin: 16px 0;
        flex-shrink: 0;
      }

      .table {
        .master-pic {
          width: auto;
          height: 36px;
        }
      }

      .vip-btn {
        width: 96px;
        height: 24px;
        border-radius: 4px;
        border: 1px solid #E8E8E8;
        background: #F7F7F7;
        word(12px, btn-color);
        flex-x(center);
        white-space: nowrap;
        margin: 0 5px;
        cursor: pointer;
      }

      .table-btn-box {
        flex-x(flex-end);

        .table-btn {
          // width: 80px;
          // min-width: 80px;
          padding: 0 12px;
          height: 24px;
          line-height: 24px;
          color: gray3;
          font-size: 12px;
          margin-right: 8px;
          cancel-btn();
        }
      }
    }
  }

  .footer {
    width: 100%;
    padding: 24px;
    box-sizing: border-box;
    flex-x(flex-end);
    background: white;
  }
  .remark-box {
    width: 100%;
    padding: 12px 0;
    padding-left: 15px;
    box-sizing: border-box;
    flex-x(flex-start, flex-start);
    white-space: nowrap;
    .remark {
      border: 1px solid #f1f1f1;
      width: 100%;
      // margin: 0 12px 0;
      margin-left: 12px;
      padding: 12px;
      box-sizing: border-box;
    }
  }
}
</style>
