<template>
  <div class="app-container">
    <el-card style="margin-bottom: 20px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-breadcrumb separator="/" style="margin-bottom: 35px">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/EventMarketing/center/index' }" >活动中心</el-breadcrumb-item>
        <el-breadcrumb-item>折扣营销</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form-item label="" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="状态">-->
<!--        <el-select v-model="queryParams.status" clearable placeholder="请选择活动状态">-->
<!--          <el-option label="启用" value="0"></el-option>-->
<!--          <el-option label="禁用" value="1"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="" prop="isonline">
        <el-select v-model="queryParams.isonline" clearable placeholder="请选择是否在线">
          <el-option label="在线" value="0"></el-option>
          <el-option label="下线" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>
    </el-card>

    <el-card style="margin-bottom: 20px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="activeDiscountList" @selection-change="handleSelectionChange">
      <el-table-column
        type="index"
        align="center"
        label="序号"
      >
      </el-table-column>
<!--      <el-table-column label="活动编号" align="center" prop="id" />-->
      <el-table-column label="活动名称" align="center" prop="name" />
      <el-table-column label="适用油品" align="center" prop="adaptOil" >
        <template slot-scope="scope">
          <span > {{ getName(oilNameList,scope.row.adaptOil) }} </span>
        </template>
      </el-table-column>
      <el-table-column label="适用用户" align="center" prop="adaptOil" >
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.dieselUserLevel "> {{item}} </span>
        </template>
      </el-table-column>
      <el-table-column label="满足金额（元）" align="center" prop="adaptOil" >
        <template slot-scope="scope">
          <span> {{scope.row.activeDiscountChildList[0].amount}} </span>
        </template>
      </el-table-column>
      <el-table-column label="折扣优惠" align="center" prop="adaptOil" >
        <template slot-scope="scope">
          <span> {{scope.row.activeDiscountChildList[0].discount}}折 </span>
        </template>
      </el-table-column>

