<template>
  <div class="detail-container">
    <el-page-header @back="goBack" :content="listItem && listItem.id ? '编辑':'新增'"></el-page-header>
    <el-divider></el-divider>

    <div class="form-contaner">
      <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-width="100px">
        <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="date">
          <el-date-picker
            v-model="mainForm.date"
            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="people">
          <el-radio-group v-model="mainForm.people">
            <el-radio :label="1">所有人</el-radio>
            <el-radio :label="2">普通会员</el-radio>
            <el-radio :label="3">业务员</el-radio>
            <el-radio :label="4">团长</el-radio>
            <el-radio :label="5">内部人员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <el-divider></el-divider>

    <div class="label"><span>*</span>设置活动门槛：</div>
    <div class="btn-group">
      <el-button type="primary" size="small" @click="addThreshold">添加阶梯</el-button>
    </div>
    <div class="tips">注：件数只能是整数，折扣优惠填写必须是0&lt;x&lt;10的数字，保留两位小数点。</div>

    <div class="threshold-list">
      <div class="item" v-for="(item, index) in thresholdList" :key="index">
        <div class="left">
          <div>满<el-input type="number" size="small" v-model="item.satisfyNum" placeholder="请输入"></el-input>件</div>
          <div>打<el-input type="number" size="small" v-model="item.discountRate" placeholder="请输入"></el-input>折</div>
          <div>佣金比例<el-input type="number" size="small" v-model="item.shareRate" placeholder="请输入"></el-input>%</div>
        </div>
        <div class="right">
          <el-button type="danger" icon="el-icon-delete" plain size="small" v-if="thresholdList.length > 1" @click="delThreshold(index)">删除</el-button>
        </div>
      </div>
    </div>

    <el-divider></el-divider>

    <div class="label"><span>*</span>选择参与产品：</div>

    <div class="mymain-container">
      <div class="btn-group">
        <el-button size="small" type="primary" @click="addClassify">选择分类</el-button>
        <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="110">
            <template slot-scope="scope">
              ¥{{ scope.row.goodsPrice }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="库存" prop="stockNum"></el-table-column>
          <el-table-column align="center" label="销量" prop="soldNum"></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'success':'danger'">{{ scope.row.status ? '上架':'下架' }}</el-tag>
            </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)" style="color: #F56C6C;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="page-footer">
      <div class="footer">
        <el-button type="primary" @click="submitMainForm" :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 { submitData, getDetail } from '@/api/fullpiece_discount'
import { deleteEmptyObj, findElem } from '@/utils/util'

let defaultObj = {
  satisfyNum: '',
  discountRate: '',
  shareRate: ''
}

export default {
  props: ['listItem'],
  data() {
    return {
      editId: '',
      mainForm: {
        name: '',
        date: '',
        people: 1,
      },
      mainFormRules: {
        name: [
          { required: true, message: '请填写活动名称', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择活动时间', trigger: 'change' }
        ],
        people: [
          { required: true, message: '请选择适用范围', trigger: 'change' }
        ],
      },
      formLoading: false,

      thresholdList: [JSON.parse(JSON.stringify(defaultObj))],

      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中 当前选择商品

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

    }
  },

  created() {
    this.editId = this.listItem.id;

    if(this.editId) {
      this.getDetail();
    }
  },

  methods: {
    // 返回主页
    goBack(needRefresh) {
      this.$emit('backList', needRefresh);
    },

    getDetail() {
      getDetail({id: this.editId}).then(res => {
        if(!res.data) return this.$errorMsg(`数据返回异常：${res.data}`);
        this.mainForm = {
          name: res.data.name,
          date: [res.data.startTime.slice(0, 10), res.data.endTime.slice(0, 10)],
          people: res.data.useType,
        }
        this.goodsList = res.data.goodsList;
        res.data.itemList.forEach(item => {
          item.discountRate = item.discountRate * 10;
          item.shareRate = item.shareRate * 100;
        })
        this.thresholdList = res.data.itemList;
      })
    },

    // 添加阶梯
    addThreshold() {
      this.thresholdList.push(JSON.parse(JSON.stringify(defaultObj)));
    },

    // 删除阶梯
    delThreshold(index) {
      this.thresholdList.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.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);
    },

    // 打开 选择分类
    addClassify() {
      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.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.goodsList = showGoodsList;
        this.addClassifyVisible = false;
      })
    },


    submitMainForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          let thresholdList = JSON.parse(JSON.stringify(this.thresholdList));
          for(let i=0; i<thresholdList.length; i++) {
            if(thresholdList[i].satisfyNum === '') {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】件数 不能为空`);
            }
            if(thresholdList[i].satisfyNum <= 0) {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】件数 需大于0`);
            }
            if(thresholdList[i].satisfyNum % 1 !== 0) {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】件数 需为整数`);
            }

            if(thresholdList[i].discountRate === '') {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】折扣 不能为空`);
            }
            if(thresholdList[i].discountRate <= 0 || thresholdList[i].discountRate >= 10) {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】折扣 需大于0且小于10`);
            }

            if(thresholdList[i].shareRate === '') {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】佣金比例 不能为空`);
            }
            if(thresholdList[i].shareRate <= 0 || thresholdList[i].shareRate >= 100) {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】佣金比例 需大于0且小于100`);
            }
            if(thresholdList[i].shareRate % 1 !== 0) {
              return this.$errorMsg(`【活动门槛-阶梯${i+1}】佣金比例 需为整数`);
            }
          }

          if(this.goodsList.length <= 0) {
            return this.$errorMsg('请选择商品');
          }

          let goodsIds = [];
          this.goodsList.forEach(item => {
            goodsIds.push(item.goodsId);
          })

          thresholdList.forEach(item => {
            item.discountRate = item.discountRate / 10;
            item.shareRate = item.shareRate / 100;
          })

          this.formLoading = true;

          let params = {
            name: this.mainForm.name,
            startTime: this.mainForm.date[0] + ' 00:00:00',
            endTime: this.mainForm.date[1] + ' 23:59:59',
            useType: this.mainForm.people,
            items: thresholdList,
            goodsIds
          }
          if(this.editId) {
            params.id = this.editId;
          }
          submitData(params).then(res => {
            this.formLoading = false;
            this.$successMsg('保存成功');
            setTimeout(()=>{
              this.goBack(true);
            }, 1000)
          }).catch(err => {
            this.formLoading = false;
          })
        }else {
          this.$errorMsg('请先完善信息');
          return false;
        }
      })
    },
  }

}
</script>

<style scoped lang="scss">
.detail-container {
  width:100%;
  height: 100%;
}
.label {
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  font-weight: 600;
  span {
    color: #F56C6C;
    margin-right: 4px;
  }
}
.tips {
  font-size: 12px;
  color: #F56C6C;
  font-weight: 500;
  margin-top: 10px;
}
.threshold-list {
  margin-left: 10px;
  .item {
    display: flex;
    align-items: center;
    margin-top: 15px;
    .left {
      display: flex;
      align-items: center;
      div {
        margin-right: 80px;
        font-size: 14px;
        color: #333333;
        flex-shrink: 0;
      }
      .el-input {
        width: 100px;
        margin: 0 8px;
      }
    }
  }
}
.mymain-container {
  margin-top: 0;
}
.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;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
::v-deep input[type='number'] {
  -moz-appearance: textfield;
}
</style>