<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: gcz
 * @LastEditTime: 2024-03-15 15:37:32
 * @FilePath: \great_webui\src\views\marketing\activity\dialog\addAndEdit.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="1200px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="form" ref="form" :rules="rules" label-width="120px">
        <el-form-item label="活动名称" prop="activityName" required>
          <el-input
            v-model="form.activityName"
            placeholder="活动名称"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityDate" required>
          <el-date-picker
            @change="dateChange"
            v-model="form.activityDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="优惠劵总数" prop="couponNum" required>
          <el-input
            v-model="form.couponNum"
            @change="changeNumber('couponNum')"
            placeholder="优惠劵总数"
            clearable
            style="width: 100%;"
          />
        </el-form-item> -->
        <el-form-item label="优惠劵" prop="couponList" required>
          <!-- <el-input
            v-model="form.couponList"
            placeholder="优惠劵"
            clearable
            style="width: 100%;"
            v-show="false"
          /> -->
          <span style="color: deepskyblue;cursor: pointer;" @click="showSelectTable = true">选择</span>
        </el-form-item>
      </el-form>
      <div class="select-table">
          <el-table
            :data="tempCouponList"
            border
            style="width: 100%;"
          >
            <el-table-column prop="couponBatch" label="批次号" width="140" />
            <el-table-column prop="couponName" label="优惠劵名称" />
            <el-table-column label="类型" align="center" prop="type">
              <template slot-scope="scope">
                <span>{{ scope.row.type==1?'满减':'折扣' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="num" width="250">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.num" controls-position="right"></el-input-number>
                </template>
              </el-table-column>
        </el-table>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading.fullscreen.lock="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
    <el-dialog title="选择优惠券" :visible.sync="showSelectTable" width="1000px" append-to-body>
      <div class="dialog select-table">
          <div class="table-title"></div>
            <el-table
              :data="couponList"
              border
              style="width: 100%;margin-bottom: 20px;"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="couponBatch" label="批次号" width="140" />
              <el-table-column prop="couponName" label="优惠劵名称" />
              <el-table-column label="类型" align="center" prop="type">
                <template slot-scope="scope">
                  <span>{{ scope.row.type==1?'满减':'折扣' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer" style="float: right;">
              <el-button @click="showSelectTable=false">取消</el-button>
              <el-button
                type="primary"
                @click="confirmSelection(true)"
                element-loading-text="提交中..."
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
              >
                <span>确定</span>
              </el-button>
            </span>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
// import { updateNoticeMgr } from "@/api/system/noticeMgr";
import { saveAndEdit } from "@/api/activity/activity";
import { unBoundList as couponPageList } from '@/api/coupon/coupon'
// import { getToken } from "@/utils/auth";
// import { log } from 'mathjs';
export default {
  name: "addAndEdit",
  props: {
    dict: {
      type: Object,
      default: () => [],
    },
  },
  components: {
    
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      open: false,
      loading: false,
      form: {
        id: undefined,
      },
      rules: {
        activityName: [{ required: true, message: "请输入活动名称", trigger: ["change","blur"] }],
        activityDate: [{ required: true, message: "开始时间", trigger: ["change","blur"] }],
        startDate: [{ required: true, message: "开始时间", trigger: ["change","blur"] }],
        endDate: [{ required: true, message: "结束时间", trigger: ["change","blur"] }],
        couponNum: [{ required: true, message: "请输入优惠劵总数(大于或等于1的整数)", trigger: ["change","blur"] }],
        couponList: [
          { required: true, message: "请选择优惠劵", trigger: ["change","blur"] },
        ],
      },
      tempCouponList:[],
      couponList:[],
      showSelectTable:false,
    };
  },
  created(){
    
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    async openDialog(title, obj) {
      this.open = true;
      this.reset();
      await this.getCouponList();
      if (obj){
        this.title = "编辑活动";
        this.$nextTick(() => {
          this.$set(this.form, 'id', obj.id);
          this.$set(this.form, 'activityName', obj.activityName);
          this.$set(this.form, 'startDate', obj.startDate);
          this.$set(this.form, 'endDate', obj.endDate);
          this.$set(this.form, 'couponNum', obj.couponNum);
          this.$set(this.form, 'couponList', obj.couponList);
          this.$set(this.form, 'activityDate', [obj.startDate, obj.endDate]);
          this.$set(this, 'tempCouponList', obj.couponInfoList||[]);
          this.confirmSelection();
        });
      }else{
        this.title = "新增活动";
        this.reset()
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
     reset() {
      this.$set(this.form, 'id', '');
      this.$set(this.form, 'activityName', '');
      this.$set(this.form, 'startDate', '');
      this.$set(this.form, 'endDate', '');
      this.$set(this.form, 'couponNum', '');
      this.$set(this.form, 'couponList', []);
      this.$set(this.form, 'activityDate', []);
      this.$set(this, 'tempCouponList', []);
    },
    changeNumber(key) {
      if(!Number.isInteger(this.form[key] * 1) || this.form[key] * 1 < 1){
        this.$message.error("输入需大于或等于1的整数!");
        this.$set(this.form, key, '');
        return false
      }
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            let params = JSON.parse(JSON.stringify(this.form))
            let flog = false
            this.tempCouponList.forEach((item,index)=>{
              if(!item.num && item.num != 0) {
                flog = true
              }
            })
            if(flog) {
              this.$message.error("请输入优惠卷的数量!");
              return
            }
            params.couponList = this.tempCouponList.map(item=>{return {
              couponId: item.id,
              num: item.num
            }});
            this.loading = true;
            const { code } = await saveAndEdit({ ...params });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.form, 'mainImg', res?.data?.url)
      }
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
    /** 查询优惠券列表 */
    async getCouponList() {
      let response = await couponPageList({pageNum:1,pageSize:999})
      this.couponList = response.data.rows;
    },
    dateChange(e){
      console.log('useStartDateChange',e);
      // console.log('useStartDate',this.form.useDate);
      this.form.startDate  = e[0];
      this.form.endDate = e[1];
      console.log(' this.form.activityDate', this.form.activityDate);
    },
    handleSelectionChange(val) {
      // console.log('val', val);
      this.tempCouponList = val;
    },
    confirmSelection(init) {
      this.showSelectTable = false;
      console.log('this.tempCouponList', this.tempCouponList);
      this.form.couponList = this.tempCouponList.map(item=>{return {
        couponId: item.id,
        num: item.num
      }});
    }
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
.dialog {
  padding: 0 30px;
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
</style>
