<template>
  <div class="app-container">
    <div class="form-contaner">
      <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-width="100px">
        <el-form-item label="活动名称：" prop="activityName">
          <el-input v-model="mainForm.activityName" placeholder="请填写活动名称" style="width: 400px;"></el-input>
        </el-form-item>
        <el-form-item label="活动时间：" prop="activityDate">
          <el-date-picker
            v-model="mainForm.activityDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            style="width: 400px;"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动场次：" prop="stageList">
          <el-select v-model="mainForm.stageList" multiple placeholder="请选择" style="width: 400px;">
            <el-option
              v-for="item in stageArr"
              :key="item.name"
              :label="item.name + '点'"
              :value="item.name">
              <span style="float: left">{{ item.name }}点</span>
              <span style="float: left; color: #8492a6; font-size: 13px; margin-left: 20px">{{ item.startHour }}:00:00-{{ item.endHour }}:00:00</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input type="textarea" v-model="mainForm.remark" :autosize="{ minRows: 4, maxRows: 8}" placeholder="请填写备注" style="width: 400px;"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="mymain-container">
      <div class="btn-group">
        <el-button size="small" type="primary" @click="addGoods">选择商品</el-button>
      </div>

      <div class="table">
        <el-table :data="goodsList" border fit stripe>
          <el-table-column align="center" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
          <el-table-column align="center" label="划线价格" prop="goodsPrice" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="库存" prop="stockNum"></el-table-column>
          <el-table-column align="center" label="分佣金额" prop="amount" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" :disabled="scope.row.sharePercent != 0 && scope.row.sharePercent != null"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="分佣比例(%)" prop="sharePercent" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sharePercent"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="限购(0为不限购)" prop="limitBuy" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.limitBuy"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="秒杀价" prop="price" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="秒杀库存" prop="secStockNum" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.secStockNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="销量" prop="salesVolume" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salesVolume"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="排序" prop="sortNum" min-width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sortNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteGoods(scope.row.goodsId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="submitMainForm" :loading="formLoading">{{ formLoading ? '提交中 ...' : '提 交' }}</el-button>
        <el-button @click="goBack">关 闭</el-button>
      </div>
    </div>


    <!-- 选择商品 -->
    <el-dialog title="选择商品" :visible.sync="addGoodsVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <div class="dialog-container clearfix">
        <div class="left fl">
          <div class="item" @click="changeClassify('')">全部分类</div>
          <div class="group" v-for="(item, index) in classifyList" :key="index">
            <div class="item" @click="toggleOpen(index)">
              <i :class="item.isOpen ? 'el-icon-caret-bottom':'el-icon-caret-right'"></i> {{item.name}}
            </div>
            <div class="child" v-if="item.isOpen">
              <div class="item" v-for="(childItem, childIndex) in item.children" :key="childIndex" @click="changeClassify(childItem.categoryId)">{{childItem.name}}</div>
            </div>
          </div>
        </div>

        <div class="right fl">
          <div class="search">
            <el-input placeholder="请输入商品名称进行搜索" v-model="keyword" class="input-with-select" clearable size="small" style="width: 250px">
              <el-button slot="append" icon="el-icon-search" size="small" @click="getGoodsListByScreen"></el-button>
            </el-input>
          </div>
          <div class="table" style="margin: 10px 0 20px;">
            <el-table 
              v-loading="table_listLoading" 
              :data="table_dataList" 
              element-loading-text="Loading" 
              tooltip-effect="dark" 
              style="width: 100%" 
              max-height="270"
              @selection-change="handleChooseGoods">
              <el-table-column align="center" type="selection" :selectable='checkboxSelect' width="45"></el-table-column>
              <el-table-column align="center" prop="goodsName" label="商品名称" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="goodsPrice" label="价格" width="80"></el-table-column>
              <el-table-column align="center" prop="stockNum" label="库存" width="80"></el-table-column>
            </el-table>
          </div>
          <div class="pagination clearfix">
            <div class="fr">
              <el-pagination
                @current-change="handleTableCurrentChange"
                :current-page="table_currentPage"
                :page-size="table_pageSize"
                background
                layout="prev, pager, next"
                :total="table_listTotal">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddGoods">保 存</el-button>
        <el-button @click="cancelAddGoods">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editActivity, addActivity, getClassifyList, getGoodsList, getActivityDetail } from '@/api/seckill'
