<template>
  <div class="brandActivity" style="width: 1100px">
    <toptitle name="品牌活动" style="border-bottom:none;margin-bottom: 0px">
    </toptitle>
    <el-dialog
      :title="title"
      width="540px"
      :visible.sync="dialogVisible"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="活动类型" prop="status">
          <el-radio-group :disabled="updDisabled" v-model="ruleForm.status" @change="changeStatus">
            <el-radio :label="1" disabled>大型活动</el-radio>
            <el-radio :label="2">日常活动</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动名称" prop="name">
          <el-input :disabled="updDisabled" style="width: 360px" v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="dateRange">
          <el-date-picker
            :disabled="updDisabled"
            style="width: 360px"
            value-format="yyyy-MM-dd"
            v-model="ruleForm.dateRange"
            type="daterange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeData"
          />
          <!--:default-time="['09:00:00', '23:59:59']"-->
        </el-form-item>
        <div class="tip">
          <p>温馨提示：</p>
          <p v-if="ruleForm.status==1">1、大型活动期间，不可设置活动名称及时间</p>
          <p v-if="ruleForm.status==2">1、可创建并设置下周的活动，且活动时长为5天</p>
          <p v-if="ruleForm.status==1">2、大型活动与日常活动不可同时存在</p>
          <p v-if="ruleForm.status==2">2、活动开始后，不可取消活动</p>
          <p v-if="ruleForm.status==1">3、默认品牌方让利5%</p>
          <p v-if="ruleForm.status==2">3、默认参与活动的商品95折</p>
        </div>
      </el-form>
      <div slot="footer" >
        <div v-if="!updDisabled">
          <el-button @click="dialogVisible = false">关 闭</el-button>
          <el-button type="primary" :loading="saveLoading" @click="save(ruleForm)">确 认</el-button>
        </div>
      </div>
    </el-dialog>
    <div style="margin-bottom: 10px">
      <el-collapse accordion>
        <el-collapse-item>
          <template slot="title">
            <div style="color: #ff6600">活动规则（收起/展开）</div>
          </template>
          <div style="font-size: 14px">
            <p>一、品牌活动</p>
            <p>1、品牌专场为品牌方在日常经营中自主发起的活动，每月1次，每次3 天;</p>
            <p>2、品牌专场优惠方式由品牌自己决定;</p>
            <p>3、品牌专场需提前一周报名，总部审核通过后按时开放。</p>
          </div>
          <div  style="font-size: 14px">
            <p>二、大型活动</p>
            <p>1、大型活动由平台发起，平台让利(与品牌结算无关);</p>
            <p>2、品牌可挑选部分商品或选择全店铺商品同步让利(让利商品结算与品牌有关)</p>
            <p>3、品牌同步让利幅度最高 95 折;</p>
            <p>4、大型活动时暂停品牌活动。</p>
            </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div>
      <div class="search-wrap">
        <div class="search-box">
          <div class="search-item">
            <span class="label">活动名称</span>
            <el-input class="input" @keyup.enter.native="onSearch" clearable v-model="params.search"
                      placeholder="请输入活动名称"></el-input>
          </div>
          <div class="search-item">
            <span class="label">活动类型</span>
            <el-select class="input" clearable v-model="params.type" placeholder="请选择活动类型">
              <el-option
                v-for="item in [{value:0,label:'全部'},{value:1,label:'大型活动'},{value:2,label:'日常活动'}]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="search-item">
            <span class="label">活动状态</span>
            <el-select class="input" clearable v-model="params.actStatus" placeholder="请选择活动状态">
              <el-option
                v-for="item in [{value:0,label:'全部'},{value:1,label:'未开始'},{value:2,label:'进行中'},{value:3,label:'已结束'}]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="search-item">
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </div>
          <div class="search-item" style="position: relative;left: 96px">
            <el-button  type="primary" @click="showModel('add')" >发起活动</el-button>
          </div>
        </div>
      </div>
      <el-table
        v-loading="tableLoading"
        ref="multipleTable"
        :data="tableList"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
      >
        <el-table-column prop="date" label="序号" width="80" align="center">
          <template slot-scope="scope">
            <p>{{scope.$index+1}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="skuModel" label="活动名称" align="center">
          <template slot-scope="scope">
            {{scope.row.name}}
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            {{scope.row.typeName}}
          </template>
        </el-table-column>
        <el-table-column label="活动时间" align="center">
          <template slot-scope="scope" v-if="scope.row.actDateStr">
            <p>{{scope.row.actStartDate}} 至</p>
            <p>{{scope.row.actEndDate}}</p>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.actStatus==1" style="color: #ff6600">未开始</div>
            <div v-if="scope.row.actStatus==2" style="color: #00cc33">进行中</div>
            <div v-if="scope.row.actStatus==3">已结束</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            <div>{{scope.row.addDate}}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template slot-scope="scope">
            <div class="edit">
              <span @click="showModel('upd',scope.row)" v-if="scope.row.type!==1">编辑</span>
              <span @click="showModel('see',scope.row)">查看</span>
            </div>
            <div class="edit">
              <span @click="goAct(scope.row)">{{scope.row.actStatus==1?'设置':'查看'}}活动商品</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-box">
        <pagination
          @eventSizeChange="eventSizeChange"
          @eventCurrentChange="eventCurrentChange"
          :total="total"
          :pageSize="params.pageSize"
          :currentPage="params.pageNum"
          :pagerCount='5'
        ></pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {_formatDate,_getStorage} from '@/utils/utils'
  import pagination from "@/components/common/pagination";
  import toptitle from "@/components/common/topTitle";

  export default {
    components: {
      pagination,
      toptitle,
    },
    name: "index",
    data() {
      return {
        startRow:null,
        title: "新建活动",
        updDisabled: false,
        ruleForm: { status: "1", dateRange: [], name: "" },
        rules: {
          name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
          status: [{ required: true, message: "请选择活动类型", trigger: "change" }],
          dateRange: [{ required: true, message: "请选择日期", trigger: "change" }],
        },
        pickerOptions: {
          disabledDate: (time) => {
            const today = new Date();
            const day = today.getDay();
            const nextMonday = new Date(today);
            nextMonday.setDate(today.getDate() + (7 - day));
            if(this.allowCustomActDate==1){
              return time.getTime() < nextMonday.getTime()
            }
            const nextSunday = new Date(nextMonday);
            nextSunday.setDate(nextMonday.getDate() + 7);
            return time.getTime() < nextMonday.getTime() || time.getTime() > nextSunday.getTime();
          },
        },
        dialogVisible: false,
        tableList: [],
        params: {
          search: "",
          pageSize: 20,
          pageNum: 1,
          type: 0,
          actStatus: 0,
        },
        total: 0,
        tableLoading: false,
        saveLoading: false,
        allowCustomActDate:null,
      };
    },
    mounted() {
      this.getAutonomList();
      this.priceformulaId = _getStorage('priceformulaId')
      this.allowCustomActDate = _getStorage('allowCustomActDate')
    },
    filters: {
      formatDate(time) {
        var date = new Date(time);
        return _formatDate(date, 'yyyy-MM-dd');
      },
    },
    methods: {
      changeStatus(e){
        if(e==2){
          this.ruleForm.name=this.formattedDate()
        }else {
          this.ruleForm.name=''
        }
      },
      getAutonomList() {
        this.tableLoading = true;
        this.$axios.post("/actregist/autonom/list", this.params).then(res => {
          let { code, data,status } = res.data;
          if (code === 200) {
            this.startRow=status
            this.total = Number(data.total);
            this.tableList = data.list;
          } else {
            this.total = 0;
            this.tableList = [];
          }
        });
        this.tableLoading = false;
      },
      goAct(data) {
        sessionStorage.setItem('setActiveShop',JSON.stringify(data))
        this.$router.push("/marketing/activityMall-act");
      },
      // 转2023格式
      formattedDate() {
        const date = new Date();
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const formattedDate = `${year}${month}${day}日常活动`;
        return formattedDate;
      },
      showModel(type,data) {
        if (type == "add") {
          // if(this.startRow==0){
          //   this.$message.warning('本月已发起过活动，下个月再发起吧！')
          //   return
          // }
          this.ruleForm = {
            status: 2,
            dateRange: [],
            name:this.formattedDate(),
          };
          this.updDisabled=false
          this.title = "新建活动";
        } else if (type == "upd") {
          // const regex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})-(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/;
          // const [match,startStr, endStr] = dateStr.match(regex);
          // const startDate = new Date(startStr);
          // const endDate = new Date(endStr);
          this.ruleForm = {
            status: 2,
            dateRange: [data.actStartDate,data.actEndDate],
            name: data.name,
            actId:data.actId
          };
          this.title = "编辑活动";
          this.updDisabled=false
        } else if (type == "see") {
          this.ruleForm = {
            status: data.type,
            dateRange: [data.actStartDate,data.actEndDate],
            name: data.name,
          };
          this.updDisabled=true
          this.title = "查看活动";
        }
        if (!!this.$refs["ruleForm"]) {
          this.$refs["ruleForm"].resetFields();
        }
        this.dialogVisible = true;
      },
      save(data) {
        let format = this.$options.filters['formatDate']
        this.saveLoading=true
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            let params = {
              name: data.name,
              startActDate: format(data.dateRange[0]),
              endActDate: format(data.dateRange[1]),
            };
            if(data.actId){
              params.actId=data.actId
            }
            let url =`/actregist/autonom/${data.actId?'edit':'add'}`
            this.$axios.post(url, params).then(res => {
              let { code, msg, message } = res.data;
              if (code === 200) {
                this.dialogVisible=false
                this.saveLoading=false
                this.$message.success(msg || message)
                this.getAutonomList();
              } else {
                this.saveLoading=false
                this.$message.error(msg || message);
              }
            });
          } else {
            this.saveLoading=false
            return false;
          }
        });
      },
      changeData() {
        let format = this.$options.filters['formatDate']
        let dateRange = this.ruleForm.dateRange;
        if (dateRange && dateRange.length > 0) {
          const startTimestamp = new Date(format(dateRange[0])).getTime();
          const endTimestamp = new Date(format(dateRange[1])).getTime();
          const dayDiff = (endTimestamp - startTimestamp) / (1000 * 60 * 60 * 24);
          if(this.allowCustomActDate!=1){
            if (dayDiff > 4) {
              this.$message({
                type: "error",
                message: "日期范围不能超过 5 天",
              });
              this.ruleForm.dateRange = [];
            }
          }
        }
      },
      onReset() {
        this.params = {
          pageSize: 20,
          pageNum: 1,
          search: "",
          type: 0,
          actStatus:0
        };
        this.getAutonomList();
      },
      onSearch() {
        this.params.pageNum = 1;
        this.getAutonomList();
      },
      eventSizeChange(e) {
        this.params.pageSize = e;
        this.getAutonomList();
      },
      eventCurrentChange(e) {
        this.params.pageNum = e;
        this.getAutonomList();
      },
    },
  };
