<template>
  <div class="AddsetupActicity">
    <div class="form-box" style="margin-top: 0">
      <div>
        <span style="color: rgb(64, 158, 255);cursor: pointer;margin-left: 20px" @click="cancel">活动管理</span>
        <span style="margin: 0 5px;color: #C0C4CC;">/</span>
        <span>活动编辑</span>
      </div>
    </div>
    <div class="el-card__body" style="background-color: white; padding: 0px;margin-top: 20px">
      <el-form :model="msg" style="padding:0 20px;" :rules="rules" ref="msg" label-width="160px" size="small">
        <div class="form-body">
          <el-form-item label="活动名称" prop="ActivityName" class="is-required">
            <el-input v-model="msg.ActivityName" />
          </el-form-item>
          <el-form-item label="封面图" prop="CoverImage" class="is-required">
            <button class="el-button el-button--default el-button--small" @click="openChangeDig(1)">
              选择图片
            </button>
            <div class="img_yuan inputM_l">
              <img v-if="msg.CoverImage=='' || msg.CoverImage==null" src="../../assets/img/setup/default_img.png" alt="">
              <img v-else :src="msg.CoverImage" alt="">
            </div>
          </el-form-item>

          <el-form-item label="活动对象"  class="is-required" >
            <el-radio v-model="msg.ActiveObject"  label="1">分销商 </el-radio>
            <el-radio v-model="msg.ActiveObject" label="2">所有用户</el-radio>
          </el-form-item>
          <el-form-item label="分销等级">
            <el-select  v-model="msg.Tier"  placeholder="请选择">
              <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-form-item>
          <el-form-item label="活动类型">
            <el-select  v-model="msg.Type"  placeholder="请选择">
              <el-option label="订单数量" :value="1"></el-option>
              <el-option label="订单金额" :value="2"></el-option>
              <el-option label="商品数量" :value="3"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item label="订单数量"  class="is-required" v-if="msg.Type==1">
            <el-input v-model="msg.OrderNum" step="1" min="0"
                      onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''">
              <template slot="append">单</template>
            </el-input>
          </el-form-item>
          <el-form-item label="订单金额"  class="is-required" v-if="msg.Type==2">
            <el-input v-model="msg.OrderMoney" step="1" min="0"
                      onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品数量"  class="is-required" v-if="msg.Type==3">
            <el-input v-model="msg.GoodsNum" step="1" min="0"
                      onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''">
              <template slot="append">个</template>
            </el-input>
          </el-form-item>

          <el-form-item label="奖品名称"  class="is-required" prop="PrizeName">
            <el-input v-model="msg.PrizeName" />
          </el-form-item>
          <el-form-item label="奖品图片" prop="PrizeImage" class="is-required">
            <button class="el-button el-button--default el-button--small" @click="openChangeDig(2)">
              选择图片
            </button>
            <div class="img_yuan inputM_l">
              <img v-if="msg.PrizeImage=='' || msg.PrizeImage==null" src="../../assets/img/setup/default_img.png" alt="">
              <img v-else :src="msg.PrizeImage" alt="">
            </div>
          </el-form-item>
          <el-form-item label="验证码长度"  class="is-required" >

            <el-select  v-model="msg.CodeLength"  placeholder="请选择">
              <el-option label="4位" :value="4"></el-option>
              <el-option label="6位" :value="6"></el-option>
              <el-option label="8位" :value="8"></el-option>
              <el-option label="10位" :value="10"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item label="有效期范围" class="is-required" prop="value">
            <el-date-picker @input="daterangeChange" style="padding: 3px 10px;width: 450px;height: 32px"
                            v-model.trim="msg.value" type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" value-format="yyyy-MM-dd" align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="兑换期限" class="is-required" prop="ReceiveTime">
            <el-date-picker
              v-model="msg.ReceiveTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="领取方式"  class="is-required" >
            <el-radio v-model="msg.Way" disabled label="1">线上</el-radio>
            <el-radio v-model="msg.Way" label="2">线下</el-radio>
          </el-form-item>

          <el-form-item label="参与商品类别或商品">
            <div style="display: flex;flex-direction: row;align-items: center">
              <div @click="getUseType(1)" style="margin-right: 15px">
                <el-radio :label="1" v-model="msg.RangeType">分类</el-radio>
              </div>
              <div @click='getUseType(2)' style="margin-right: 15px">
                <el-radio :label="2" v-model="msg.RangeType">指定商品</el-radio>
              </div>
            </div>
            <div class="splist" v-if="msg.RangeType==1">
              <div v-for="(item,index) in AppointList" :label="item.ProductId" :key="index" style="margin-right: 20px;"
                   class="el-tag el-tag--warning el-tag--plain">
                <span>{{item.Name}}</span>
                <i class="el-tag__close el-icon-close" @click="deleteProduct(item,index)"></i>
              </div>
            </div>

            <div class="splist" v-if="msg.RangeType==2">
              <div v-for="(item,index) in commoditylist" :label="item.ProductId" :key="index"
                   style="margin-right: 20px; position: relative; cursor: pointer;margin-bottom: 10px">
                <div class="app-image" :style="{backgroundImage:'url(' + item.CoverImage + ')',backgroundSize:'cover'}">
                </div>
                <i class="el-icon-error" style="position: absolute;right: -5px;top:-5px;color: #F56C6C;font-size: 20px"
                   @click="deletecommod(item,index)"></i>
              </div>
            </div>
          </el-form-item>



          <el-form-item label="启用状态" v-if="!this.$route.query.ID">
            <el-switch :active-value="1" :inactive-value="2" v-model="msg.Enable">
            </el-switch>
          </el-form-item>
          <el-form-item label="活动描述" prop="Description">
            <el-input type="textarea" :rows="2" v-model="msg.Description">
            </el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-button type="primary" style="margin: 12px 0" size="small" @click="preserve('msg')" :loading="loading">保存
    </el-button>
    <!--已指定商品类别选择-->
    <el-dialog title="已指定商品类别" :visible.sync="category" width="714px">
      <div style="height:400px;overflow:auto;">
        <el-tree :data="ProductCategoryTreeList" show-checkbox :check-strictly="true" default-expand-all node-key="Id" ref="tree"
                 :default-checked-keys="checkedkeys" @check="TreeList" :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="category = false" size="small">取 消</el-button>
        <el-button type="primary" @click="getProductList" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <!--选择的商品列表-->
    <el-dialog title="添加商品" :visible.sync="addcommodity" width="1024px">
      <template>
        <div class="el-form-item">
          <div class="el-form-item__content">
            <div class="el-input el-input--small" style="width: 40%;">
              <input type="text" autocomplete="off" placeholder="商品名称" class="el-input__inner" v-model="msg2.Name"
                     @clear="msg2.pageIndex=1,getProductGoodsPageList()" clearable>
            </div>
            <button type="button" class="el-button el-button--default el-button--small" style="margin-left: 15px"
                    @click="msg2.pageIndex=1,getProductGoodsPageList()">查找商品</button>
            <button class="el-button el-button--default el-button--small" style="float: right;"
                    @click="batchAdd">批量添加</button>
          </div>
        </div>
        <el-table v-loading="loading_t" :data="tableData" ref="dataTable" @selection-change="handleSelectionChange"
                  style="width: 984px">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="Id" label="ID" width="80">
          </el-table-column>
          <el-table-column label="商品图" width="80">
            <template slot-scope="scope">
              <img style="width:50px;height:50px;margin-right:1px" :src="scope.row.CoverImage" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="Name" label="商品名称" width="333">
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" plain size="mini" @click="addtableData(scope)" :disabled="scope.row.disabled">
                {{scope.row.disabled==true? '已添加':'添加'}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="text-align:right" background @current-change="handleCurrentChange"
                       :page-size="msg2.pageSize" layout="prev, pager, next" :current-page.sync="msg2.pageIndex" :total="count">
        </el-pagination>
      </template>
    </el-dialog>
    <!-- 选择文件 -->
    <el-dialog title="选择文件" :visible.sync="changeState" width="1240px">
      <ChooseImg @SelectId="SelectId" ref="mychild"></ChooseImg>
    </el-dialog>
  </div>
</template>

<script>
  import ChooseImg from "@/components/global/ChooseImg.vue";

  export default {
    name: "AddsetupActicity",
    components: {
      ChooseImg,
    },
    data() {
      return {
        msg: {
          ID: 0,
          ActivityName: '',
          CoverImage:'',
          Tier: 0,
          Type:1,
          RangeType:0,
          RangeIds:[],
          Way:'2',//领取方式 1线上 2线下
          CodeLength:4,//验证码长度
          StartTime: '',
          EndTime: '',
          Description:'',
          ReceiveTime:'',//兑换期限
          Enable:1,//
          value: [],
          OrderNum:0,
          OrderMoney:0,
          GoodsNum:0,
          PrizeName:'',
          PrizeImage:'',
          ActiveObject:"1",

        },
        checkedkeys: [], //默认选中的
        checked: true,
        loading: false,
        addcommodity: false,
        commoditylist: [], //商品的list
        changeState: false,
        SmallShopData: [],
        rules: {
          ActivityName: [{
            required: true,
            message: "活动名称不能为空",
            trigger: "blur"
          }],

          CoverImage: [{
            required: true,
            message: "请选择活动图片",
            trigger: "blur"
          }],
          PrizeName: [{
            required: true,
            message: "奖品名称不能为空",
            trigger: "blur"
          }],

          PrizeImage: [{
            required: true,
            message: "请选择奖品图片",
            trigger: "blur"
          }],


          ReceiveTime:[{
            required: true,
            message: "请选择兑换时间",
            trigger: "blur"
          }],

          value: [{
            type: 'array',
            required: true,
            message: '活动有效期不能为空',
            trigger: 'change'
          }

          ]
        },
        cityOptions: [],
        cities: [],
        checkAll: false,
        isIndeterminate: false,
        category: false,
        ProductCategoryTreeList: [],
        AppointList: [], //指定商品分类
        defaultProps: {
          children: 'ChildList',
          label: 'Name'
        },
        eData: {},
        msg2: {
          pageIndex: 1,
          pageSize: 15,
          Name: '',
          GoodsStatus: 0,
          IsSelectSellOut: 0,
          CategoryIds: '',
          Id: 0,
          StartTime: '',
          EndTime: '',
        },
        tableData: [],
        loading_t: false,
        count: 0,
        multipleSelection: [],
        AppointList2: [],
        SmallShopMsg: {
          Name: '',
        },
        storeCheck: [], //门店多选
        imgtype:0,
      }
    },
    created() {
      this.getMemberGradeList()
      this.getSmallShopsDropDownList()
      this.getProductGoodsPageList();
      if (this.$route.query.ID) {
        this.msg.ID = this.$route.query.ID;
        this.getData()
      }

    },
    methods: {

      getMemberGradeList() {
        // this.cityOptions = [];
        // this.apipost("/api/User/GetMemberGradeList", {}, res => {
        //   this.cities = res.data.data;
        //   let data = res.data.data;
        //   data.forEach(item => {
        //     this.cityOptions.push(item.Id)
        //   })
        //
        // })
        this.getProductCategoryTreeList()
      },

      getData(){
        this.apipost("/api/product/GetGoodsActivityInfo", {
          ActivityId: this.msg.ID
        }, res => {
          if (res.data.resultCode == 1) {
            this.msg = res.data.data;
            this.msg.value = [];
            this.msg.value.push(res.data.data.StartTime)
            this.msg.value.push(res.data.data.EndTime)
            this.msg.Way = res.data.data.Way.toString()
            if(res.data.data.ActiveObject){
              this.msg.ActiveObject =  res.data.data.ActiveObject.toString()

            }


            if (res.data.data.RangeType == 1) {
              let ProductList = res.data.data.RangeList;
              this.AppointList = []
              this.getProductCategoryTreeList();
              for (let i = 0; i < ProductList.length; i++) {
                this.checkedkeys.push(ProductList[i].Id)
                var objList = this.getObjById(this.ProductCategoryTreeList, ProductList[i].Id);

                if (objList) {
                  this.AppointList.push({
                    ProductId: objList.Id,
                    Name: objList.Name
                  })
                }
              }
            }
            if (res.data.data.RangeType == 2) {
              this.commoditylist = this.msg.RangeList;
              this.commoditylist.forEach(x=>{
                x.CoverImage = x.Image
              })
              var myTable = [];
              this.apipost("/api/product/GetProductGoodsPageList", this.msg2, res => {
                if (res.data.resultCode == 1) {
                  myTable = res.data.data.pageData;
                }
                myTable.forEach((x,xi) => {
                  this.msg.RangeList.forEach((y,yi) => {
                    if (y.Id == x.Id) {
                      // this.commoditylist.push(x);
                      x.disabled=true;
                    }

                  })
                })
                this.tableData = myTable;
              })
            }
          } else {
            this.Error(res.data.message);
          }
        })
      },
      getProductCategoryTreeList() {
        this.apipost("/api/AppletGoods/GetProductCategoryTreeList", {}, res => {
          if (res.data.resultCode == 1) {
            this.ProductCategoryTreeList = res.data.data
          } else {
            this.Error(res.data.message);
          }
        })
      },
      getProductGoodsPageList() {
        this.loading_t = true
        this.apipost("/api/product/GetProductGoodsPageList", this.msg2, res => {
          this.loading_t = false;
          if (res.data.resultCode == 1) {
            this.tableData = res.data.data.pageData
            this.count = res.data.data.count
            if(this.msg.RangeList.length>0){
              this.tableData.forEach(x=>{
                this.msg.RangeList.forEach(j=>{
                  if(x.Id == j.Id){
                    x.disabled=true
                  }
                })
              })
            }
          }
        })
      },
      cancel() {
        this.$router.go(-1)
      },
      handleCheckAllChange(val) {
        this.msg.MemberLevelList = val ? this.cityOptions : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },

      addtableData(data) {
        var myTable = JSON.parse(JSON.stringify(this.tableData));
        myTable[data.$index].disabled = true;
        this.commoditylist.push(data.row);
        this.tableData=myTable;
        this.Success('添加成功');
      },
      batchAdd() { //批量添加
        let newdata = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.commoditylist.length > 0) {
            for (let j = 0; j < this.commoditylist.length; j++) {
              if (this.multipleSelection[i].Id != this.commoditylist[j].Id) {
                newdata.push(this.multipleSelection[i])
                for (let z = 0; z < this.tableData.length; z++) {
                  if (this.tableData[z].Id == this.multipleSelection[i].Id) {
                    this.tableData[z].disabled = true;
                    break
                  }
                }
              }
            }
          } else {
            newdata.push(this.multipleSelection[i])
            for (let z = 0; z < this.tableData.length; z++) {
              if (this.tableData[z].Id == this.multipleSelection[i].Id) {
                this.tableData[z].disabled = true;
                break

              }
            }
          }
        }
        if (newdata.length > 0) {
          this.Success('添加成功');
        }
        this.commoditylist = this.unique(this.commoditylist.concat(newdata));
        this.$refs.dataTable.clearSelection()
      },
      // 数组去重
      unique(arr) {
        for (var i = 0, len = arr.length; i < len; i++) {
          for (var j = i + 1, len = arr.length; j < len; j++) {
            if (arr[i].Id === arr[j].Id) {
              arr.splice(j, 1);
              j--; // 每删除一个数j的值就减1
              len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
            }
          }
        }
        return arr;
      },
      deletecommod(data, index) {
        this.tableData.forEach(x => {
          if (data.Id == x.Id) {
            x.disabled = false
            this.commoditylist.splice(index, 1)
          }
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      getUseType(val) {
        if (val == 1) {
          this.category = true;
          this.$nextTick(() => { //在弹出dialog之前执行$nextTick回调函数，确保el-tree已经渲染
            this.$refs.tree.setCheckedKeys(this.checkedkeys);
          });
        } else if (val == 2) {
          this.checkedkeys = []
          this.addcommodity = true
        }
      },
      daterangeChange(e) {
        let _this = this
        if (e == null) {
          _this.msg.value = []
        } else {

          _this.$nextTick(() => {
            _this.$set(_this.msg, "value", [e[0], e[1]]);
          });
        }
        _this.$forceUpdate();


      },
      getUseType2() {
        this.checkedkeys = []
      },
      deleteProduct(item, index) {
        this.AppointList.splice(index, 1)
        for (let i = 0; i < this.checkedkeys.length; i++) {
          if (this.checkedkeys[i] == item.ProductId) {
            this.checkedkeys.splice(i, 1)
          }
        }
      },
      handleCurrentChange(val) {
        this.msg2.pageIndex = val;
        this.getProductGoodsPageList();
      },
      TreeList(val, e) {
        this.eData = e
      },
      preserve(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.msg.value.length > 0) {
              this.msg.StartTime = this.msg.value[0];
              this.msg.EndTime = this.msg.value[1];
              this.msg.IndateDay = 0
            } else {
              this.Error('活动有效期不能为空')
              return false
            }

            if (this.msg.RangeType == 2) {
              let data = []
              this.commoditylist.forEach(x=>{
                data.push(x.Id)
              })
              this.msg.RangeIds = data.join(',');
              if(this.commoditylist.length==0){
                this.Error('请选择指定商品');
                return;
              }
            } else if (this.msg.RangeType == 1) {
              let data = []
              this.AppointList.forEach(x=>{
                data.push(x.ProductId)
              })
              this.msg.RangeIds = data.join(',');

              if(this.AppointList.length==0){
                this.Error('请选择指定商品分类');
                return;
              }
            }

            if(this.msg.Type==1 && (this.msg.OrderNum=='' || this.msg.OrderNum==null || this.msg.OrderNum==0) ){
              this.Error('订单数量大于0');
              return;
            }else if(this.msg.Type==2 && (this.msg.OrderMoney=='' || this.msg.OrderMoney==null || this.msg.OrderMoney==0) ){
              this.Error('订单金额大于0');
              return;
            }else if(this.msg.Type==3 && (this.msg.GoodsNum=='' || this.msg.GoodsNum==null || this.msg.GoodsNum==0) ){
              this.Error('商品数量大于0');
              return;
            }
            if(new Date(this.msg.EndTime).getTime()>= new Date(this.msg.ReceiveTime).getTime()){
              this.Error('兑换期限大于结束时期');
              return;
            }

            this.loading = true

            this.apipost("/api/product/SetGoodsActivityInfo", this.msg, res => {
              this.loading = false
              if (res.data.resultCode == 1) {
                this.Success(res.data.message);
                this.$router.go(-1); //返回上一层

              } else {
                this.Info(res.data.message);
              }
            })
          } else {
            return false;
          }
        });
      },
      getProductList() {
        this.category = false;
        let e = this.eData;
        let ProductList = []
        this.checkedkeys = e.checkedKeys;
        if (e.checkedNodes.length > 0) {
          this.checkedkeys.forEach(x => {
            var objList = this.getObjById(this.ProductCategoryTreeList, x);
            if (objList) {
              for (var i = 0; i < this.AppointList.length; i++) {
                if (this.AppointList[i].ProductId == objList.Id) {
                  return;
                }
              }
              this.AppointList.push({
                ProductId: objList.Id,
                Name: objList.Name
              })
            }
          })
        }
      },
      getObjById(list, id) {
        if (!list instanceof Array) {
          return null
        }
        //遍历数组
        for (let i in list) {
          let item = list[i]
          if (item.Id === id) {
            return item
          } else {
            //查不到继续遍历
            if (item.ChildList) {
              let value = this.getObjById(item.ChildList, id)
              //查询到直接返回
              if (value) {
                return value
              }
            }
          }
        }
      },

      ChangeListName(val) {
        this.SmallShopMsg.Name = val;
        this.getSmallShopsDropDownList()

      },
      getSmallShopsDropDownList() {
        this.apipost("/api/SmallShops/GetAllSmallShopsList", this.SmallShopMsg, res => {
          this.loading = false
          if (res.data.resultCode == 1) {
            this.SmallShopData = res.data.data
          } else {
            this.Info(res.data.message);
          }
        })
      },
      openChangeDig(type) {
        this.imgtype=type
        this.changeState = true;
        setTimeout(() => {
          this.$refs.mychild.InitData();
        }, 10)
      },
      SelectId(msg) {
        this.changeState = false;
        if(this.imgtype==1){
          this.msg.CoverImage = this.getIconLink(msg.url);

        }else if(this.imgtype==2){
          this.msg.PrizeImage = this.getIconLink(msg.url);

        }
      },

    },
    mounted() {

    }
  }

</script>

<style>
  .AddsetupActicity .form-box {
    background: #fff;
    padding: 20px 50% 20px 0;
    margin-top: 10px;
  }

  .AddsetupActicity .el-input--small .el-input__inner {
    height: 32px;
    line-height: 32px;
  }

  .AddsetupActicity .img_yuan {
    width: 80px;
    height: 80px;
    margin-top: 5px;
    position: relative;
  }

  .AddsetupActicity .img_yuan img {
    width: 100%;
    height: 100%;
  }

  .AddsetupActicity .el-date-editor .el-range__icon {
    line-height: 24px;
  }

  .AddsetupActicity .el-date-editor .el-range-separator {
    line-height: 24px;

  }

  .AddsetupActicity .el-date-editor .el-range__close-icon {
    line-height: 24px;

  }

  .AddsetupActicity .el-form-item__label {
    padding: 0 20px 0 0;
  }

  .AddsetupActicity .form-body {
    background-color: #fff;
    padding: 10px 50% 10px 20px;
    min-width: 1000px;
  }

  .AddsetupActicity .splist {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .AddsetupActicity .app-image {
    width: 50px;
    height: 50px;
    border-radius: 0%;
    background-position: center center;
  }

</style>
