<template>
  <div class="app-container">
    <el-form :model="queryParams" size="small" ref="queryForm" :rules="rules" :disabled="showViewTime" label-width="100px" class="demo-ruleForm">
      <el-form-item :label="$t('编号')" v-if="titleShow" prop="ruleNumber">
        <el-input v-model="queryParams.ruleNumber" :disabled="true" style="width: 30%;" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('状态')" v-if="titleShow" prop="status">
        <dict-selector clearable :disabled="true" :type="DICT_TYPE.ENABLE_STATUS" v-model="queryParams.status" formatter="number"> </dict-selector>
      </el-form-item>
      <el-form-item :label="$t('名称')" prop="name">
        <el-input v-model="queryParams.name" style="width: 50%;" clearable @blur="trimParams('name')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('等级')" prop="level">
        <dict-selector clearable :disabled="showViewTime" :type="DICT_TYPE.MEMBERSHIP_LEVELS" v-model="queryParams.level"> </dict-selector>
      </el-form-item>
      <el-form-item :label="$t('积分范围')">
        <el-col :span="6">
          <el-form-item prop="lowerCount">
            <el-input v-model="queryParams.lowerCount"  onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">{{ $t("至") }}</el-col>
        <el-col :span="6">
          <el-form-item prop="upperCount">
            <el-input v-model="queryParams.upperCount" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('等级有效期')" style="width: 30%;" prop="validityPeriod">
        <el-input v-model="queryParams.validityPeriod" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')">
          <span slot="append">{{ $t('天') }}</span>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('积分累计周期')" style="width: 30%;" prop="accumulationPeriod">
        <el-input v-model.number="queryParams.accumulationPeriod" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')">
          <span slot="append">{{ $t('天') }}</span>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('积分累计开始日期')" style="width: 30%;" prop="startDate">
        <el-date-picker type="date" :placeholder="$t('请选择日期')" v-model="queryParams.startDate" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('启用日期')" style="width: 30%;" v-if="titleShow" prop="enableDate">
        <el-date-picker type="datetime" :disabled="true" :placeholder="$t('请选择日期')" v-model="queryParams.enableDate" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('等级有效期')+'-'+$t('开始日期')" style="width: 30%;" prop="startTime">
        <el-date-picker type="date" :placeholder="$t('请选择日期')" v-model="queryParams.startTime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('等级有效期')+'-'+$t('结束日期')" style="width: 30%;" prop="endTime">
        <el-date-picker type="date" :placeholder="$t('请选择日期')" v-model="queryParams.endTime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('选择图标')" prop="icon">
        <image-upload v-model="queryParams.icon" :fileType="['png', 'jpg', 'jpeg']" :limit="1" />
      </el-form-item>
      <el-form-item :label="$t('等级说明')" style="width: 30%;" prop="description">
        <el-input type="textarea" autosize :autosize="{ minRows: 2, maxRows: 4}" v-model="queryParams.description" @blur="trimParams('description')"></el-input>
        <span style="color: red;">{{$t('注：用于客户积分日志显示，请规范填写')}}</span>
      </el-form-item>
      <el-form-item :label="$t('匹配顺序')" style="width: 30%;" prop="sort">
        <el-input v-model.number="queryParams.sort" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"></el-input>
        <span style="color: red;">{{$t('注：设置相同等级，匹配的优先级')}}</span>
      </el-form-item>
      <!-- 编辑相关内容 -->
      <div v-if="showViewTime">
        <el-form-item :label="$t('创建人')">
          <el-input v-model.number="queryParams.creator" style="width: 26%;" :placeholder="$t('请输入创建人')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
        </el-form-item>
        <el-form-item :label="$t('创建时间')">
          <el-date-picker type="datetime" :placeholder="$t('选择创建时间')" v-model="queryParams.createTime" value-format="yyyy-MM-dd HH:mm:ss" placement="bottom-start"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('最后更新人')" style="width: 30%;">
          <el-input v-model.number="queryParams.updater" :placeholder="$t('请输入最后更新人')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
        </el-form-item>
        <el-form-item :label="$t('最后更新时间')">
          <el-date-picker type="datetime" :placeholder="$t('选择最后更新时间')" v-model="queryParams.updateTime" value-format="yyyy-MM-dd HH:mm:ss" placement="bottom-start"></el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <el-row justify="end" :gutter="20" type="flex">
      <el-col :span="3" v-if="$route.query.pageStatus == 'new'">
        <el-button type="primary" @click="handleSaveIntegralRule" style="width: 100%">{{ $t("保存") }}</el-button>
      </el-col>
      <el-col :span="3" v-if="$route.query.pageStatus == 'new'">
        <el-button type="primary" style="width: 100%" @click="handleEnableIntegralRule">{{ $t("保存并启用") }}</el-button>
      </el-col>
      <el-col :span="3" v-if="$route.query.pageStatus == 'edit'">
        <el-button type="primary" style="width: 100%" @click="handleUpdatedMemberLevel">{{ $t("更新") }}</el-button>
      </el-col>
      <el-col :span="3">
        <el-button v-if="$route.query.pageStatus != 'view'" type="primary" style="width: 100%" @click="handleResetMemberLevel">{{ $t("重置") }}</el-button>
      </el-col>
      <el-col :span="3">
        <el-button style="width: 100%" type="primary" @click="handleGoBack">{{ $t("返回") }}</el-button>
      </el-col>
    </el-row>
    <!-- table Tab -->
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" v-if='$route.query.pageStatus == "view"'>
      <el-menu-item index="reward">{{ $t("操作日志") }}</el-menu-item>
    </el-menu>
    <div class="table-container" v-if='$route.query.pageStatus == "view"'>
      <div class="reward" v-show="activeIndex == 'reward'">
        <el-table :data="logs" v-loading="logsLoading">

          <el-table-column :label="$t('环节')">
            <template slot-scope="{ row }">{{ row.operateType == 1 ? $t("新增") : $t("修改") }}</template>
          </el-table-column>
          <el-table-column :label="$t('操作人')" prop="operator"> </el-table-column>

          <el-table-column :label="$t('操作时间')">
            <template slot-scope="{ row }">{{ row.createTime | parseTime }}</template>
          </el-table-column>
          <el-table-column :label="$t('备注')" prop="remarks"></el-table-column>
          <el-table-column :label="$t('审批流程')" prop="bpmProcessId" width="150"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { getDictDatas, DICT_TYPE } from "@/utils/dict"