</script>

<style lang="scss" scoped>
  .brandActivity {
    padding: 20px;
    /deep/ .el-dialog__body {
      padding: 16px 20px;
    }
    .tip {
      margin-left: 35px;
      line-height: 20px;
      color: #999999;
    }
    .guize {
      background: #f2f2f2;
      width: 100%;
      height: 60px;
      line-height: 20px;
      margin-bottom: 15px;
      .text {
        padding: 10px 15px;
      }
    }
    .search-wrap {
      .search-box {
        overflow: hidden;
        flex-wrap: wrap;
        display: flex;
        transition: max-height 0.15s ease-in-out;
        .search-item {
          margin-right: 15px;
          margin-bottom: 15px;
          .label {
            display: inline-block;
            width: 62px;
            text-align: right;
            font-size: 14px;
          }
          .input {
            width: 180px;
          }
        }
      }
      .search-btn-box {
        margin-bottom: 10px;

        display: flex;
        align-items: center;
        .icon-arrow {
          margin-left: 4px;
          transition: transform 0.25s ease-in-out;
        }
        .more {
          color: #ff6600;
          margin-left: 10px;
          cursor: pointer;
          line-height: 33px;
        }
      }
    }
    .edit {
      color: #0785dd;
      span {
        cursor: pointer;
        margin: 0 4px;
      }
    }
  }
</style>
