<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="油站名称" prop="stationId" >
        <el-select
          v-model="form.stationId"
          placeholder="请选择油站"
          clearable
          size="small"
          @change="onInstitutionChang"
        >
          <el-option
            v-for="item in stationOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="false" label="油站名称" prop="stationName">
        <el-input v-model="form.stationName"  placeholder="请输入油站名称" />
      </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=='1'">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"
                  :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>元</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
                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-form>
        </el-row>
      </div>
      <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"
                        placeholder="选择清空积分时间">
        </el-date-picker>
        <span>清空积分</span>
      </el-form-item>
      <el-form-item label=  "到期提醒设置" prop="expirationReminder">
        <el-radio-group v-model="form.expirationReminder">
          <el-radio
            v-for="dict in expirationOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
        <el-date-picker clearable size="small" style="margin-left: 10px;width: 200px"
                        v-model="form.remindDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择提醒时间设置">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="积分活动设置" ></el-form-item>
      <el-form-item >
        <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="margin-left: 80px;">
          <el-form-item  label="日期选择" prop="datePicker">
            <el-date-picker clearable size="small" style="margin-left: 10px;width: 200px"
                            v-model="form.datePicker"
                            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" :min="1" placeholder="请输入加倍比例" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="抵扣油品规则" prop="integralDeductionOil">
        <el-radio-group v-model="form.integralDeductionOil">
          <el-radio
            v-for="dict in integralDeductionOilOptions"
            :key="dict.dictValue"
            :label="dict.dictValue"
          >{{dict.dictLabel}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <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">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {getGun, stationinfo} from "@/api/station/gun";
import {  addRule, updateRule,oilNameList,gradeList,getRule } from "@/api/integral/rule";
export default {
name: "ruleDetail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 弹出层标题
      title: "",
      uploadUrl:"",
      stationOptions:[],
      oilNameOptions:[],
      ruleTypeOptions:[],
      termDateManageOptions:[],
      expirationOptions:[],
      integralDeductionOilOptions:[],
      integralActivityOptions:[],
      gradeOptions:[],
      imgInfoList: [], //包含图片的id,name,size的集合
      imgNameList: [], //后端返回的上传图片的name集合，传到后端
      imgSize: [], //后端返回的上传图片的imgSize集合，传到后端
      deleteImgFileList: [], //存已被删除了的图片的id
      dialogImageUrl: '',
      dialogVisible: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        stationName: null,
        ruleType: null,
        oilName: null
      },
      // 表单参数
      form: {
        itemsDetail: [{}],
        notOilList: [{}],
        imgFileList:[]
      },
      // 表单校验
      rules: {
      },
      headers: { Authorization: "Bearer " + getToken() },
      addressUrl: location.protocol+"//"+location.host+ process.env.VUE_APP_BASE_API+"/common/upload"
    };
  },
  created() {
    //判断是否是做修改
    if(this.$route.query.stationId!=null && this.$route.query.stationId!="" && this.$route.query.parentId !=null &&this.$route.query.parentId !=""){
      this.queryParams.stationId=this.$route.query.stationId;
      let id=this.$route.query.parentId;
      if(id!=null && id != ""){
        getRule(id).then(response => {
          this.form = response.data;
          if(this.form.notOilList.length==0 ){
            this.form.notOilList=[{}];
          }
          if(this.form.itemsDetail.length==0 ){
            this.form.itemsDetail=[{}];
          }
        });
        oilNameList(this.queryParams).then(response => {
          this.oilNameOptions = response.rows;
        });
      }
    }
    stationinfo().then(response => {
      this.stationOptions = response.rows;
    });
    this.getDicts("rule_type").then(response => {
      this.ruleTypeOptions = response.data;
    });
    this.getDicts("term_date").then(response => {
      this.termDateManageOptions = response.data;
    });
    this.getDicts("expiration").then(response => {
      this.expirationOptions = response.data;
    });
    this.getDicts("integral_deduction_oil").then(response => {
      this.integralDeductionOilOptions = response.data;
    });
    this.getDicts("integral_manage").then(response => {
      this.integralActivityOptions = response.data;
    });
  },
  methods: {
    //添加行
    addItem() {
      this.form.itemsDetail.push({
        ruleTerms: '',
        oilName: '',
        gread: '',
        saleAmt: '' ,
        integral: '',
        ruleType: ''
      });
    },
    // 删除行
    del(index) {
      this.form.itemsDetail.splice(index, 1);
    },
    queryreset() {
      this.queryParams={
        stationId: null,
        stationName: null,
        oilName: null
      }
    },
    changeGread(e){
      //获取等级名称和id
      console.log(e);
    },
    onInstitutionChang(){
      let obj = {};
      obj = this.stationOptions.find((item)=>{//这里的userList就是上面遍历的数据源
        return item.deptId === this.form.stationId;//筛选出匹配数据
      })
      this.queryreset();
      this.form.stationName=obj.deptName;
      this.queryParams.stationId=obj.deptId;
      oilNameList(this.queryParams).then(response => {
        this.oilNameOptions = response.rows;
      });
    },
    oilNameChang(e){
      let obj = {};
      console.log("oilNameOptions:",this.oilNameOptions);
        console.log("e:",this.form.itemsDetail[e].oilName);
      obj = this.oilNameOptions.find((item)=>{//这里的userList就是上面遍历的数据源
        return item.oilName === this.form.itemsDetail[e].oilName;//筛选出匹配数据
      })
      this.queryreset();
      //获取油站名称
      this.queryParams.stationId = this.form.stationId;
      this.queryParams.oilName=obj.oilName;
      console.log("stationId", this.form.stationId);
      console.log("oilname",obj.oilName);
      gradeList(this.queryParams).then(response => {
        this.gradeOptions = response.rows;
          console.log("gradeOptions", this.gradeOptions );
      });
    },

    handlePictureCardPreview(file) {
      console.log("file",file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    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 isType = file.type === 'image/jpeg' || 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 1;
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return isType && 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.datePicker != null){
              this.form.datePicker =this.form.datePicker.toString();
            }
            if(this.form.notOilList!=null&&this.form.notOilList.length>0||this.form.notOilList[0].hasOwnProperty(saleAmt)){
                if(this.form.notOilList[0].saleAmt==""||this.form.notOilList[0].saleAmt=="0" ||this.form.notOilList[0].saleAmt=="undefined"){
                  this.form.notOilList=[];
                }
            }
            updateRule(this.form).then(response => {
              this.msgSuccess("修改成功");
            });
          } else {
            if(this.form.datePicker != null){
              this.form.datePicker =this.form.datePicker.toString();
            }
            if(this.form.notOilList!=null&&this.form.notOilList.length>0||this.form.notOilList[0].hasOwnProperty(saleAmt)){
                if(this.form.notOilList[0].saleAmt==""||this.form.notOilList[0].saleAmt=="0" ||this.form.notOilList[0].saleAmt=="undefined"){
                  this.form.notOilList=[];
                }
            }
            addRule(this.form).then(response => {
              this.msgSuccess("新增成功");
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.queryreset();
    }
  },
}
</script>


