<template>
  <div class="edit_add_page">
    <div class="content">
      <el-form ref="form" :model="form" label-width="150px" :rules="formRules">
        <h2>基础信息</h2>
        <br>
        <el-form-item label="活动名称:" prop="activityName">
          <el-input v-model="form.activityName" maxlength="20" placeholder="请输入活动名称" :disabled="unStart" />
        </el-form-item>

        <el-form-item label="活动介绍:" prop="activityIntroduce">
          <el-input
            v-model="form.activityIntroduce" maxlength="200" type="textarea" placeholder="请输入活动介绍"
            :disabled="unStart" style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="报名时间:" prop="signTime">
          <el-date-picker
            v-model="date2" type="datetimerange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
          />
          <p class="timeInfo">报名时间不能交叉且报名时间不能大于活动时间</p>
        </el-form-item>

        <el-form-item label="活动时间:" prop="activityTime">
          <el-date-picker
            v-model="date1" type="datetimerange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" :disabled="applyEnd"
          />
          <p class="timeInfo">平台活动时间不能交叉并且活动时间不能小于报名时间</p>
        </el-form-item>

        <el-form-item label="活动保证金:">
          <el-radio-group v-model="form.ifBond">
            <el-radio :label="1" :disabled="unStart">需要</el-radio>
            <el-radio :label="0" :disabled="unStart">不需要</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.ifBond === 1" label="保证金金额:">
          <el-input v-model="form.bondMoney" maxlength="9" placeholder="请输入活动保证金金额" :disabled="unStart" />
        </el-form-item>

        <!-- <el-form-item label="活动标签">
          <el-input v-model="form.activityLabel" placeholder="请输入活动标签" :disabled="unStart" />
        </el-form-item> -->

        <h2>优惠规则</h2>
        <br>
        <el-form-item label="使用门槛:" prop="threshold">
          满<el-input
            v-model="form.threshold" maxlength="9" :disabled="unStart" style="width: 100px;margin: 0 12px;"
            @input="checkMoney"
          />元
        </el-form-item>
        <el-form-item label="优惠方式:">
          <el-radio-group v-model="form.discountMode" @change="changeDiscountMode">
            <el-radio :label="1" :disabled="unStart">满减</el-radio>
            <el-radio :label="2" :disabled="unStart">折扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠内容:" prop="couponContent">
          <div v-if="form.discountMode === 1">
            减<el-input
              v-model="form.couponContent" maxlength="9" :disabled="unStart" style="width: 100px;margin: 0 12px;"
              @input="checkMoney2"
            />元
          </div>
          <div v-if="form.discountMode === 2">
            <el-input
              v-model="form.couponContent" maxlength="9" :disabled="unStart"
              style="width: 100px;margin-right: 12px;" @input="checkDiscount"
            />折
          </div>
        </el-form-item>

        <el-form-item label="发放数量:" prop="number">
          <el-input
            v-model="form.number" maxlength="9" :disabled="unStart" style="width: 100px;margin-right: 12px;"
            @input="checkNumber"
          />张
        </el-form-item>
        <el-form-item label="是否限领:">
          <el-radio-group v-model="form.receiveType">
            <el-radio :label="1" :disabled="unStart">不限制</el-radio>
            <el-radio :label="2" :disabled="unStart">限制领取</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.receiveType === 2" label="限制领取次数:">
          <el-input
            v-model="form.frequency" maxlength="9" :disabled="unStart" style="width: 100px;margin-right: 12px;"
            oninput="value=value.replace(/[^\d]/g,'')"
          />次
        </el-form-item>
        <el-form-item label="是否开启积分兑换:">
          <el-radio-group v-model="form.ifCredit">
            <el-radio :label="1" :disabled="unStart">是</el-radio>
            <el-radio :label="0" :disabled="unStart">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.ifCredit" label="所需积分:">
          <el-input
            v-model="form.credit" maxlength="9" :disabled="unStart" style="width: 150px"
            oninput="value=value.replace(/[^\d]/g,'')"
          /> 分
        </el-form-item>
        <el-form-item label="可用范围:">
          <el-radio-group v-model="form.applyType" @change="changeType">
            <el-radio :label="1" :disabled="unStart">全部</el-radio>
            <el-radio :label="2" :disabled="unStart">选择类别</el-radio>
            <el-select v-if="form.applyType === 2" v-model="form.applyCategory" placeholder="请选择">
              <el-option
                v-for="item in classList" :key="item.classifyId" :label="item.classifyName"
                :value="item.classifyId"
              />
            </el-select>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="微信卡券:">
          <el-checkbox
            v-model="form.syncCard" :true-label="1" :false-label="0"
            :disabled="unStart"
          >
            领取后可同步微信卡包
          </el-checkbox>
        </el-form-item>
        <div v-show="form.syncCard === 1">
          <h2>卡券同步设置</h2>
          <br>
          <!--          <el-form-item label="券跳转配置:">-->
          <!--            <div>券跳转路径</div>-->
          <!--            <el-input v-model="form.appletAppId" type="text" :disabled="unStart" placeholder="请输入券跳转路径" />-->
          <!--          </el-form-item>-->
          <el-form-item label="卡券标题:">
            <el-input
              v-model="form.cardTitle" maxlength="21" show-word-limit type="text"
              :disabled="isEdit"
              placeholder="请输入卡券标题"
            />
          </el-form-item>
          <el-form-item label="券主题颜色:">
            <!--            <el-color-picker v-model="form.color" />-->
            <el-select v-model="form.cardColor" class="color-select" placeholder="请选择" :disabled="isEdit">
              <el-option v-for="item in bgColors" :key="item.value" :label="item.value" :value="item.value">
                <span
                  class="color-box"
                  :style="{ 'width': '30px', 'height': '30px', 'float': 'left', 'backgroundColor': item.label }"
                />
                <span class="color-val" :style="{ 'float': 'right' }">{{ item.value }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用需知:">
            <el-input
              v-model="form.cardNotice" maxlength="15" show-word-limit type="textarea"
              placeholder="使用需知"
              :disabled="isEdit" style="width: 400px;"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <div class="btn_list">
        <span @click="cancel">取消</span>
        <span @click="save">保存</span>
      </div>
    </div>
  </div>
</template>

<script>
import { activeAdd, activeUpdate, activeGetById } from '@/api/active'
import { commdityClassGetAll } from '@/api/renovation'
// import shopList from '@/views/active/couponlist/component/shopList';
import {
} from '@/api/active/active_seckill.js'
import Form from './module'
export default {
  components: {
    // shopList
  },
  props: {
    activityForm: {
      type: Object,
      default: () => { }
    },
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const validateSignTime = (rule, value, callback) => {
      if (!(this.date2 && this.date2.length === 2)) {
        callback(new Error('请选择报名时间'))
      } else {
        callback()
      }
    }
    const validateActivityTime = (rule, value, callback) => {
      if (!(this.date1 && this.date1.length === 2)) {
        callback(new Error('请选择活动时间'))
      } else {
        callback()
      }
    }
    return {
      form: new Form(),
      date1: [], // 活动时间
      date2: [], // 报名时间
      type: false,
      classList: [],
      formParams: {
        page: 1,
        pageSize: 100
      },
      classifyId: null,
      shopListShow: false,
      shopList: [],
      bgColors: [{
        value: 'Color010',
        label: '#638359'
      }, {
        value: 'Color020',
        label: '#2C9F67'
      }, {
        value: 'Color030',
        label: '#509FC9'
      }, {
        value: 'Color040',
        label: '#5885CF'
      }, {
        value: 'Color050',
        label: '#9062C0'
      }, {
        value: 'Color060',
        label: '#D09A45'
      }, {
        value: 'Color070',
        label: '#E48138'
      }, {
        value: 'Color080',
        label: '#EE903C'
      }, {
        value: 'Color090',
        label: '#DD6549'
      }, {
        value: 'Color100',
        label: '#CC463D'
      }],
      formRules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        activityIntroduce: [
          { required: true, message: '请输入活动介绍', trigger: 'blur' }
        ],
        signTime: [
          { validator: validateSignTime, required: true, trigger: 'blur' }
        ],
        activityTime: [
          { validator: validateActivityTime, required: true, trigger: 'blur' }
        ],
        threshold: [
          { required: true, message: '请输入使用门槛', trigger: 'blur' }
        ],
        couponContent: [
          { required: true, message: '请输入优惠内容', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入发放数量', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 其他修改
    unStart() {
      const t = this.isEdit ? this.activityForm : null
      return t && !(t.state === 0)
    },
    // 时间修改
    applyEnd() {
      const t = this.isEdit ? this.activityForm : null
      return t && (t.state === 3 || t.state === 4)
    }
  },
  watch: {
    isEdit: {
      handler(nVal, oVal) {
        if (nVal) {
          this.getDetails()
        } else {
          this.reset()
        }
      }
    },
    activityForm: {
      handler(nVal, oVal) {
        if (nVal) {
          this.getDetails()
        }
      }
    }
  },
  mounted() {
    this.getAll(this.formParams)
    if (this.isEdit) { // 初始化watch无法监听isEdit，手动获取数据
      this.getDetails()
    }
  },
  methods: {
    // 获取类别
    async getAll(formParams) {
      const res = await commdityClassGetAll(formParams)
      this.classList = res.data.list
    },
    async getDetails() {
      const res = await activeGetById({ activityId: this.activityForm.activityId })
      if (JSON.stringify(res.data) !== '{}') {
        this.form = res.data
        this.date1 = [res.data.activityStartTime, res.data.activityEndTime] // 活动时间
        this.date2 = [res.data.signStartTime, res.data.signEndTime] // 报名时间
      }
    },
    showShopLst() {
      this.shopListShow = !this.shopListShow
    },
    // 商家
    cleanShopList() {
      this.shopListShow = false
    },
    cancel() {
      this.$emit('cancel')
      this.form = new Form()
      this.date1 = [] // 活动时间
      this.date2 = [] // 报名时间
    },
    refersh() { this.$emit('refersh') },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.form, {
            activityStartTime: this.date1[0] || '',
            activityEndTime: this.date1[1] || '',
            signStartTime: this.date2[0] || '',
            signEndTime: this.date2[1] || '',
            bondMoney: this.form.bondMoney * 1
          })
          // if (this.shopList.length) {
          //   this.shopList.forEach((item) => {
          //     this.form.shopIdList.push(item.shopId)
          //   })
          // }
          console.log(this.form.shopIdList, 'shopIdList')
          const errArr = []
          if (params.activityName === '') {
            errArr.push('请输入活动名称')
          }
          if (params.activityIntroduce === '') {
            errArr.push('请输入活动介绍')
          }
          if (this.date2.length === 0) {
            errArr.push('请选择报名时间')
          }
          if (this.date1.length === 0) {
            errArr.push('请选择活动时间')
          }
          if (errArr.length !== 0) {
            errArr.forEach((item, index) => {
              this.$message({
                type: 'error',
                message: item,
                offset: index * 40 + 20,
                duration: 5000
              })
            })
            return
          }
          if (this.isEdit) {
            return activeUpdate(Object.assign(params, { activityId: this.activityForm.activityId })).then((res) => {
              if (res.code === '') {
                this.$message.success('修改成功')
                this.reset()
                this.refersh()
              }
            })
          }
          return activeAdd(params).then((res) => {
            if (res.code === '') {
              this.$message.success('新增成功')
              this.reset()
              this.refersh()
            }
          })
        }
      })
    },
    reset() {
      this.form = new Form()
      this.list = [ { fullMoney: '', reduceMoney: '' } ]
      this.date1 = []
      this.date2 = []
    },
    selectShop(val) {
      this.shopList = val
    },
    changeType() {
    },
    checkMoney(e) {
      this.form.threshold = e.match(/^\d*(\.?\d{0,2})/g)[0] || null
    },
    checkMoney2(e) {
      this.form.couponContent = e.match(/^\d*(\.?\d{0,2})/g)[0] || null
    },
    checkDiscount(e) {
      this.form.couponContent = e.match(/^\d{0,1}(\.?\d{0,1})/g)[0] || null
      if (this.form.couponContent !== null) {
        if (this.form.couponContent > 9.9) {
          this.form.couponContent = 9.9
        }
      }
    },
    changeDiscountMode() {
      this.form.couponContent = 0
    },
    checkNumber(e) {
      const ret = e.match(/^\d{1,9}$/g)
      if (!ret) {
        this.form.number = 1
      } else {
        this.form.number = ret[0]
        if (this.form.number < 1) {
          this.form.number = 1
        } else if (this.form.number > 999999999) {
          this.form.number = 999999999
        }
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.edit_add_page {
	padding: 20px;

	h2 {
		font-size: 24px;
		font-weight: 500;
		position: relative;

		&::before {
			content: "";
			height: 24px;
			width: 4px;
			background-color: #3a68f2;
			position: absolute;
			left: -10px;
			top: 2px;
			display: block;
		}
	}

	.content {
		background-color: #fff;
		padding: 0 50px 20px;
		overflow: hidden;

		.el-form {
			.el-form-item {
				label.el-form-item__label {
					font-size: 16px !important;
					color: red !important;
				}
			}
		}

		.photo {
			padding: 70px 100px;

			.avatar-uploader {
				width: 180px;

				.el-icon-plus,
				img {
					width: 180px;
					height: 180px;
					line-height: 180px;
					border: 1px #bbb solid;
					border-radius: 4px 4px 0px 4px;
					margin-bottom: 10px;
					text-align: center;
				}

				img {
					border: none;
				}
			}
		}
	}

	.footer {
		height: 100px;
		line-height: 100px;
		font-size: 24px;
		position: relative;
		border-top: 1px solid #e0e5eb;

		.btn_list {
			position: absolute;
			right: 0;
			top: 0;
			height: 50px;

			span {
				padding: 0;
				margin: 0;
				width: 100px;
				height: 50px;
				line-height: 50px;
				text-align: center;
				display: inline-block;
				font-size: 16px;
				border-radius: 4px;
				box-sizing: border-box;

				&:hover {
					cursor: pointer;
				}

				&:nth-child(1) {
					background: rgba(255, 255, 255, 1);
					order: 1px solid rgba(224, 229, 235, 1);
					margin-right: 20px;
					border: 1px solid rgba(224, 229, 235, 1);
				}

				&:nth-child(2) {
					background: rgba(58, 104, 242, 1);
					color: #fff;
				}
			}
		}
	}

	.timeInfo {
		font-size: 12px;
		color: #999999;
	}

	.el-input {
		width: 400px;
	}

	.addShop {
		color: #409EFF;
		cursor: pointer;
	}

	.arrow {
		display: inline-block;
		width: 10px;
		height: 10px;
		border-top: 1px solid #CCCCCC;
		border-right: 1px solid #CCCCCC;
	}

	.arrowUp {
		transform: rotate(-45deg);
	}

	.arrowDown {
		transform: rotate(135deg);
	}

	.selectShopBox {
		.leftTit {
			font-size: 14px;
			color: #666666;
			float: left;
			margin-right: 15px;
		}

		.rightBox {
			float: left;

			span {
				padding: 5px 8px;
				border: 1px solid #e1e1e1;
				color: #999999;
				font-size: 12px;
				margin-right: 10px;
			}
		}
	}
}
</style>