<!--      <el-table-column label="会员等级" align="center" prop="dieselUserLevel" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-for="(item,index) in scope.row.dieselUserLevel "> {{item}} </span>-->
<!--        </template>-->
<!--      </el-table-column>-->


      <el-table-column label="活动状态 " align="center" prop="status" >
      <template slot-scope="scope">
        <span style="cursor: pointer;" @click="qiyong(scope.row)" v-if="scope.row.status == 0"> <el-tag>在线</el-tag > </span>
        <span style="cursor: pointer;" @click="jinyong(scope.row)" v-if="scope.row.status == 1"> <el-tag type="danger">下线</el-tag>  </span>
      </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" prop="adaptUserType" >
        <template slot-scope="scope">
          <span >{{scope.row.activeStartTime || 0}}-{{scope.row.activeEndTime || 0}}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动更新时间" align="center" prop="updateTime" >
        <template slot-scope="scope">
          <span >{{scope.row.updateTime || '暂无更新'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="updateTime" >
        <template slot-scope="scope">
          <span >{{scope.row.createBy || ''}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="lookDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeletexia(scope.row)"
            v-if="scope.row.isonline == 0"
          >下线</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="Deleteshan(scope.row)"
            v-if="scope.row.isonline == 1"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <el-dialog title="详情统计" :visible.sync="opendetails" width="45%" append-to-body>
      <div style="display: flex;justify-content: space-between;width: 100%;">
        <div class="x-box">
          <div>优惠券数量统计</div>
          <div>总数量: {{statisticsyou.count ||0}}</div>
          <div>已使用数量: {{statisticsyou.countEd ||0}}</div>
          <div>未使用数量: {{statisticsyou.countLd ||0}}</div>
        </div>
        <div class="x-box">
          <div>兑换券数量统计</div>
          <div>总数量: {{statisticsyou.counts ||0}}</div>
          <div>已使用数量: {{statisticsyou.countEds ||0}}</div>
          <div>未使用数量: {{statisticsyou.countLds ||0}}</div>
        </div>
      </div>
      <el-table
        :data="looklist"
        style="width: 100%">
        <el-table-column
          prop="name"
          label="昵称"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="联系方式"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="领取日期"
        >
        </el-table-column>
        <el-table-column
          prop="exchangeFrom"
          label="获取方式"
        >
        </el-table-column>


      </el-table>


    </el-dialog>
    <!-- 添加或修改折扣营销对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-position="labelPosition" label-width="120px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="折扣规则" prop="activeDiscountChildList">
          <div  style="width: 100%; display: flex;align-items: center; margin-bottom: 10px  " v-for="(item,index) in activeDiscountChildList" :key="index">
            <div style="width: 25%;display: flex; align-items: center;margin-right: 20px " >
              <span style="margin: 0 5px">满</span>
              <el-input-number v-model="item.amount"  :min="0" :max="99999" label="0"></el-input-number>
              <span style="margin: 0 5px">元</span>
            </div>
            <div  style="width: 25%;display: flex; align-items: center;">
              <span style="margin: 0 5px">打</span>
              <el-input-number v-model="item.discount"  :min="0" :max="9.9" placeholder="1 ~ 9.9" label=""></el-input-number>
              <span style="margin: 0 5px">折</span>

            </div>
            <div @click="deleteactiveDiscountChildList(index)">
              <el-button type="danger" icon="el-icon-delete" circle style="margin-left: 8px"  ></el-button>
            </div>
          </div>
          <div >
            <el-button type="primary" icon="el-icon-plus" @click="addactiveDiscountChildList">新增</el-button>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="activeStartTime">
              <el-date-picker clearable
                              v-model="form.activeStartTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择活动开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" prop="activeEndTime">
              <el-date-picker clearable
                              v-model="form.activeEndTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择活动结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="是否有会员日" prop="memberDayType">
          <el-radio-group v-model="form.memberDayType">
            <el-radio label="0">无会员日</el-radio>
            <el-radio label="1">指定日</el-radio>
            <el-radio label="2">指定星期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.memberDayType=='1'" prop="monthDay">
          <el-checkbox-group v-model="monthDay" @change="changeMonth">
            <el-checkbox v-for="item in 31" :key="item" :label="item+''">{{item}}日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="form.memberDayType=='2'" prop="weekDay">
          <el-checkbox-group v-model="weekDay">
            <el-checkbox label="星期一">星期一</el-checkbox>
            <el-checkbox label="星期二">星期二</el-checkbox>
            <el-checkbox label="星期三">星期三</el-checkbox>
            <el-checkbox label="星期四">星期四</el-checkbox>
            <el-checkbox label="星期五">星期五</el-checkbox>
            <el-checkbox label="星期六">星期六</el-checkbox>
            <el-checkbox label="星期日">星期日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>



        <el-form-item label="可用油品" prop="adaptOil" >
          <el-checkbox-group v-model="form.adaptOil">
            <el-checkbox v-for="(item,index) in oillist" :label="item.id" :key="index">{{item.oilType}}{{item.oilName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="会员等级" prop="dieselUserLevel" >
          <el-select v-model="form.dieselUserLevel"  multiple clearable placeholder="会员等级">
            <el-option :label="item.name" :value="item.id.toString()" v-for="(item,index) in userGradeList" :key="index" >  </el-option>
          </el-select>
        </el-form-item>


<!--        <el-form-item label="参与条件" prop="participationCondition">
          <el-select v-model="form.participationCondition" clearable placeholder="请选择天参与条件">
            <el-option label="不限制" value="0"></el-option>
            <el-option label="优惠订单不参与" value="1"></el-option>

          </el-select>
        </el-form-item>-->
        <el-form-item label="参与次数类别" prop="participationAcount">
          <el-select v-model="form.participationAcount" clearable placeholder="请选择参与次数类别">
            <el-option label="不限制" value="0"></el-option>
            <el-option label="限制" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限制次数" prop="limitAcount" v-if="form.participationAcount ==1">
          <el-input-number v-model="form.limitAcount" placeholder="请输入限制次数" />
        </el-form-item>
<!--        <el-form-item label="是否上线" prop="isonline">-->
<!--          <el-select v-model="form.isonline" clearable placeholder="请选择参与次数类别">-->
<!--            <el-option label="上线" value="0"></el-option>-->
<!--            <el-option label="下线" value="1"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listActiveDiscount,
  getActiveDiscount,
  delActiveDiscount,
  addActiveDiscount,
  updateActiveDiscount,
  editActiveDiscount
} from "@/api/EventMarketing/activeDiscount";
import {
  delActiveConsumption, editActiveConsumption,
  getActiveConsumption,
  getoilName, looklook, looklooklook,
  updateActiveConsumption
} from "@/api/EventMarketing/activeConsumption";
import {listUserGrade} from "@/api/staff/user/usergrade";
import {getOilNameList} from "@/api/order/oilnumgun";

export default {
  name: "ActiveDiscount",
  data() {
    return {
      opendetails:false,
      looklist:[],
      statisticsyou:{},
      labelPosition:'left',
      discount:'',
      amount:'',
      activeDiscountChildList:[
        {amount:'',discount:''},

      ],
      userGradeList:[],
      oillist:['92#','95#','98#','0#','-10#','LNG','CNG','京92#','京95#','京0#'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 折扣营销表格数据
      activeDiscountList: [],
      // 油号列表
      oilNameList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chainStoreId: null,
        storeId: null,
        name: null,
        activeStartTime: null,
        activeEndTime: null,
        adaptOil: null,
        adaptUserType: null,
        memberType: null,
        dieselUserLevel: null,
        gasolineUserLevel: null,
        naturalUserLevel: null,
        paymentType: null,
        participationCondition: null,
        participationAcount: null,
        limitAcount: null,
        status: null,
        isonline: null,
      },
      weekDay:[],
      monthDay:[],
      // 表单参数
      form: {


      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        activeStartTime:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        activeEndTime:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        adaptOil:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        dieselUserLevel:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        gasolineUserLevel:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        naturalUserLevel:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        participationCondition:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        participationAcount:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        isonline:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        activeDiscountChildList:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        memberDayType:[
          { required: true, message: '不能为空', trigger: 'change' }
        ],
      }
    };
  },
  created() {
    console.log('dsbuaidhbiasuigbduaibduui')
    listUserGrade().then(res=>{
      console.log('1233333333333333333333' ,res)
      this.userGradeList = res.data.records

    })
    //
    this.getList();
    this.getoilName();

  },
  methods: {
    /** 查询折扣营销列表 */
    getList() {
      this.loading = true;
      listActiveDiscount(this.queryParams).then(response => {
        console.log(response)
        this.activeDiscountList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getoilName(){
      getoilName().then(res=>{
        console.log(res)
        this.oillist = res.data

      })
      getOilNameList().then( response => {
        this.oilNameList = response.data;
      })

    },
    listUserGrade(){

    },
    // 新增
    addactiveDiscountChildList(){
      let data = {
        // discount :this.form.activeDiscountChildList.discount,
        // amount:this.form.activeDiscountChildList.amount,
        discount :"",
        amount:"",

      }
      console.log(data)
        // this.form.activeDiscountChildList.push(data)
        this.activeDiscountChildList.push(data)
    },
    deleteactiveDiscountChildList(index){
      // this.form.activeDiscountChildList.splice(index, 1)
      this.activeDiscountChildList.splice(index, 1)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chainStoreId: null,
        storeId: null,
        name: null,
        activeStartTime: null,
        activeEndTime: null,
        adaptOil: [],
        adaptUserType: null,
        memberType: null,
        dieselUserLevel: [],
        gasolineUserLevel: [],
        naturalUserLevel: [],
        paymentType: null,
        participationCondition: null,
        participationAcount: null,
        limitAcount: null,
        status: 0,
        isonline: 0,
        activeDiscountChildList: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.activeDiscountChildList = [ {amount:'',discount:''}, ]
      this.monthDay = []
      this.weekDay = []
      this.open = true;
      this.title = "添加折扣营销";
    },
    changeMonth(val){
      console.log(val,this.monthDay,111)
    },
    // 获取油号名称
    getName(oilNameList,ids){
      let name = ""
      let _this = this;
      ids.forEach(i => {
        oilNameList.forEach(item => {
          if (item.id == i){
            name += item.oilName + ",";
          }
        })
      })
      return name;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getActiveDiscount(id).then(response => {
        console.log( response.data)
        this.form = response.data;
        if (response.data.activeDiscountChildList && response.data.activeDiscountChildList.length>0){
          this.activeDiscountChildList = response.data.activeDiscountChildList
        }else {
          this.activeDiscountChildList = [ {amount:'',discount:''}, ]
        }
        if (this.form.monthDay){
          this.monthDay = this.form.monthDay.split(",")
        }else {
          this.monthDay = []
        }
        if (this.form.weekDay){
          this.weekDay = this.form.weekDay.split(",")
        }else {
          this.weekDay = []
        }
        this.open = true;
        this.title = "修改折扣营销";
      });
    },
    handleDeletexia(row){
      // getActiveDiscount(row.id).then(response => {
      //   // this.form = response.data;
      //   let data = response.data
      //   data.isonline = 1
      //   updateActiveDiscount(data).then(response => {
      //     this.$modal.msgSuccess("下线成功");
      //     this.open = false;
      //     this.getList();
      //   });
      //
      // });

      this.$modal.confirm('确定下线此条修改折扣营销活动信息？').then(function() {
        return editActiveDiscount({id:row.id,isonline:1});
      }).then(() => {
        this.$modal.msgSuccess("下线成功");
        this.open = false;
        this.getList();
      }).catch(() => {});
    },
    qiyong(row){
      //
      if(row.isonline == 1){
        this.$message.error("下线不可进行操作")
        return
      }
      getActiveDiscount(row.id).then(response => {
        // this.form = response.data;
        let data = response.data
        data.status = 1
        updateActiveDiscount(data).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.open = false;
          this.getList();
        });

      });
    },
    jinyong(row){
      if(row.isonline == 1){
        this.$message.error("下线不可进行操作")
        return
      }
      getActiveDiscount(row.id).then(response => {
        // this.form = response.data;
        let data = response.data
        data.status = 0
        updateActiveDiscount(data).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.open = false;
          this.getList();
        });

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.activeDiscountChildList = this.activeDiscountChildList
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.monthDay = this.monthDay.toString()
          this.form.weekDay = this.weekDay.toString()
          if (this.form.id != null) {
            updateActiveDiscount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActiveDiscount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    lookDetail(row){
      this.opendetails = true
      let data = {
        id:row.id
      }
      looklook(data).then(res=>{
        this.looklist = res.data

        console.log('详情',res)
      })
      looklooklook(row.id).then(resp=>{
        this.statisticsyou = resp.data
        console.log('优惠券详情统计',resp)
      })
    },
    Deleteshan(row){

      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除此项折扣营销活动？').then(function() {
        return delActiveDiscount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除折扣营销编号为"' + ids + '"的数据项？').then(function() {
        return delActiveDiscount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/marketingActivity/activeDiscount/export', {
        ...this.queryParams
      }, `activeDiscount_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.box-bt{
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}
.x-box{
  background: #f9f9f9;
  border-radius: 6px;
  box-sizing: border-box;
  padding: 15px;
  width: 45%;
}
</style>
