<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="是否开启积分规则功能"  label-width="160px">
        <el-radio-group v-model="ruleForm.integralFlag">
          <el-radio
            v-for="dict in integralFlagOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item  label="油品积分规则" ></el-form-item>
      <div>
        <el-row v-for="(item, index) in form.itemsDetail"  :key="index" style="margin-left: 80px;">
          <el-form
            :inline="true"
            :model="form.itemsDetail[index]"
            :rules="rules"
            ref="ruleForms"
            class="demo-form-inline"
            size="small"
          >
            <el-form-item>
              <span>规则类型</span>
              <el-select v-model="item.ruleType" placeholder="请选择规则" clearable size="small">
                <el-option
                  v-for="item in ruleTypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
              <span>满</span>
              <el-input-number v-model="item.ruleTerms" :min="0" size="small" />
              <span v-if="item.ruleType=='3'">L</span>
              <span v-else>元</span>
              <span>起累计 </span>
              <el-select v-model="item.oilName" placeholder="请选择油品" clearable size="small" @change="oilNameChang(index)" >
                <el-option
                  v-for="item in oilNameOptions"
                  :key="item.oilName"
                  :label="item.oilName"
                  :value="item.oilName"
                ></el-option>
              </el-select>
              <el-select
                v-model="item.gread"
                placeholder="请选择等级"
                clearable
                size="small"
              >
                <el-option
                  v-for="item in gradeOptions[index]"
                  :key="item.grade"
                  :label="item.grade"
                  :value="item.grade"
                ></el-option>
              </el-select>
              <span>每消费</span>
              <el-input-number v-model="item.saleAmt"  size="small" :min="0"/>
              <span v-if="item.ruleType=='3'">L</span>
              <span v-else>元</span>
              <el-input-number v-model="item.integral" size="small" :min="0"/>
              <span>积分</span>
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                @click="del(index)"
                size="small"
              >删除</el-button>
              <el-button
                v-show="index==rowsnum"
                type="success"
                @click="addItem()"
                size="small"
              >新增</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <el-form-item  label="非油品积分规则" ></el-form-item>
       <div>
        <el-row v-for="(item, index) in form.notOilList"  :key="index" style="margin-left: 80px;">
          <el-form
            :inline="true"
            :model="form.notOilList[index]"
            :rules="rules"
            ref="ruleForms"
            class="demo-form-inline"
            size="small"
          >
            <el-form-item>
              <span>满</span>
              <el-input-number v-model="item.ruleTerms" :min="0" size="small" />
              <span></span>
              <span>元  起累计 </span>
              <span>每消费</span>
              <el-input-number v-model="item.saleAmt"  size="small" :min="0"/>
              <span>元</span>
              <el-input-number v-model="item.integral" size="small" :min="0"/>
              <span>积分</span>
            </el-form-item>
            <el-button
                type="danger"
                @click="delNoil()"
                size="small"
              >清空非油品积分规则</el-button>
          </el-form>
        </el-row>
      </div>
       <el-form-item label="积分有效期设置" prop="termDateManage">
        <el-radio-group v-model="form.integralTermSetting">
          <el-radio
            v-for="dict in integralTermSettingOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
        <el-date-picker clearable size="small" style="width: 200px;margin-left: 10px;"
                        v-model="form.integralEmptyTime"
                        type="datetime">
        </el-date-picker>
      </el-form-item>
    
      <el-form-item label="积分活动时限" prop="termDateManage">
        <el-radio-group v-model="form.termDateManage">
          <el-radio
            v-for="dict in termDateManageOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
        <el-date-picker clearable size="small" style="width: 200px;margin-left: 10px;"
                        v-model="form.emptyDate"
                        type="date"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
    
      <el-form-item label="积分活动设置" ></el-form-item>
      <el-form-item label="多倍积分活动">
        <el-radio-group v-model="form.integralActivity">
          <el-radio
            v-for="dict in integralActivityOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row>
        <el-col :span="8" style="">
          <el-form-item  label="周期类型" prop="datePicker">
            <el-select v-model="form.datePicker" 
             clearable size="small" @change="datePickerChang" >
                <el-option
                  v-for="item in datePickerOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">  
          <el-form-item v-show="workDaytrue">
            <div style="display: flex;flex-wrap: wrap;border-style: solid;border-color:#F5F7FA">
              <div v-for="(item, index) in workDay" :key="index" style="margin:3px;">
                <div class="hover-style" style="border-radius:5px;font-weight:bold;font-size:12px;cursor: pointer;" @click="clickWorkDayCalendar(item, index)">
                  <div>{{ item }}</div>
                  <div v-if="collectClickWorkDay.indexOf(index) > -1" style="width:4px;height:4px;border-radius:50%;background-color:red;position: relative;left:calc(50% - 2px);"></div>
                  <div v-else style="width:4px;height:4px;"></div>
                </div>
              </div>
             </div>
          </el-form-item>
          <el-form-item v-show="moonDaytrue" >
             <div style="display: flex;flex-wrap: wrap;border-style: solid;border-color:#F5F7FA">
              <div v-for="(item, index) in moonEverDay" :key="index" style="margin:3px;">
                <div class="hover-style" style="border-radius:5px;font-weight:bold;font-size:12px;cursor: pointer;" @click="clickCalendar(item, index)">
                  <div>{{ item }}</div>
                  <div v-if="collectClickCalendar.indexOf(index) > -1" style="width:4px;height:4px;border-radius:50%;background-color:red;position: relative;left:calc(50% - 2px);"></div>
                  <div v-else style="width:4px;height:4px;"></div>
                </div>
              </div>
             </div>
          </el-form-item>
          <el-form-item  v-show="datetrue">
            <el-date-picker clearable size="small" style="margin-left: 10px;width: 200px"
                            v-model="pickerTime"
                            type="dates"
                            value-format="yyyy-MM-dd"
                            placeholder="选择提醒时间设置">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item  label="积分比例" prop="integralProportion">
            <el-input-number v-model="form.integralProportion" style="width:130px;" :min="1" placeholder="请输入加倍比例" />
            <span>倍</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="积分轮播图">
        <el-upload
          class="avatar-uploader"
          :action="addressUrl"
          :headers="headers"
          multiple
          list-type="picture-card"
          :limit='5'
          :file-list="form.imgFileList"
          accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp"
          :before-upload="beforeAvatarUpload"
          :on-remove="handleRemove"
          :on-success="handlepaymentSuccess">
          <i class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，最多上传5张且单张图片不超过1M</div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer"> 
      <el-button type="primary" @click="submitForm" :disabled="false" >确 定</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {  addRule, updateRule,oilNameInfo,gradeList,listRuleOne} from "@/api/integral/rule";
