<template>
  <div class="app-container">
    <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-width="100px" label-position="right">
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="mainForm.name" placeholder="请输入活动名称" style="width: 400px"></el-input>
      </el-form-item>

      <el-form-item label="活动有效期" prop="activityDate">
        <el-date-picker
          v-model="mainForm.activityDate"
          style="width: 400px"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item label="兑换码有效期" prop="exchangeDate">
        <el-date-picker
          v-model="mainForm.exchangeDate"
          style="width: 400px"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item label="优惠券有效期" prop="couponDate">
        <el-date-picker
          v-model="mainForm.couponDate"
          style="width: 400px"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item label="活动说明" prop="remark">
        <el-input type="textarea" v-model="mainForm.remark" placeholder="请输入活动说明" :rows="4"></el-input>
      </el-form-item>

      <el-divider></el-divider>

      <h4 class="title">优惠券<el-button size="small" type="primary" @click="addCoupon()">添加优惠券</el-button></h4>

      <div v-for="(item, index) in couponList" :key="index">
        <div class="title">优惠券{{index + 1}}<el-button type="danger" size="small" @click="delCoupon(index)">删除优惠券</el-button></div>

        <el-form-item label="优惠券名称" label-width="100px">
          <el-input v-model="item.couponName" placeholder="请输入优惠券名称" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="优惠券类型" label-width="100px">
          <el-radio-group v-model="item.couponType">
            <el-radio label="SATISFY">满减券</el-radio>
            <el-radio label="GOODS">商品券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="订单满足金额" label-width="100px" v-if="item.couponType == 'SATISFY'">
          <el-input v-model="item.orderLimitAmount" autocomplete="off" placeholder="请输入订单满足金额" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="优惠券面值" label-width="100px">
          <el-input v-model="item.discountAmount" autocomplete="off" placeholder="请输入优惠券面值" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="发放数量" label-width="100px">
          <el-input v-model="item.totalNum" autocomplete="off" placeholder="请输入发放数量" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="商品信息" label-width="100px" v-if="item.couponType == 'GOODS'">
          <div class="btn-group">
            <el-button size="small" type="primary" @click="addClassify(index)">选择分类</el-button>
            <el-button size="small" type="primary" @click="addGoods(index)">选择商品</el-button>
          </div>

          <div class="table">
            <el-table :data="item.goodsList" border fit stripe max-height="300px">
              <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="left" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
              
              <el-table-column align="center" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="text" @click="deleteGoods(index, scope.$index)" style="color: #F56C6C;">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="兑换码" label-width="100px">
          <el-radio-group v-model="item.exchange">
            <el-radio :label="1">系统自动生成</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="使用说明" label-width="100px">
          <el-input type="textarea" v-model="item.useRemark" placeholder="请输入使用说明" :rows="4"></el-input>
        </el-form-item>
      </div>

    </el-form>

    <div class="page-footer">
      <div class="footer">
        <el-button type="primary" @click="submitForm" :loading="formLoading">{{ formLoading ? '提交中 ...' : '提 交' }}</el-button>
        <el-popconfirm
          title="确定关闭吗？"
          @onConfirm="goBack"
          style="margin-left: 10px;"
        >
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </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>

    <!-- 选择分类 -->
    <el-dialog title="选择分类" :visible.sync="addClassifyVisible" :show-close="false" width="40%" :close-on-click-modal="false">
      <div class="classify-list">
        <el-tree
          :data="classifyList"
          show-checkbox
          default-expand-all
          node-key="categoryId"
          ref="tree"
          highlight-current
          :props="defaultProps">
        </el-tree>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddClassify">保 存</el-button>
        <el-button @click="cancelAddClassify">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getClassifyList, getGoodsList, getMoreGoodsList } from '@/api/goods'
import { addData } from "@/api/draw";

const defaultObj = {
  couponName: '',
  couponType: 'SATISFY', 
  orderLimitAmount: '',
  discountAmount: '',
  totalNum: '',
  exchange: 1,
  useRemark: '',
  goodsList: [],
}