import { deleteEmptyObj, findElem } from '@/utils/util'

export default {
  data() {
    return {
      isEdit: false,
      editId: '',
      formLoading: false,
      mainForm: {
        activityName: '',
        activityDate: '',
        stageList: [],
        remark: '',
      },
      mainFormRules: {
        activityName: [
          { required: true, message: '请填写活动名称', trigger: 'blur' }
        ],
        activityDate: [
          { required: true, message: '请选择活动时间', trigger: 'change' }
        ],
        stageList: [
          { required: true, message: '请选择活动场次', trigger: 'change' }
        ],
      },
      goodsList: [], // 列表数据
      addGoodsVisible: false,

      classifyList: [],
      classifyCurrent: '',
      keyword: '',
      table_dataList: null, // 列表数据
      table_listLoading: true, // 列表加载loading
      table_currentPage: 1, // 当前页码
      table_pageSize: 10, // 每页数量
      table_listTotal: 0, // 列表总数
      table_chooseGoods: [], // table中 当前选择商品

      stageArr: [
        {name: 10, startHour: 10, endHour: 12},
        {name: 12, startHour: 12, endHour: 15},
        {name: 15, startHour: 15, endHour: 18},
        {name: 18, startHour: 18, endHour: 20},
        {name: 20, startHour: 20, endHour: 10},
      ]
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },
  created() {
    const { id } = this.$route.query;
    this.isEdit = id ? true : false;
    this.editId = id;

    if(this.isEdit) {
      this.getActivityDetail(id);
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },

    // 获取详情
    getActivityDetail(secKillId) {
      getActivityDetail({secKillId}).then(res => {
        let stageList = [];
        res.data.stages.forEach(item => {
          stageList.push(Number(item.name));
        })
        this.mainForm = {
          activityName: res.data.secKillName,
          activityDate: [res.data.startTime.slice(0, 10), this.reduceDate(res.data.endTime.slice(0, 10))],
          remark: res.data.remark,
          stageList: stageList
        }
        this.goodsList = res.data.goodsSpecs;
      })
    },

    // 获取分类列表
    getClassifyList() {
      getClassifyList({categoryLevel: 1, status: true}).then(res => {
        res.data.forEach(item => {
          item.isOpen = false;
        });
        this.classifyList = res.data;
        this.classifyCurrent = '';
        this.getGoodsList();
      })
    },

    // 展开/收起 分类
    toggleOpen(index) {
      this.classifyList[index].isOpen = !this.classifyList[index].isOpen;
    },

    // 切换分类
    changeClassify(cid) {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可切换分类');
      }
      this.classifyCurrent = cid;
      this.table_currentPage = 1;
      this.getGoodsList();
    },

    // 搜索
    getGoodsListByScreen() {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可搜索');
      }
      this.table_currentPage = 1;
      this.getGoodsList();
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.table_currentPage,
        pageSize: this.table_pageSize,
        keyword: this.keyword,
        categoryId: this.classifyCurrent,
      }).then(res => {
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data.records;
        for(let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i]
          for(let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j]
            if(newItem.goodsId === oldItem.goodsId){
              newGoodsList[j].selected = true;
              break;
            }
          }
        }
        this.table_dataList = newGoodsList;
        this.table_listTotal = res.data.total;
        this.table_listLoading = false;
      })
    },

    // 查询重复值并禁选
    checkboxSelect (row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      }else{
        return true // 不禁用
      }
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可切换分页');
      }
      this.table_currentPage = val;
      this.getGoodsList();
    },

    // table点击选择商品
    handleChooseGoods(val) {
      this.table_chooseGoods = val;
    },

    addGoods() {
      this.addGoodsVisible = true;
      this.getClassifyList();
    },

    // 取消 选择商品
    cancelAddGoods(){
      this.addGoodsVisible = false;
    },

    // 提交 选择商品
    submitAddGoods() {
      let oldGoodsList = this.goodsList;
      let newGoodsList = this.table_chooseGoods;
      this.goodsList = oldGoodsList.concat(newGoodsList);
      this.addGoodsVisible = false;
    },

    // 删除商品
    deleteGoods(id) {
      let index = findElem(this.goodsList, 'goodsId', id);
      this.goodsList.splice(index, 1);
    },

    // 给日期减一天
    reduceDate(date, days) {
      if (days == undefined || days == '') {
        days = 1;
      }
      var date = new Date(date);
      date.setDate(date.getDate() - days);
      var month = date.getMonth() + 1;
      var day = date.getDate();
      function checkTime(i){
        if (i<10) {
          i = "0"+i;
        }
        return i;
      }
      return date.getFullYear() + '-' + checkTime(month) + '-' + checkTime(day);
    },

    // 给日期加一天
    addDate(date, days) {
      if (days == undefined || days == '') {
        days = 1;
      }
      var date = new Date(date);
      date.setDate(date.getDate() + days);
      var month = date.getMonth() + 1;
      var day = date.getDate();
      function checkTime(i){
        if (i<10) {
          i = "0"+i;
        }
        return i;
      }
      return date.getFullYear() + '-' + checkTime(month) + '-' + checkTime(day);
    },

    // 提交表单
    submitMainForm() {
      if(this.mainForm.stageList.length < 1) {
        return this.$warningNotify('至少选择一个活动场次');
      }
      if(this.goodsList.length < 1) {
        return this.$warningNotify('至少选择一个商品');
      }
      let goodsList = this.goodsList;
      for(let i=0; i<goodsList.length; i++) {
        if(!Number(goodsList[i].sharePercent) && (goodsList[i].amount / goodsList[i].price > 0.4)) {
          this.formLoading = false;
          this.$errorMsg('单个商品的分佣金额不能超过秒杀价的40%');
          return;
        }
        if(Number(goodsList[i].sharePercent) < 0 || Number(goodsList[i].sharePercent) > 40) {
          this.formLoading = false;
          this.$errorMsg('单个商品的分佣比例范围在0-40');
          return;
        }
      }
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          this.formLoading = true;

          let stageList = [];
          this.mainForm.stageList.forEach(item => {
            let index = findElem(this.stageArr, 'name', item)
            if(index >= 0) {
              stageList.push(this.stageArr[index]);
            }
          })

          let params = {
            secKillName: this.mainForm.activityName,
            startTime: this.mainForm.activityDate[0] + ' 10:00:00',
            endTime: this.addDate(this.mainForm.activityDate[1]) + ' 09:59:59',
            remark: this.mainForm.remark,
            goodsSpecs: this.goodsList,
            stages: stageList
          }
          params = deleteEmptyObj(params);

          if(this.isEdit) {
            params.secKillId = this.editId;
            editActivity(params).then(res => {
              this.formLoading = false;
              this.$successMsg('编辑成功');
              setTimeout(()=>{
                this.goBack();
              }, 1000)
            }).catch(err => {
              this.formLoading = false;
            })
          } else {
            addActivity(params).then(res => {
              this.formLoading = false;
              this.$successMsg('添加成功');
              setTimeout(()=>{
                this.goBack();
              }, 1000)
            }).catch(err => {
              this.formLoading = false;
            })
          }
        }else {
          this.$warningNotify('请先完善信息');
          return false;
        }
      })
    },
  },

}
</script>

<style scoped lang="scss">
  .dialog-container {
    .left {
      width: 140px;
      height: 350px;
      overflow-y: scroll;
      .group {
        margin-top: 10px;
      }
      .child {
        margin-top: 5px;
        .item {
          padding-left: 18px;
        }
      }
      .item {
        cursor: pointer;
        line-height: 24px;
      }
    }
    .right {
      width: calc(100% - 140px);
      height: 350px;
      box-sizing: border-box;
      padding-left: 20px;
    }
  }

  .page-footer {
    height: 70px;
  }
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    background: #fff;
    padding: 15px 40px;
    box-sizing: border-box;
    transition: all 0.28s;
    text-align: right;
    box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);
    &.hideSidebar {
      margin-left: 54px;
      width: calc(100vw - 54px);
    }
    &.openSidebar {
      margin-left: 210px;
      width: calc(100vw - 210px);
    }
  }
</style>