<template>
  <div class="container">
    <!-- 填写信息 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-form ref="form" :model="form" :rules="rules" label-width="auto" class="form" size="medium">
          <el-form-item label="优惠券名称" prop="couponName">
            <el-input v-model.trim="form.couponName" placeholder="优惠券名称"></el-input>
          </el-form-item>
          <el-form-item label="优惠券数量" prop="couponNumber">
            <el-input-number v-model="form.couponNumber" :min="1" :precision="0" label="优惠券数量" style="width:100%" @blur="handleCalculate"></el-input-number>
          </el-form-item>
          <el-form-item label="优惠方式" prop="couponType">
            <el-radio-group v-model="form.couponType" @change="handleChange($event===0?['fullKimsMoney']:$event===1?['fullDiscountMoney']:false)">
              <el-radio v-model="form.couponType" :label="0">代金券</el-radio>
              <el-radio v-model="form.couponType" :label="1">折扣券</el-radio>
              <el-radio v-model="form.couponType" :label="2">代扣券</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="fullKimsMoney" v-if="form.couponType===0">
            <el-input-number class="hideBtn" v-model="form.fullKimsMoney" :min="1" :precision="0" placeholder="抵扣金额"></el-input-number>
          </el-form-item>
          <el-form-item prop="fullDiscountMoney" v-if="form.couponType===1">
            <el-input-number class="hideBtn" v-model="form.fullDiscountMoney" :min="1" :max="100" :precision="0" placeholder="折扣(%)"></el-input-number>
          </el-form-item>
          <el-form-item label="优惠限制" prop="serviceConditions">
            <el-radio-group v-model="form.serviceConditions">
              <el-radio v-model="form.serviceConditions" :label="0">满减</el-radio>
              <el-radio v-model="form.serviceConditions" :label="1">没有限制</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.serviceConditions===0" prop="fullReductionMoney">
            <el-input-number class="hideBtn" v-model="form.fullReductionMoney" :min="1" :precision="2" placeholder="满减金额（满多少可以减）"></el-input-number>
          </el-form-item>
          <el-form-item label="适用门店" prop="suitableStore">
            <el-radio-group v-model="form.suitableStore">
              <el-radio v-model="form.suitableStore" :label="0">所有门店</el-radio>
              <el-radio v-model="form.suitableStore" :label="1">指定门店</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.suitableStore===1" prop="useStoreList">
            <div class="store" v-for="item in form.useStoreList" :key="item.storeId" @click="handleStore">{{`${item.storeName}（${item.storeNum}）`}}</div>
            <el-button v-if="!(form.useStoreList.length>0)" type="primary" size="mini" @click="handleStore">选择门店</el-button>
          </el-form-item>
          <el-form-item label="适用项目" prop="suitableProject">
            <el-radio-group v-model="form.suitableProject">
              <el-radio v-model="form.suitableProject" :label="0">所有项目</el-radio>
              <el-radio v-model="form.suitableProject" :label="1">指定项目</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.suitableProject===1" prop="projectList">
            <div class="store" v-for="item in form.projectList" :key="item.projectId" @click="handleProject">{{`${item.projectName}（${item.projectNum}）`}}</div>
            <el-button v-if="!(form.projectList.length>0)" type="primary" size="mini" @click="handleProject">选择项目</el-button>
          </el-form-item>
          <el-form-item label="有效方式" prop="indateType">
            <el-radio-group v-model="form.indateType" @change="handleChange($event===0?['startDay','endDay']:$event===1?['fixDate']:false)">
              <el-radio v-model="form.indateType" :label="0">领取后多少天</el-radio>
              <el-radio v-model="form.indateType" :label="1">固定日期</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.indateType===0" prop="startDay">
            <el-input v-model.trim="form.startDay" placeholder="领取后多少天生效"></el-input>
          </el-form-item>
          <el-form-item v-if="form.indateType===0" prop="endDay">
            <el-input v-model.trim="form.endDay" placeholder="生效后多少天内有效"></el-input>
          </el-form-item>
          <el-form-item v-if="form.indateType===1" prop="fixDate">
            <el-date-picker v-model="form.fixDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="截止日期" value-format="yyyy-MM-dd 00:00:00" @change="handleChange(['fixDate'],true)" style="width:100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="分享提成规则" prop="shareCommissionRules">
            <el-radio-group v-model="form.shareCommissionRules" @change="handleChange($event===0?['fixedAmount']:$event===1?['orderCommission']:false)">
              <el-radio v-model="form.shareCommissionRules" :label="0">固定提成(元)</el-radio>
              <el-radio v-model="form.shareCommissionRules" :label="1">单据金额抽成(%)</el-radio>
            </el-radio-group>
            <div style="color:red">注：单据金额抽成无需保证金</div>
          </el-form-item>
          <el-form-item v-if="form.shareCommissionRules===0" prop="fixedAmount">
            <el-input-number class="hideBtn" v-model="form.fixedAmount" :min="1" :precision="2" placeholder="固定提成(元)" @blur="handleCalculate"></el-input-number>
          </el-form-item>
          <el-form-item v-if="form.shareCommissionRules===1" prop="orderCommission">
            <el-input-number class="hideBtn" v-model="form.orderCommission" :min="1" :max="100" :precision="0" placeholder="单据金额抽成(%)" @blur="handleCalculate"></el-input-number>
          </el-form-item>
          <el-form-item label="保证金" prop="guaranteeMoney" v-if="form.shareCommissionRules===0">
            <el-input v-model.trim="form.guaranteeMoney" placeholder="保证金(自动生成)" readonly></el-input>
          </el-form-item>
          <el-form-item label="活动图片" prop="imageUrl">
            <active-img ref="activeImg" @active-img="handleImage"></active-img>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="box">
          <el-button type="warning" @click="handleNext" size="medium">下一步</el-button>
          <!-- <el-button type="primary" @click="handleNext" size="medium">提交</el-button> -->
          <el-button @click="resetForm" size="medium">重置</el-button>
        </div>
      </el-col>
    </el-row>
    <Store ref="Store" @call-back-store="callBackStore"></Store>
    <Project ref="Project" @call-back-project="callBackProject"></Project>
    <!-- <QrCode ref="QrCode"></QrCode> -->

  </div>