export default {
  data() {
    return {
      mainForm: {
        name: '',
        activityDate: [],
        exchangeDate: [],
        couponDate: [],
        remark: '',
      },
      mainFormRules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
      },

      couponList: [JSON.parse(JSON.stringify(defaultObj))], // 优惠券列表

      formLoading: false,

      addGoodsVisible: false,

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

      addClassifyVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      handleCouponIndex: '',
    }
  },
  computed: {
    
  },

  created() {
    
  },

  methods: {

    // 新增优惠券
    addCoupon() {
      this.couponList.push(JSON.parse(JSON.stringify(defaultObj)));
    },

    // 删除优惠券
    delCoupon(index) {
      this.couponList.splice(index, 1);
    },

    // 获取分类列表
    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.couponList[this.handleCouponIndex].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(index) {
      this.handleCouponIndex = index;
      this.addGoodsVisible = true;
      this.getClassifyList();
    },

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

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

    // 删除商品
    deleteGoods(pidx, idx) {
      this.couponList[pidx].goodsList.splice(idx, 1);
    },

    // 打开 选择分类
    addClassify(index) {
      this.handleCouponIndex = index;
      this.addClassifyVisible = true;
      this.getClassifyList();
    },

    // 取消 选择分类
    cancelAddClassify(){
      this.addClassifyVisible = false;
    },

    // 提交 选择分类
    submitAddClassify() {
      if(this.$refs.tree.getCheckedNodes().length <= 0) {
        return this.$errorMsg('请选择分类');
      }
      let checkeds = this.$refs.tree.getCheckedNodes();
      let ids = [];
      checkeds.forEach(item => {
        if(item.level === 2) {
          ids.push(item.categoryId);
        }
      })
      getMoreGoodsList({ categoryIds: ids.join(',')}).then(res => {
        let oldGoodsList = this.couponList[this.handleCouponIndex].goodsList;
        let newGoodsList = res.data;
        let allGoodsList = oldGoodsList.concat(newGoodsList);
        let showGoodsList = [];
        let obj = {};
        for(var i =0; i<allGoodsList.length; i++){
            if(!obj[allGoodsList[i].goodsId]){
              showGoodsList.push(allGoodsList[i]);
              obj[allGoodsList[i].goodsId] = true;
            }
        }
        this.couponList[this.handleCouponIndex].goodsList = showGoodsList;
        this.addClassifyVisible = false;
      })
    },


    submitForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {

          let couponList = JSON.parse(JSON.stringify(this.couponList));
          for(let i=0; i < couponList.length; i++) {
            if(couponList[i].couponType == 'GOODS') {
              couponList[i].goodsIds = couponList[i].goodsList.map(item => {
                return item.goodsId;
              })
            }
            delete couponList[i].goodsList;
          }

          this.formLoading = true;

          let params = {
            name: this.mainForm.name,
            startTime: this.mainForm.activityDate.length ? this.mainForm.activityDate[0] + ' 00:00:00' : '',
            endTime: this.mainForm.activityDate.length ? this.mainForm.activityDate[1] + ' 23:59:59' : '',
            exchangeStartTime: this.mainForm.exchangeDate.length ? this.mainForm.exchangeDate[0] + ' 00:00:00' : '',
            exchangeEndTime: this.mainForm.exchangeDate.length ? this.mainForm.exchangeDate[1] + ' 23:59:59' : '',
            couponStartTime: this.mainForm.couponDate.length ? this.mainForm.couponDate[0] + ' 00:00:00' : '',
            couponEndTime: this.mainForm.couponDate.length ? this.mainForm.couponDate[1] + ' 23:59:59' : '',
            remark: this.mainForm.remark,
            promotionLuckDrawCoupons: couponList,
          }
          console.log(params);

          addData(params).then(res => {
            this.formLoading = false;
            this.$successMsg('新增成功');
            setTimeout(()=>{
              this.goBack();
            }, 1000)
          }).catch(err => {
            this.formLoading = false;
          })

        }
      })
    },

    goBack() {
      this.$router.go(-1);
      // this.$store.dispatch("tagsView/delView", this.$route);
    },
  }
}
</script>

<style lang="scss" scoped>
  .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;
    }
  }

  .classify-list {
    height: 50vh;
    overflow-y: scroll;
  }

  .title {
    font-size: 16px;
    margin-top: 30px;
    margin-bottom: 20px;
    padding-left: 10px;
    font-weight: bold;
    display: flex;
    align-items: center;
    .el-button {
      margin-left: 20px;
    }
  }
</style>