import imageUpload from "@/components/ImageUpload/index.vue"
import {editMemberLevel, memberLevelConfigDetails, addNewMemberLevel, operateLogPage} from "@/api/ecw/memberManagement"
import { parseTime } from "@/utils/ruoyi"
import { deepClone, titleCase } from "@/utils"
export default {
  name: "operatingLevel",
  components: {
    imageUpload
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    },
  },
  watch: {
    rewardsDetails(newVal, oldVal) {
      if (JSON.stringify(newVal) != "{}") {
        this.queryParams = deepClone(newVal)
        this.queryParams.pickMethod = newVal.pickMethod.split(",")
        this.$nextTick(() => {
          this.$refs["queryForm"].clearValidate()
        })
      } else {
        this.resetFormQuery()
        this.$nextTick(() => {
          this.$refs["queryForm"].resetFields()
          this.$refs["queryForm"].clearValidate()
        })

        console.log("Prop is empty")
      }
    }
  },
  filters: {
    parseTime
  },
  data() {
    return {
      loading: false,
      showViewTime:false,
      titleShow:true,
      activeIndex: "reward",
      logs: [], // 操作日志
      logsLoading: false, // 日志加载中
      queryParams: {
        ruleNumber: null,
        status: null,
        level: null,
        icon: null,
        lowerCount: null,
        name: null,
        upperCount: null,
        validityPeriod: null,
        accumulationPeriod: null,
        startDate: null,
        startTime: null,
        endTime: null,
        enableDate: null,
        description: null,
        sort: null,
        dateRangeCreateTime: []
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t("必填，限制50字符"),
            trigger: "blur",
            max: 50
          }
        ],
        level: [
          {
            required: true,
            message: this.$t("请输入等级"),
            trigger: "blur"
          }
        ],
        lowerCount: [
          {
            required: true,
            validator: this.validatePositiveInteger2,
            trigger: "blur"
          }
        ],
        upperCount: [
          {
            required: true,
            validator: this.validatePositiveInteger2,
            trigger: "blur"
          }
        ],
        validityPeriod: [
          {
            required: true,
            validator: this.validatePositiveInteger,
            trigger: "blur"
          }
        ],
        accumulationPeriod : [
          {
            required: true,
            validator: this.validatePositiveInteger,
            trigger: "blur"
          },
          {
            type: "number",
            message: this.$t("请输入整数"),
            trigger: "blur"
          }
        ],
        sort : [
          {
            required: true,
            message: this.$t("请输入匹配顺序"),
            trigger: "blur"
          },
          {
            type: "number",
            message: this.$t("请输入整数"),
            trigger: "blur"
          }
        ],
        startTime : [
          {
            required: true,
            message: this.$t("请输入积分开始累计时间"),
            trigger: "blur"
          }
        ],
        description : [
          {
            required: true,
            message: this.$t("必填，限制200字符"),
            trigger: "blur",
            max: 200
          }
        ]
      }
    }
  },
  created() {
    if (this.$route.query.pageStatus == "edit") {
      this.handleMemberLevelDetails()
    } else if (this.$route.query.pageStatus == "view") {
      this.showViewTime = true
      this.handleMemberLevelDetails()
    } else {
      this.titleShow=false;
      if (this.$route.query.params!=null){
        this.queryParams=this.$route.query.params
        this.queryParams.id = null;
        this.queryParams.startDate=parseTime(this.queryParams.startDate)
        this.queryParams.startTime=parseTime(this.queryParams.startTime)
        this.queryParams.endTime=parseTime(this.queryParams.endTime)
        this.queryParams.enableDate=parseTime(this.queryParams.enableDate)
      }
    }
  },
  methods: {
    trimParams(val) {
      this.queryParams[val] = this.queryParams[val].trim();
    },
    validatePositiveInteger(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t("请输入整数")));
      } else {
        const regex = /^[1-9]\d*$/;
        if (regex.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("请输入整数")));
        }
      }
    },
    validatePositiveInteger2(rule, value, callback) {
        const regex = /^(?:0|[1-9]\d*)$/;
        if (regex.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("请输入整数")));
        }

    },
    validatePositiveIntegerorNull(rule, value, callback) {
      if (value === ''||value === null) {
        callback();
      } else {
        const regex = /^[1-9]\d*$/;
        if (regex.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("请输入整数")));
        }
      }
    },
    handleMemberLevelDetails(){
      memberLevelConfigDetails({ id: this.$route.query.id }).then(response => {
        this.queryParams = response.data
        this.queryParams.startDate=parseTime(response.data.startDate)
        this.queryParams.startTime=parseTime(response.data.startTime)
        this.queryParams.endTime=parseTime(response.data.endTime)
        this.queryParams.enableDate=parseTime(response.data.enableDate)
        this.queryParams.createTime = parseTime(response.data.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
        this.queryParams.updateTime = parseTime(response.data.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
        this.loadLogs()
      })
    },
    //保存
    handleSaveIntegralRule(){
      var now = new Date();
      var nowMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      var specificDate = new Date(this.queryParams.startTime);
      var endDate = new Date(this.queryParams.endTime);
      if(specificDate<nowMidnight) {
        this.$modal.msgWarning(this.$t('开始日期不能早于今天'))
        return false
      }
      if(this.queryParams.endTime!=null&&specificDate>endDate) {
        this.$modal.msgWarning(this.$t('开始日期不能大于结束时间'))
        return false
      }
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams)
          params.status = null
          params.enableDate = null
          params.ruleNumber = null
          addNewMemberLevel(params).then((res) => {
            this.$message.success(this.$t("保存成功"))
            this.$router.go(-1)
          })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    //保存并启用
    handleEnableIntegralRule(){
      var now = new Date();
      var nowMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      var specificDate = new Date(this.queryParams.startTime);
      var endDate = new Date(this.queryParams.endTime);
      if(specificDate<nowMidnight) {
        this.$modal.msgWarning(this.$t('开始日期不能早于今天'))
        return false
      }
      if(this.queryParams.endTime!=null&&specificDate>endDate) {
        this.$modal.msgWarning(this.$t('开始日期不能大于结束时间'))
        return false
      }
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams)
          params.status = "1"
          params.ruleNumber = null
          addNewMemberLevel(params).then((res) => {
            this.$message.success(this.$t("保存成功"))
            this.$router.go(-1)
          })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    //编辑更新等级规则
    handleUpdatedMemberLevel(){
      var now = new Date();
      var nowMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      var specificDate = new Date(this.queryParams.startTime);
      if(specificDate<nowMidnight) {
        this.$modal.msgWarning(this.$t('开始日期不能早于今天'))
        return false
      }
      if(this.queryParams.startTime>this.queryParams.endTime) {
        this.$modal.msgWarning(this.$t('开始日期不能大于结束时间'))
        return false
      }
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams)
          editMemberLevel(params).then((res) => {
            this.$message.success(this.$t("更新成功"))
            this.$router.go(-1)
          })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    //返回按钮操作
    handleGoBack() {
      this.$modal
        .confirm(this.$t("确认返回吗?"), this.$t("提示"))
        .then(() => {
          // this.$router.go(-1);
          this.$store.dispatch("tagsView/delCurrentView")
          this.$modal.msgSuccess(this.$t("成功"))
        })
        .catch(() => {})
    },
    //重置按钮操作
    handleResetMemberLevel() {
      console.log("handleResetMemberLevel")
      this.$modal
        .confirm(this.$t("是否确认重置此会员等级规则表单"), this.$t("提示"))
        .then(() => {
          this.$refs["queryForm"].resetFields()
          this.queryParams= {
            ruleNumber: null,
              status: null,
              level: null,
              icon: null,
              lowerCount: null,
              name: null,
              upperCount: null,
              validityPeriod: null,
              accumulationPeriod: null,
              startDate: null,
              startTime: null,
              endTime: null,
              enableDate: null,
              description: null,
              sort: null,
              dateRangeCreateTime: []
          }
          this.$modal.msgSuccess(this.$t("操作成功"))
        })
        .catch(() => {})
    },
    // 加载操作日志
    loadLogs() {
      this.logsLoading = true
      let params = {};
      params.page=1;
      params.rows=10000;
      params.configId=this.queryParams.id;
      operateLogPage(params)
        .then((res) => {
          this.logs = res.data.list
        })
        .finally(() => {
          this.logsLoading = false
        })
    },
  }
}
</script>
<style>
.input-item-width {
  width: 194px;
}
.giftNum .input-item-width {
  width: auto;
}
.line{
  text-align: center;
}
</style>