import { getDept } from "@/api/system/dept";
import {getStationPay,updatePay} from "@/api/station/pay";
export default {
name: "ruleDetail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 弹出层标题
      title: "",
      uploadUrl:"",
      // stationOptions:[],
      oilNameOptions:[],
      ruleTypeOptions:[],
      termDateManageOptions:[],
      integralActivityOptions:[],
      integralTermSettingOptions:[],
      datePickerOptions:[],
      gradeOptions:[],
      dialogImageUrl: '',
      integralFlagOptions:[],
      ruleForm:{
        imgFileList:[]
      },
      num :0,
      pickerTime:"",
      dialogVisible: false,
      workDaytrue:false,
      moonDaytrue:false,
      datetrue:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        stationName: null,
        ruleType: null,
        oilName: null
      },
      rowsnum:0,
      // 表单参数
      form: {
        itemsDetail: [{}],
        notOilList: [{}],
        imgFileList:[]
      },
      queryRule:{
          stationId: null
        },
      deptId:null,
      deptInfo:{},
      query:{
        deptId: null
      },
      // 表单校验
      rules: {
      },
      headers: { Authorization: "Bearer " + getToken() },
      collectClickCalendar: [], // 收集固定日期选择的日子
      collectClickWorkDay:[],
      moonEverDay: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
      '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
      '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
      workDay:["周天","周一","周二","周三","周四","周五","周六"],
      addressUrl: location.protocol+"//"+location.host+ process.env.VUE_APP_BASE_API+"/common/upload"
    };
  },
  created() {
    this.getDicts("status").then(response => {
      this.integralFlagOptions = response.data;
    });
    this.getDicts("rule_type").then(response => {
      this.ruleTypeOptions = response.data;
    });
    this.getDicts("term_date").then(response => {
      this.termDateManageOptions = response.data;
    });
    
    this.getDicts("integral_manage").then(response => {
      this.integralActivityOptions = response.data;
    });
    this.getDicts("integral_term_setting").then(response => {
      this.integralTermSettingOptions = response.data;
    });
    this.getDicts("date_picker").then(response => {
      this.datePickerOptions = response.data;
    });
    this.deptId=this.$store.selectDeptId;
    if(this.deptId==null || this.deptId==""){
      this.deptId =this.$store.state.user.deptId;
    }
    getDept(this.deptId).then(response => {
        this.deptInfo = response.data;
        if(this.deptInfo.jiBie==2){
          this.form.stationId=this.deptInfo.deptId;
          this.form.stationName=this.deptInfo.deptName;
          this.queryParams.stationId=this.deptInfo.deptId;
          listRuleOne(this.queryParams).then(response => {
            if(response.hasOwnProperty('data')){
              this.form = response.data;
              if(response.data.hasOwnProperty('notOilList')){
                if(this.form.notOilList.length==0){
                   this.form.notOilList=[{}];
                }
              }else{
                  this.form.notOilList=[{}];
              }
              if(response.data.hasOwnProperty('itemsDetail')  ){
                if(this.form.itemsDetail.length==0){
                   this.form.itemsDetail=[{}];
                }else{
                  let itemDetail = this.form.itemsDetail;
                  this.sjfa(itemDetail);
                  this.rowsnum= this.form.itemsDetail.length-1;
                }
              }else{
                this.form.itemsDetail=[{}];
              }
              let datepicker = this.form.datePicker;
              if(datepicker=="1"){
                this.workDaytrue=true;
                if(this.form.datePickerTime!=null){
                  this.collectClickWorkDay= this.form.datePickerTime.split(',').map(parseFloat);
                }
              }else if(datepicker=="2"){
                this.moonDaytrue=true;
                if(this.form.datePickerTime!=null){
                  this.collectClickCalendar= this.form.datePickerTime.split(',').map(parseFloat);
                }
              }else{
                this.datetrue=true;
                if(this.form.datePickerTime!=null){
                  this.pickerTime= this.form.datePickerTime.split(',');
                }else{
                  this.pickerTime=null;
                }
              }
            }
          });
          oilNameInfo(this.queryParams).then(response => {
            this.oilNameOptions = response.rows;
          });
        }else{
            this.msgSuccess("请选择油站");
        }
    });
//查看当前积分设置
    this.queryRule.stationId= this.$store.selectDeptId;
    if(this.queryRule.stationId==null || this.queryRule.stationId==""){
      this.queryRule.stationId =this.$store.state.user.deptId;
    }
    getStationPay(this.queryRule).then(response => {
      this.ruleForm = response.data;
      if(this.ruleForm.integralFlag == ""){
        this.ruleForm.integralFlag ="0";
      }
    });
  },
  methods: {
    async sjfa(itemDetail ){
      for(let j = 0; j < itemDetail.length; j++) {
        this.queryParams.stationId = this.form.stationId;
        this.queryParams.oilName = itemDetail[j].oilName;
        if(itemDetail[j].gread ===""){
            itemDetail[j].gread = "所有人";
        }
        const response = await gradeList(this.queryParams);
        response.rows.push({grade:"所有人"});
        this.gradeOptions.push(response.rows);
      }
    },
    //添加行
    addItem() {
      this.form.itemsDetail.push({
        ruleTerms: '',
        oilName: '',
        gread: '',
        saleAmt: '' ,
        integral: '',
        ruleType: ''
      });
      this.rowsnum=this.form.itemsDetail.length-1;
    },
    // 删除行
    del(index) {
      this.form.itemsDetail.splice(index, 1);
      this.rowsnum=this.form.itemsDetail.length-1;
      if(this.form.itemsDetail.length<=0){
         this.addItem();
      }
    },
    delNoil(){
      this.form.notOilList =[{}];
    },
    queryreset() {
      this.queryParams={
        stationId: null,
        stationName: null,
        oilName: null
      }
    },
    oilNameChang(index){
      let obj = {};
      obj = this.oilNameOptions.find((item)=>{//这里的userList就是上面遍历的数据源
        return item.oilName === this.form.itemsDetail[index].oilName;//筛选出匹配数据
      })
      this.queryreset();
      //获取油站名称
      this.queryParams.stationId = this.form.stationId;
      this.queryParams.oilName=obj.oilName;
      gradeList(this.queryParams).then(response => {
        const temp = [...this.gradeOptions]
        response.rows.push({grade:"所有人"});
        temp[index] = response.rows;
        this.gradeOptions = temp;
      });
    },
   
    handleRemove(file, fileList) {
      if(fileList!=null && fileList.length>0){
        this.form.imgFileList=[];
        for (let i = 0; i < fileList.length; i++) {
          let fileName = fileList[i].name;
          let imgurl = fileList[i].url;
          this.form.imgFileList.push({name:fileName,url:imgurl});
        }
      }else{
         this.form.imgFileList = fileList;
      }
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 1;
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return  isLt5M;
    },
   //上传成功
    handlepaymentSuccess(response,file, fileList){
        let imgurl=location.protocol+"//"+location.host+process.env.VUE_APP_BASE_API+response.fileName;
        this.form.imgFileList.push({name:file.name,url:imgurl});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if(this.form.notOilList!=null&&this.form.notOilList.length==0 ){
            }else{
               if(this.form.notOilList[0].saleAmt==""||this.form.notOilList[0].saleAmt=="0" ||this.form.notOilList[0].saleAmt=="undefined"){
                this.form.notOilList=[{}];
              }
            }
            let datepicker = this.form.datePicker;
            if(datepicker=="1"){
              if(this.collectClickWorkDay!=null&&this.collectClickWorkDay.length>0){
                let discountTime=null;
                for(let i =0;i<this.collectClickWorkDay.length;i++){
                  if(!isNaN(this.collectClickWorkDay[i]) && this.collectClickWorkDay[i]!="NaN"){
                    if( discountTime!=null){
                      discountTime =discountTime+","+this.collectClickWorkDay[i];
                    }else{
                      discountTime =this.collectClickWorkDay[i];
                    }
                  }else{
                    discountTime =discountTime;
                  }
                }
                this.form.datePickerTime=discountTime; 
                discountTime=null;
              }else{
                  this.form.datePickerTime=""; 
              }  
            }else if(datepicker=="2"){
              if(this.collectClickCalendar!=null&&this.collectClickCalendar.length>0){
                let discountTime=null;
                for(let i =0;i<this.collectClickCalendar.length;i++){
                  if(!isNaN(this.collectClickCalendar[i]) && this.collectClickCalendar[i]!="NaN"){
                    if( discountTime!=null){
                      discountTime =discountTime+","+this.collectClickCalendar[i];
                    }else{
                      discountTime =this.collectClickCalendar[i];
                    }
                  }else{
                    discountTime =discountTime;
                  }
                }
                this.form.datePickerTime=discountTime; 
                discountTime=null;
              } else{
                  this.form.datePickerTime=""; 
              }
            }else{
              if(this.pickerTime!=null){
                  this.form.datePickerTime = this.pickerTime.toString();
              }else{
                this.form.datePickerTime = "";
              }
            }
            let itemsDetail =this.form.itemsDetail;
            let flag= true;
            if(itemsDetail!=null&&itemsDetail.length>1){
              for (var i = 0; i < itemsDetail.length; i++) {
                  for (var j = i + 1; j < itemsDetail.length; j++) {
                    if (itemsDetail[i].oilName == itemsDetail[j].oilName) { 
                      if(itemsDetail[i].gread==itemsDetail[j].gread){
                        flag=false;
                        break;
                      }else if(itemsDetail[i].gread!=itemsDetail[j].gread){
                        if(itemsDetail[i].gread=="所有人"){
                          flag=false;
                          break;
                        }else if(itemsDetail[j].gread=="所有人"){
                          flag=false;
                          break;
                        }
                      }
                    }
                  }
                  if (!flag){
                    break;  
                  } 
              }
            }
            if(flag){
              updateRule(this.form).then(response => {
                this.msgSuccess("修改成功");
              });
            }else{
               this.msgSuccess("添加的规则明细有重复的，请再次确实积分规则");
            }
          } else {
            if(this.num===0){
                let datepicker = this.form.datePicker;
              if(datepicker=="1"){
                if(this.collectClickWorkDay!=null&&this.collectClickWorkDay.length>0){
                  let discountTime=null;
                  for(let i =0;i<this.collectClickWorkDay.length;i++){
                    if(!isNaN(this.collectClickWorkDay[i]) && this.collectClickWorkDay[i]!="NaN"){
                      if( discountTime!=null){
                        discountTime =discountTime+","+this.collectClickWorkDay[i];
                      }else{
                        discountTime =this.collectClickWorkDay[i];
                      }
                    }else{
                      discountTime =discountTime;
                    }
                  }
                  this.form.datePickerTime=discountTime; 
                  discountTime=null;
                }else{
                    this.form.datePickerTime=""; 
                }  
              }else if(datepicker=="2"){
                if(this.collectClickCalendar!=null&&this.collectClickCalendar.length>0){
                  let discountTime=null;
                  for(let i =0;i<this.collectClickCalendar.length;i++){
                    if(!isNaN(this.collectClickCalendar[i]) && this.collectClickCalendar[i]!="NaN"){
                      if( discountTime!=null){
                        discountTime =discountTime+","+this.collectClickCalendar[i];
                      }else{
                        discountTime =this.collectClickCalendar[i];
                      }
                    }else{
                      discountTime =discountTime;
                    }
                  }
                  this.form.datePickerTime=discountTime; 
                  discountTime=null;
                } else{
                    this.form.datePickerTime=""; 
                }
              }else{
                if(this.pickerTime!=null){
                    this.form.datePickerTime = this.pickerTime.toString();
                }else{
                  this.form.datePickerTime = "";
                }
              }
              let itemsDetail =this.form.itemsDetail;
              let flag= true;
              //验证积分规则，相同油品，等级为所有人，该油品不能再设置其他等级。相同油品等级不为所有人，可以设置不同等级的规则，不可以设置油品相同等级相同的规则
              if(itemsDetail!=null&&itemsDetail.length>0){
                for (var i = 0; i < itemsDetail.length; i++) {
                    for (var j = i + 1; j < itemsDetail.length; j++) {
                      if (itemsDetail[i].ruleType == itemsDetail[j].ruleType &&itemsDetail[i].oilName == itemsDetail[j].oilName&& itemsDetail[i].gread==itemsDetail[j].gread) { 
                        flag=false;
                        break;
                      }
                    }
                    if (flag) break;
                }
              }
              if(flag){
                addRule(this.form).then(response => {
                  this.msgSuccess("新增成功");
                });
              }else{
                this.msgSuccess("添加的规则明细有重复的，请再次确实积分规则");
              }
              this.num=this.num+1;
            }else{
                this.msgSuccess("已新增成功！如需修改请刷新页面");
            }
          }
        }
      });
      if (this.ruleForm.payId != null) {
        updatePay(this.ruleForm).then(response => {
        });
      }  
    },
  
    deleteItemFromArr(item) {
      // eslint-disable-next-line
      Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] === val) {
            return i
          }
        }
        return -1
      }
      // 通过索引删除数组元素
      Array.prototype.remove = function(val) {
        var index = this.indexOf(val)
        if (index > -1) {
          this.splice(index, 1)
        }
      }
      // 删除数组元素
      this.collectClickCalendar.remove(item)
    },
    clickCalendar(item, index) {
      if (this.collectClickCalendar.indexOf(index) === -1) {
        this.collectClickCalendar.push(index)
      } else if (this.collectClickCalendar.indexOf(index) > -1) {
        this.deleteItemFromArr(index)
      }
    },
    deleteWorkDayFromArr(item) {
      Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] === val) {
            return i
          }
        }
        return -1
      }
      // 通过索引删除数组元素
      Array.prototype.remove = function(val) {
        var index = this.indexOf(val)
        if (index > -1) {
          this.splice(index, 1)
        }
      }
      // 删除数组元素
      this.collectClickWorkDay.remove(item)
    },
    clickWorkDayCalendar(item, index) {
      if (this.collectClickWorkDay.indexOf(index) === -1) {
        this.collectClickWorkDay.push(index)
      } else if (this.collectClickWorkDay.indexOf(index) > -1) {
        this.deleteWorkDayFromArr(index)
      }
    },
    datePickerChang(){
      if(this.form.datePicker == "1"){
        this.workDaytrue=true;
        this.moonDaytrue=false;
        this.datetrue=false;
      }else if(this.form.datePicker == "2"){
        this.workDaytrue=false;
        this.moonDaytrue=true;
        this.datetrue=false;
      }else if(this.form.datePicker == "3"){
        this.workDaytrue=false;
        this.moonDaytrue=false;
        this.datetrue=true;
      }
    }
  },
}
</script>
<style scoped>
.hover-style:hover {
  color: white;
  background-color: blue;
}

</style>