</template>

<script>
import ActiveImg from './activeImg'
import Tencent from './Tencent'
import Store from '@/components/mulStore/index'
import Project from '@/components/mulProject/index'
import { partten } from "@/utils/partten/index.js";
import QrCode from "./qrCode";
export default {
  name: 'Form',
  components: { ActiveImg, Tencent, Store, Project, QrCode },
  data() {
    return {
      form: {
        couponNumber: 1,
        useStoreList: [],
        projectList: [],
      },
      qrCode: null,
      rules: {
        couponName: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
        ],
        couponNumber: [
          { required: true, message: '请输入优惠券数量', trigger: 'blur' },
        ],
        serviceConditions: [
          { required: true, message: '请选择优惠限制', trigger: ['blur', 'change'] },
        ],
        couponType: [
          { required: true, message: '请选择优惠方式', trigger: ['blur', 'change'] },
        ],
        fullKimsMoney: [
          { required: true, message: '请输入抵扣金额', trigger: 'blur' },
        ],
        fullDiscountMoney: [
          { required: true, message: '请输入折扣(%)', trigger: 'blur' },
        ],
        fullReductionMoney: [
          { required: true, message: '请输入满减金额', trigger: 'blur' },
        ],
        suitableStore: [
          { required: true, message: '请选择所有门店/指定门店', trigger: ['blur', 'change'] },
        ],
        useStoreList: [
          { required: true, message: '请选择适用门店', trigger: ['blur', 'change'] },
        ],
        suitableProject: [
          { required: true, message: '请选择所有项目/指定项目', trigger: ['blur', 'change'] },
        ],
        projectList: [
          { required: true, message: '请选择适用项目', trigger: ['blur', 'change'] },
        ],
        indateType: [
          { required: true, message: '请选择有效方式', trigger: ['blur', 'change'] },
        ],
        fixDate: [
          { required: true, message: '请选择有效日期', trigger: ['blur', 'change'] },
        ],
        startDay: [
          { required: true, message: '请输入多少天', trigger: 'blur' },
        ],
        endDay: [
          { required: true, message: '请输入多少天', trigger: 'blur' },
        ],
        shareCommissionRules: [
          { required: true, message: '请选择分享提成规则', trigger: ['blur', 'change'] },
        ],
        fixedAmount: [
          { required: true, message: '请输入固定金额', trigger: 'blur' },
        ],
        orderCommission: [
          { required: true, message: '请输入单据金额抽成(%', trigger: 'blur' },
        ],
        imageUrl: [{ required: true, message: '请上传活动图片', trigger: ['blur', 'change'] }],
        guaranteeMoney: [{ required: true, message: '请输入保证金', trigger: ['blur', 'change'] }],
        qrCode: [{ required: true, message: '请关注公众号', trigger: ['blur', 'change'] }],
      },
    }
  },
  created() {
    // this.fetchAccessToken()
  },
  methods: {

    // ============================== 操作 ============================== //
    // 编辑
    handleData(row) {
      console.log('row', row);
      // 判断传过来的值中时候有id来判断当前是新增的还是编辑的数据，有id的为编辑数据
      if (row.id) {
        // 从管理页面过来useStoreList和projectList空所以取的是useStores和useProjects中的值，如果是从预览页面，即步骤2过来的就直接取useStoreList和projectList中的值
        row.useStoreList = row.useStoreList ? row.useStoreList : Array.from(row.useStores);
        row.projectList = row.projectList ? row.projectList : Array.from(row.useProjects);
        // 因为是编辑，所以需要将图片的链接拼接出来，将之前上传的图片展示出来,但是如果已经选了其它图片就直接使用当前的imageUrl路径
        row.imageUrl = row.imageUrl ? row.imageUrl : partten.imagePath + row.fileLists[0].filePath + '/' + row.fileLists[0].fileName
        // 因为后台需要的是一个拆开的两个时间不是一个时间数组，element的时间组件获取的值时时间数组所以需要自定义一个fixDate值来接受，新增提交时拆开，现在编辑需要重新将两个值组合回一个时间数组
        row.fixDate = Array.from([row.startDate, row.endDate]);

      }
      if (row.imageUrl) {
        // 展示图片，因为一开始展示页面，当前页面的子组件也是刚加载无法立马使用this.$refs获取，需要用this.$nextTick来过度一下
        this.$nextTick(function () {
          this.$refs.activeImg.show(row.imageUrl)
        });
      }
      this.form = Object.assign({}, row);
    },
    // 下一步
    handleNext() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('next', 2, this.form)
        } else {
          return false
        }
      })
    },
    // 重置
    resetForm() {
      this.$refs.form.resetFields()
      this.$baseMessage('重置成功', 'success')
    },
    // ============================== 第三方插件方法 ============================== //
    // 单选框发生改变时,清除上一个的校验
    handleChange(value, judge) {
      if (judge) {
        // 有效日期发生改变时，将时间数组fixDate拆分为startDate和endDate
        this.$refs.form.validateField(value)
        let form = Object.assign({}, this.form);
        form.startDate = form.fixDate[0]
        form.endDate = form.fixDate[1]
        this.form = Object.assign({}, form);
      }
      // 单选框切换时，对应输入框的显示和隐藏没有能够将校验去掉，所以得要我自己手动去掉校验
      if (value.length > 1) {
        value.forEach((item) => {
          this.$refs.form.clearValidate([item])
        });
      } else {
        this.$refs.form.clearValidate(value)
      }
    },
    // 选择图片后返回
    handleImage(file) {
      let form = Object.assign({}, this.form);
      form.multipartFile = file
      form.imageUrl = URL.createObjectURL(file)
      this.form = Object.assign({}, form);
      this.$nextTick(function () {
        this.$refs.form.validateField(['imageUrl'])
      });
    },
    // 发布后清除选择的文件
    handleClear() {
      this.$refs.activeImg.handleClear()
    },
    // 打开门店弹窗
    handleStore() {
      this.$refs.Store.show()
    },
    // 选择门店后返回
    callBackStore(list) {
      let form = Object.assign({}, this.form);
      form.useStoreList = Array.from(list);
      this.form = Object.assign({}, form);
      this.$nextTick(function () {
        this.$refs.form.validateField(['useStoreList'])
      });
    },
    // 打开项目弹窗
    handleProject() {
      this.$refs.Project.show()
    },
    // 选择项目后返回
    callBackProject(list) {
      let form = Object.assign({}, this.form);
      form.projectList = Array.from(list);
      this.form = Object.assign({}, form);
      this.$nextTick(function () {
        this.$refs.form.validateField(['projectList'])
      });
    },
    // 计算保证金
    handleCalculate() {
      let form = Object.assign({}, this.form);
      // 固定提成方式：保证金(guaranteeMoney) = 优惠券数量(couponNumber) * 固定提成（元）(fixedAmount)
      if (form.shareCommissionRules === 0) {
        if (form.couponNumber && form.fixedAmount) {
          form.guaranteeMoney = new this.$Decimal(form.couponNumber).mul(new this.$Decimal(form.fixedAmount)).toNumber()
        }
      }
      // 单据金额抽成：保证金(guaranteeMoney) = 当前默认10000元
      if (form.shareCommissionRules === 1) {
        form.guaranteeMoney = 0
      }
      this.form = Object.assign({}, form);
    }
  },
}
</script>
<style scoped>
.container {
  height: 75vh;
  /* background-color: #409eff; */
  overflow-y: auto;
  overflow-x: hidden;
}
.container .form {
  width: 500px;
}
.container .box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}
/* 让form-item下边距增大 */
.form .el-form-item {
  margin-bottom: 15px;
}
/* 让输入款的内容居中 */
.form /deep/ .el-form-item .el-input--medium .el-input__inner {
  text-align: center;
}
/* 让form标题离内容更远一点 */
.form /deep/ .el-form-item .el-form-item__content {
  margin-left: 90px !important;
}
/* 隐藏el-input-number的加减按钮 */
.form .hideBtn {
  width: 100%;
}
.form .hideBtn /deep/ .el-input-number__decrease {
  display: none;
}
.form .hideBtn /deep/ .el-input-number__increase {
  display: none;
}
/* 门店 */
.form .store {
  color: #000;
  border: 1px solid #409eff;
  padding: 5px 10px;
  margin-bottom: 10px;
  border-radius: 5px;
  cursor: pointer;
}
</style>
