<template>
  <div>
    <div>
      <!-- <el-switch></el-switch> -->
      <div v-loading="loading">
        <div class="tab-top">
          <div class="fl">
            <el-input :placeholder="placeholderText" v-model="search" class="mr10" clearable @keyup.enter.native="getSearchList" @clear="getSearchList">
              <el-select v-model="searchType" slot="prepend" placeholder="礼品名称" style="width:140px;" @change="handleChangeType">
                <el-option label="礼品名称" :value="1"></el-option>
                <el-option label="礼品编码" :value="2"></el-option>
                <el-option label="条形码" :value="3"></el-option>
                <el-option label="福利id" :value="4"></el-option>
              </el-select>
            </el-input>
            <el-select v-model="query.hiddenFlag" placeholder="礼品状态" class="w-160 mr10" clearable @change="getSearchList">
              <el-option label="显示" :value="0"></el-option>
              <el-option label="隐藏" :value="1"></el-option>
            </el-select>
          </div>
          <div class="fr">
            <el-select v-model="batchOperate" placeholder="批量操作" class="w-160 mr10 more-select" :disabled="selectList.length < 1" @change="handleBatch">
              <el-option label="批量隐藏" :value="0"></el-option>
              <el-option label="批量取消隐藏" :value="1"></el-option>
              <el-option label="批量禁用" :value="2"></el-option>
              <el-option label="批量启用" :value="3"></el-option>
            </el-select>
            <el-button type="primary" @click="add">新建礼品</el-button>
          </div>
        </div>
        <div style="height:32px;margin: 20px 20px 0px 20px;">
          <div class="spanclass">更新时间：</div>
          <el-date-picker class="mr20" v-model="timeValue" @change="changeTime" type="datetimerange" align="right" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"></el-date-picker>
          <div class="spanclass">成本</div>
          <dm-input-amount precision="2" :min="0" :max="9999999.99" class="mr10 ml10 w100" v-model.trim="query.startCostPrice" @keyup.enter.native="getSearchList"></dm-input-amount>
          <div class="spanclass">-</div>
          <dm-input-amount precision="2" :min="0" :max="9999999.99" class="mr20 ml10 w100" v-model.trim="query.endCostPrice" @keyup.enter.native="getSearchList"></dm-input-amount>
          <div class="spanclass">可占库存</div>
          <dm-input-number precision="0" :min="0" :max="9999999" class="mr10 ml10 w100" v-model="query.startStock" placeholder="请输入" @keyup.enter.native="getSearchList"></dm-input-number>
          <div class="spanclass">-</div>
          <dm-input-number precision="0" :min="0" :max="9999999" class="ml10 w100" v-model="query.endStock" placeholder="请输入" @keyup.enter.native="getSearchList"></dm-input-number>
        </div>
        <div class="table-content">
          <el-table :data="tableData" ref="multipleTable" style="width: 100%" @sort-change="sortChange" @selection-change="handleSelectAll">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="礼品信息" width="300px">
              <template slot-scope="scope">
                <div class="img-text">
                  <dm-preview-img :img="scope.row.giftImgUrl" style="display:inline-block;border: 1px solid #dcdfe6;padding:4px;border-radius:2px;" width="50" height="50"></dm-preview-img>
                  <div class="text">
                    <p class="goods-descript">
                      <span>{{ scope.row.giftName }}</span>
                      <i class="el-icon-edit-outline" @click="handleName(scope.row)"></i>
                    </p>
                    <p class="goods-code">
                      <el-tooltip open-delay="200" effect="dark" placement="top">
                        <div slot="content">
                          <p class="goods-code">福利id：{{ scope.row.giftId }}</p>
                          <div>更新时间：<p class="inline-block" v-html="listTime(scope.row.updateTime)"></p></div>
                        </div>
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                      礼品编码：{{ scope.row.giftNo }}
                    </p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="updateTime" label="更新时间" sortable="custom" min-width="150px"> -->
              <!-- <template slot-scope="scope">{{ formatDateTimeByType(scope.row.updateName) }}</template> -->
              <!-- <template slot-scope="scope"><span v-html="listTime(scope.row.updateTime)"></span></template> -->
            <!-- </el-table-column> -->
            <el-table-column prop="costPrice" label="成本" sortable="custom" min-width="150px">
              <template slot-scope="scope">
                <p class="stock-box">
                  <span v-if="scope.row.minCostPrice == scope.row.maxCostPrice">{{ scope.row.minCostPrice }}</span>
                  <span v-else>{{ scope.row.minCostPrice }}-{{ scope.row.maxCostPrice }}</span>
                  <i class="el-icon-edit-outline" @click="updateCost(scope.row)"></i>
                </p>
              </template>
            </el-table-column>
            <el-table-column sortable="custom" label="库存" min-width="120px">
              <template slot="header">
                <el-tooltip open-delay="200" effect="dark" style="width:250px" placement="top">
                  <span class="undeline-dash">库存</span>
                  <span slot="content" style="width:240px">
                    可占库存：福利可以被直接使用和被应用占用的数量；<br>
                    已占用：福利已经被应用通过”固定库存“方式占用的数量；<br>
                    总库存：福利实际未产生履约单，还可以被出库的数量；<br>
                    总出库量：福利从创建到现在已生成履约单的数量；
                  </span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <div>
                  <p class="stock-box">
                    <span>可占库存：{{ scope.row.remainedStock }}</span>
                    <!-- <confirm-stock @confirmStock="confirmStock($event, scope.row)" :stock="scope.row.remainedStock"> -->
                      <i class="el-icon-edit-outline" @click="updateStock(scope.row)"></i>
                    <!-- </confirm-stock> -->
                  </p>
                  <p>已占用：{{ scope.row.occupyStock }}</p>
                  <p>总库存：{{ scope.row.totalStock }}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="allExchangeNumber" label="总出库量" sortable="custom" min-width="100px">
              <template slot="header">
                <el-tooltip open-delay="200" effect="dark" style="width:250px" placement="top">
                  <span class="undeline-dash">总出库量</span>
                  <span slot="content" style="width:240px">
                    可占库存：福利可以被直接使用和被应用占用的数量；<br>
                    已占用：福利已经被应用通过”固定库存“方式占用的数量；<br>
                    总库存：福利实际未产生履约单，还可以被出库的数量；<br>
                    总出库量：福利从创建到现在已生成履约单的数量；
                  </span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <span>{{ scope.row.historyTotalStock }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="hiddenFlag" label="是否隐藏" min-width="100px">
              <template slot="header">
                <el-tooltip open-delay="200" effect="dark" style="width:250px" placement="top">
                  <span class="undeline-dash">是否隐藏</span>
                  <span slot="content" style="width:240px">
                    隐藏后福利组件中不展示，其他应用不可增加占用数量，已占用的库存不影响使用
                  </span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-switch v-model="scope.row.hiddenFlag" :active-value="1" :inactive-value="0"  @change="changeShow(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="210px" fixed="right">
              <template slot-scope="scope">
                <div style="font-size:0px">
                  <dm-perm-button type="text" @click="edit(scope.row, 2)">编辑</dm-perm-button>
                  <dm-perm-button type="text" @click="$router.push({ path: '/gift-manage/stock-record' })">库存记录</dm-perm-button>
                  <el-dropdown style="margin-left:20px;" @command="command => handleCommand(command, scope.row)" placement="bottom-start">
                    <span class="el-dropdown-link" style="color:#2f54ed;cursor: pointer;"> 更多<i class="el-icon-arrow-down el-icon--right"></i> </span>
                    <el-dropdown-menu slot="dropdown" style="width:110px;">
                      <el-dropdown-item command="1">查看记录</el-dropdown-item>
                      <el-dropdown-item command="2" v-if="scope.row.statusFlag === 0" @click="changeStatus(scope.row)">禁用</el-dropdown-item>
                      <el-dropdown-item command="3" v-if="scope.row.statusFlag === 1" @click="changeStatus(scope.row)">启用</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-conteiner" style="background:#fff;" v-show="total > 0">
            <div class="pagination">
              <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="query.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next" :total="total" v-if="total != 0"> </dm-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="forbiddenTitle" :visible.sync="forbiddenDialog" width="30%">
      <div style="display:flex">
        <i class="el-icon-warning inline-block" style="font-size:24px;color:#e6a23c"></i>
        <span class="inline-block ml10" style="font-size:16px;line-height:20px">禁用礼品将在福利组件不展示，并且该礼品参加的活动将全部失效，确认禁用?</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="forbiddenDialog = false">取 消</el-button>
        <el-button type="primary" @click="forbiddenDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 调整成本 -->
    <!-- <update-cost v-if="updateCostDialog" :update-cost-data="updateCostData" @closeUpdateCost="closeUpdateCost" @getTableList="getTableList"></update-cost> -->
    <update-multi-cost v-if="updateCostDialog" :update-cost-data="updateCostData" @closeUpdateCost="closeUpdateCost" @getTableList="getTableList"></update-multi-cost>
    <!-- 修改名称 -->
    <update-name :update-name-form="updateNameForm" v-if="updateNameDialog" @closeUpdateName="closeUpdateName" @getTableList="getTableList"></update-name>
    <!-- 调整库存 -->
    <!-- <update-stock :stock-data="stockData" v-if="StockDialog" @getTableList="getTableList" @closeUpdateStock="closeUpdateStock"></update-stock> -->
    <update-virtual-stock :stock-data="stockData" v-if="StockDialog" @getTableList="getTableList" @closeUpdateStock="closeUpdateStock"></update-virtual-stock>
    <!-- <goods-stock :stock-data="stockData" v-if="StockDialog" @getList="getList" @closeStock="closeStock"></goods-stock> -->
    <check-upload-detail v-if="dialogVisible"></check-upload-detail>
  </div>
</template>
<script>
import { page, formate } from '@/mixins/table.js';
// import UpdateCost from './module/update-cost.vue';
import UpdateMultiCost from './module/update-multi-cost.vue';
// import request from '../../service/request';
// import common from '../../utils/common';
import updateName from './module/update-name.vue';
// import updateStock from './module/update-stock.vue';
import updateVirtualStock from './module/update-virtual-stock.vue';
import checkUploadDetail from './module/check-upload-detail';
// import updateSkuIntegral from '../../components/updateSkuIntegral';
// import { mapGetters } from 'vuex';
import { formatDateTimeByType, listTime } from '@/utils/index.js';
// import { getTimesByReq } from '@/utils/common.js';
import api from '@/api/gift.js';
const { giftPage, batchUpdate } = api;
export default {
  components: {
    // UpdateCost,
    UpdateMultiCost,
    updateName,
    // updateStock,
    updateVirtualStock,
    // goodsStock,
    // updateSkuIntegral,
    checkUploadDetail,
  },
  data() {
    return {
      bread: [
        {
          breadName: '礼品管理'
        },
        {
          breadName: '虚拟礼品'
        }
      ],
      // activeName: '0',
      mixins: [ page, formate ],
      query: {
        giftName: '',
        giftNo: '',
        giftId: '',
        giftBarNo: '',
        hiddenFlag: '',
        startTime: '',
        endTime: '',
        startCostPrice: '',
        endCostPrice: '',
        startStock: undefined,
        endStock: undefined,
        sortColumn: '',
        sortOrder: '',
        pageNum: 1,
        pageSize: 20,
      },
      batchOperate: '',
      total: 0,
      sortOrder: '',
      sortColumn: '',
      // tableData: [],
      tableData: [
        {
          costPrice: '99',
          giftId: '111111',
          giftName: '测试1',
          giftNo: '00000',
          hiddenFlag: 1,
          historyTotalStock: '9999',
          occupyStock: '100',
          totalStock: '800',
          remainedStock: '700',
          updateTime: 1610693597000,
          statusFlag: 1,
        },
        {
          costPrice: '99',
          giftId: '111111',
          giftName: '测试2',
          giftNo: '00000',
          hiddenFlag: 1,
          historyTotalStock: '9999',
          occupyStock: '100',
          totalStock: '800',
          remainedStock: '700',
          updateTime: 1610693597000,
          statusFlag: 0,
        }
      ],
      selectList: [],
      // 更新成本数据
      updateCostData: {
        costPrice: '',
        id: '',
        textarea: ''
      },
      updateCostDialog: false,
      // 更新名称
      updateNameForm: {
        name: '',
        id: '',
        type: ''
      },
      updateNameDialog: false,
      // 更新库存
      stockData: {
        id: '',
        remainedStock: '',
        textarea: '',
      },
      StockDialog: false,
      integralDialog: false,
      loading: false,
      search: '',
      searchType: 1,
      placeholderText: '请输入礼品名称',
      isShow: false,
      timeValue: '',
      dialogVisible: false,
      forbiddenDialog: false,
      forbiddenTitle: '禁用'
    };
  },
  created() {
    this.$emit('updateBread', this.bread);
    this.$emit('showAside', true);
    this.init();
  },
  methods: {
    formatDateTimeByType,
    listTime,
    init() {
      this.getTableList();
    },
    getSearchList() {
      if (this.searchType === 1) {
        this.query.giftName = this.search;
      } else if (this.searchType === 2) {
        this.query.giftNo = this.search;
      } else if (this.searchType === 3) {
        this.query.giftBarNo = this.search;
      } else if (this.searchType === 4) {
        this.query.giftId = this.search;
      }
      this.pageNum = 1;
      this.getTableList();
    },
    // 列表筛选条件更改
    handleChangeType() {
      if (this.searchType === 1) {
        this.placeholderText = '请输入礼品名称';
      } else if (this.searchType === 2) {
        this.placeholderText = '请输入礼品编码';
      } else if (this.searchType === 3) {
        this.placeholderText = '条形码';
      } else if (this.searchType === 4) {
        this.placeholderText = '福利id';
      }
    },
    // 实物礼品列表
    getTableList() {
      let params = {
        ...this.query,
        giftType: 2
      };
      giftPage(params).then(res =>{
        console.log(res);
        this.tableData = res.result.result;
        console.log(this.tableData);
      });
    },
    handleCommand(value1, value2){
      console.log(value1);
      console.log(value2);
      if(value1 == 1){
        this.dialogVisible = true;
      }else if(value1 == 2){
        this.forbiddenDialog = true;
      }
    },
    // 排序
    sortChange(value) {
      if (value.order == 'ascending') {
        this.query.sortOrder = 'asc';
      } else if (value.order == 'descending') {
        this.query.sortOrder = 'desc';
      }
      if (value.prop === 'updateTime') {
        this.query.sortColumn = 'update_time';
      } else if (value.prop === 'costPrice') {
        this.query.sortColumn = 'cost_price';
      } else if (value.prop === 'stock') {
        this.query.sortColumn = 'stock';
      }
      this.getTableList();
    },
    changeTime(){
      if(this.timeValue){
        this.query.startTime = this.formatDateTimeByType(this.timeValue[0], 'yyyy-MM-dd-HH-mm-ss');
        this.query.endTime = this.formatDateTimeByType(this.timeValue[1], 'yyyy-MM-dd-HH-mm-ss');
      }else{
        this.query.startTime = '';
        this.query.endTime = '';
      };
      this.query.pageNum = 1;
      this.query.pageSize = 20;
      this.getTableList();
    },
    handleSelectAll(val) {
      this.selectList = val;
      // console.log(this.selectList);
    },
    // 批量操作
    handleBatch(value) {
      console.log(value);
      let goodsIdArr = [];
      for (let item of this.selectList) {
        goodsIdArr.push(item.giftId);
      }
      let params = {
        giftIdList: goodsIdArr,
        type: value
      };
      if(value == 2){
        this.$confirm('<div>已添加被禁用礼品的活动将会失效，确认禁用?</div>', '批量禁用', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
        })
          .then(() => {
            this.batchRequest(params);
            console.log('批量禁用');
          });
      }else if(value == 0){
        this.$confirm('<div>是否隐藏?</div>', '批量隐藏', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
        })
          .then(() => {
            this.batchRequest(params);
            console.log('批量隐藏');
          });
      }else if(value == 1){
        this.$confirm('<div>是否取消隐藏?</div>', '批量取消隐藏', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
        })
          .then(() => {
            this.batchRequest(params);
            console.log('批量取消隐藏');
          });
      }else if(value == 3){
        this.$confirm('<div>是否启用?</div>', '批量启用', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
        })
          .then(() => {
            this.batchRequest(params);
            console.log('批量启用');
          });
      }
    },
    batchRequest(params) {
    // batchRequest() {
      batchUpdate(params).then(res => {
        if(res.code === '0000'){
          this.$message.success('操作成功');
          this.getTableList();
        }else{
          this.$message.error(res.message);
        }
      });
      console.log('批量操作');
    },
    // 显示与隐藏
    changeShow(item){
      console.log(item.statusFlag, item.hiddenFlag);
      if(item.statusFlag == 0 && item.hiddenFlag == 0){
        this.$confirm('<div>该礼品已禁用，不可关闭隐藏状态?</div>', '提示', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
          showCancelButton: false
        });
        item.hiddenFlag = 1;
      }
      let value;
      if(item.hiddenFlag == 0){
        value = 1;
      }else{
        value = 0;
      }
      let params = {
        giftIdList: [ item.giftId ],
        type: value
      };
      this.batchRequest(params);
    },
    // 启用与禁用
    changeStatus(item){
      let value;
      if(item.statusFlag == 0){
        value = 2;
      }else{
        value = 3;
      }
      let params = {
        giftIdList: [ item.giftId ],
        type: value
      };
      this.batchRequest(params);
    },
    // 更新名字
    handleName(item) {
      console.log('更改商品名称', item);
      this.updateNameForm.name = item.giftName;
      this.updateNameForm.id = item.giftId;
      // this.updateNameForm.type = 1; // 1、礼品 2、优惠券 3、渠道礼品
      this.updateNameDialog = true;
    },
    // 关闭弹框
    closeUpdateName() {
      // this.updateNameForm.name = '';
      // this.updateNameForm.id = '';
      this.updateNameDialog = false;
      this.getTableList();
    },
    // 更新库存
    updateStock(item) {
      this.stockData.id = item.giftId;
      this.stockData.remainedStock = item.remainedStock;
      this.stockData.textarea = item.textarea;
      console.log(this.stockData.remainedStock);
      this.StockDialog = true;
    },
    closeUpdateStock() {
    // this.stockData.id = '';
      this.stockData.remainedStock = '';
      this.stockData.textarea = '';
      this.StockDialog = false;
    },
    // 虚拟礼品库存调整
    // confirmStock(obj, item) {
    //   console.log('调整库存', obj, item);
    // let stock;
    // if (obj.type === 1) {
    //   stock = obj.stock;
    // } else if (obj.type === 2) {
    //   stock = '-' + obj.stock;
    // }
    // let params = {
    //   goodsId: item.goodsId,
    //   goodsStock: stock
    // };

    // request
    //   .post('/api-integral-mall/update-integral-gift-info', params)
    //   .then(res => {
    //     if (res.data.code === '0000') {
    //       this.$message.success('修改成功');
    //       this.getTableList();
    //     } else {
    //       this.$message.error(res.data.message);
    //     }
    //   })
    //   .catch(error => {
    //     this.$message.error({
    //       duration: 1000,
    //       message: error.message
    //     });
    //   });
    // },
    // 更新成本
    updateCost(item) {
      console.log('修改成本', item);
      this.updateCostData.id = item.giftId;
      // this.updateCostData.costPrice = item.costPrice;
      // this.updateCostData.textarea = item.textarea;
      this.updateCostDialog = true;
    },
    closeUpdateCost() {
      console.log('关闭修改成本弹窗');
      this.integralDate.id = '';
      this.integralDate.costPrice = '';
      this.updateCostDialog = false;
    },
    add() {
      console.log('新建礼品,跳转');
      this.$router.push({ path: '/gift-manage/virtual-gift-detail', query: { giftId: '' } });
    },
    edit(item) {
    //   console.log('编辑实物礼品', item);
    // let giftObj = {
    //   pageNum: this.pageNum,
    //   pageSize: this.pageSize,
    //   search: this.search,
    //   proType: this.proType,
    //   status: this.status,
    //   sortColumn: this.sortColumn,
    //   sortOrder: this.sortOrder,
    //  // activeName: this.activeName
    // };
    // window.localStorage.setItem('giftObj', JSON.stringify(giftObj)); // 搜索条件放入缓存
      this.$router.push({ path: '/gift-manage/virtual-gift-detail', query: { giftId: item.giftId } });
    }
  },
  // computed: {
  //   // ...mapGetters([ 'getDefaultId' ])
  // },
  // watch: {
  // getDefaultId() {
  //   this.shopId = this.getDefaultId;
  //   if (this.shopId) {
  //     this.init();
  //   }
  // }
  // }
};
</script>
<style lang="scss" scoped>
.tab-top {
  height: 32px;
  margin: 20px 20px 0px 20px;
  display: flex;
  justify-content: space-between;
  .fl{
    display: flex;
    justify-content: space-between;
  }
}
.table-content {
  margin: 20px;
  padding-bottom: 20px;
  .img-text {
    height: 60px;
    img {
      width: 60px;
      height: 60px;
      border: 1px solid #dcdfe6;
      padding: 4px;
      border-radius: 2px;
    }
    .text {
      display: inline-block;
      vertical-align: top;
      width: 75%;
      margin-left: 3px;
      font-size: 13px;
      line-height: 14px;
      .goods-descript {
        color: #606266;
        line-height: 18px;
        font-size: 14px;
        margin-bottom: 25px;
      }
      .goods-code {
        color: #909399;
        font-size: 12px;
        line-height: 16px;
      }
    }
    & :hover .el-icon-edit-outline {
      display: inline-block;
      cursor: pointer;
    }
    .el-icon-edit-outline:hover {
      color: #2f54ed;
    }
  }
  .stock-box {
    &:hover .el-icon-edit-outline {
      display: inline-block;
      cursor: pointer;
    }
  }
}
.el-icon-edit-outline:hover {
  color: #2f54ed;
}
.undeline-dash{
  border-bottom: 1px dashed #2F54EB;
  font-weight:500;
}
.spanclass{
  display: inline-block;
  line-height: 32px;
}
</style>
<style>
/* .damolish .el-tooltip__popper{
  width: 240px;
} */
</style>