<!--商家-新增/编辑拼团 -->
<template>
  <el-dialog
    custom-class="center-dialog"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="50%"
    @close="close"
  >
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item :label="__('活动标题')" prop="activity_title">
        <el-input v-model="form.activity_title" :placeholder="__('活动标题')" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('活动开始时间')" prop="activity_starttime">
              <el-date-picker
                v-model="form.activity_starttime"
                :placeholder="__('选择日期')"
                :readonly="isReadOnly"
                :style="{ width: '100%' }"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple"></div>
          <el-form-item :label="__('活动结束时间')" prop="activity_endtime">
            <el-date-picker
              v-model="form.activity_endtime"
              :placeholder="__('选择日期')"
              :readonly="isReadOnly"
              :style="{ width: '100%' }"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="__('成团天数限制')" prop="group_days_limit">
        <el-input
          v-model="form.group_days_limit"
          oninput="value=value.replace(/[^\d]/g,'')"
          :placeholder="__('成团天数限制')"
          :style="{ width: '100%' }"
          type="number"
        />
      </el-form-item>
      <el-form-item :label="__('活动介绍')" prop="activity_intro">
        <el-input
          v-model="form.activity_intro"
          :placeholder="__('活动介绍')"
          :rows="6"
          :style="{ width: '100%' }"
          type="textarea"
        />
      </el-form-item>
      <el-form-item :label="__('请选择商品')" prop="product_item_name">
        <el-input
          v-model="form.product_item_name"
          clearable
          :placeholder="__('请选择商品')"
          readonly
          @focus="showItemTable"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('商品限购')" prop="group_buy_limit">
              <el-input
                v-model="form.group_buy_limit"
                oninput="value=value.replace(/[^\d]/g,'')"
                :placeholder="__('商品限购')"
                :style="{ width: '100%' }"
                type="number"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('拼团人数')" prop="group_quantity">
              <el-input
                v-model="form.group_quantity"
                oninput="value=value.replace(/[^\d]/g,'')"
                :placeholder="__('拼团人数')"
                :style="{ width: '100%' }"
                type="number"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item :label="__('选择优惠方式')" prop="group_discount_type">
        <el-radio-group
          v-model="form.group_discount_type"
          @change="resetDiscount"
        >
          <el-radio :label="1">{{ __('固定价格购买') }}</el-radio>
          <el-radio :label="2">{{ __('优惠固定金额') }}</el-radio>
          <el-radio :label="3">{{ __('以固定折扣购买') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('拼团单价')" prop="group_sale_price">
              <el-input
                v-model="form.group_sale_price"
                oninput="if(isNaN(value)) { value = parseFloat(value) } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                :placeholder="__('拼团单价')"
                :readonly="
                  form.group_discount_type === 2 ||
                  form.group_discount_type === 3
                "
                :style="{ width: '100%' }"
                type="number"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col v-if="form.group_discount_type === 2" :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('优惠固定金额')" prop="group_fixed_amount">
              <el-input
                v-model="form.group_fixed_amount"
                oninput="if(isNaN(value)) { value = parseFloat(value) } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                :placeholder="__('优惠固定金额')"
                :style="{ width: '100%' }"
                type="number"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col v-if="form.group_discount_type === 3" :span="12">
          <div class="grid-content bg-purple">
            <el-form-item :label="__('固定折扣')" prop="group_fixed_discount">
              <el-input
                v-model="form.group_fixed_discount"
                :placeholder="__('固定折扣')"
                :style="{ width: '100%' }"
                type="number"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
    <ProductItemTable ref="productItemTable" @checkItem="getCheckItem" />
  </el-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import ProductItemTable from '@/components/activity/ProductItemDialogTable'
  import { doEdit, Update } from '@/api/store/activity/base'
  import { renderTime } from '@/utils/date'
  import { URL } from '@/config'
  import { sub, accDiv, mul } from '@/utils/math'

  export default {
    name: 'StoreActivityBaseEdit',
    components: { ProductItemTable },
    data() {
      return {
        action: URL.action,
        item_unit_price: 0,
        form: {
          group_fixed_discount: 0,
          group_fixed_amount: 0,
          group_discount_type: 1,
          group_sale_price: 0,
          activity_starttime: '',
          activity_endtime: '',
          activity_type_id: 1123,
          product_item_name: '',
          item_id: '',
        },
        rules: {
          activity_title: [
            { required: true, trigger: 'blur', message: this.__('活动标题') },
          ],
          activity_starttime: [
            {
              required: true,
              trigger: 'blur',
              message: this.__('活动开始时间'),
            },
          ],
          activity_endtime: [
            {
              required: true,
              trigger: 'blur',
              message: this.__('活动结束时间'),
            },
          ],
          product_item_name: [
            {
              required: true,
              trigger: 'blur',
              message: this.__('请选择商品'),
            },
          ],
          group_quantity: [
            {
              required: true,
              trigger: 'blur',
              message: this.__('请输入拼团人数'),
            },
          ],
          group_sale_price: [
            {
              required: true,
              trigger: 'blur',
              message: this.__('请输入拼团单价'),
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    computed: {
      isReadOnly() {
        return this.form.activity_id !== undefined
      },
    },
    watch: {
      'form.group_fixed_amount': {
        handler(newVal, oldVal) {
          if (newVal) {
            this.form.group_sale_price = sub(this.item_unit_price, newVal, 2)
          } else {
            this.form.group_sale_price = this.item_unit_price
          }
        },
        immediate: true,
      },
      'form.group_fixed_discount': {
        handler(newVal, oldVal) {
          if (newVal) {
            this.form.group_sale_price = mul(
              accDiv(newVal, 100, 2),
              this.item_unit_price,
              2
            )
          } else {
            this.form.group_sale_price = this.item_unit_price
          }
        },
        immediate: true,
      },
    },
    methods: {
      __,
      resetDiscount(value) {
        this.form.group_sale_price = this.item_unit_price
        switch (value) {
          case 1:
            this.form.group_fixed_amount = 0
            this.form.group_fixed_discount = 0
            break
          case 2:
            this.form.group_fixed_discount = 0
            break
          case 3:
            this.form.group_fixed_amount = 0
            break
        }
      },
      getCheckItem(row) {
        this.form.item_id = row.item_id
        this.form.product_item_name = row.product_item_name
        this.item_unit_price = row.item_unit_price
        this.$refs['form'].validateField(
          ['product_item_name', 'item_id'],
          (errorMsg) => {
            if (!errorMsg) {
              //执行校验成功的相关操作
            }
          }
        )
        this.calculatePrice(row.item_unit_price)
      },

      calculatePrice(item_unit_price) {
        let groupFixedAmount = this.form.group_fixed_amount
        let group_fixed_discount = this.form.group_fixed_discount
        switch (this.form.group_discount_type) {
          case 1:
            this.form.group_sale_price = item_unit_price
            break
          case 2:
            if (groupFixedAmount) {
              this.form.group_sale_price = sub(
                this.item_unit_price,
                groupFixedAmount,
                2
              )
            } else {
              this.form.group_sale_price = item_unit_price
              this.form.group_fixed_amount = 0
            }
            break
          case 3:
            if (group_fixed_discount) {
              this.form.group_sale_price = mul(
                accDiv(group_fixed_discount, 100),
                this.form.group_sale_price,
                2
              )
            } else {
              this.form.group_sale_price = item_unit_price
              this.form.group_fixed_discount = 0
            }
            break
        }
      },
      showEdit(row) {
        if (!row) {
          this.title = this.__('新增')
        } else {
          this.title = this.__('编辑')
          this.form = {
            activity_type_id: 1123,
            activity_id: row.activity_id,
            activity_title: row.activity_title,
            activity_starttime: renderTime(row.activity_starttime),
            activity_endtime: renderTime(row.activity_endtime),
            item_id: row.activity_rule.item_id,
            group_days_limit: row.activity_rule.group_days_limit,
            product_item_name: row.activity_rule.product_item_name,
            group_buy_limit: row.activity_rule.group_buy_limit,
            activity_intro: row.activity_rule.activity_intro,
            group_quantity: row.activity_rule.group_quantity,
            group_fixed_discount: row.activity_rule.group_fixed_discount,
            group_discount_type: row.activity_rule.group_discount_type,
            group_sale_price: row.activity_rule.group_sale_price,
            group_fixed_amount: row.activity_rule.group_fixed_amount,
          }
          this.item_unit_price = row.activity_rule.item_unit_price
        }

        this.dialogFormVisible = true
      },
      close() {
        this.item_unit_price = 0
        this.form = {
          group_fixed_discount: 0,
          group_fixed_amount: 0,
          group_discount_type: 1,
          group_sale_price: 0,
          activity_starttime: '',
          activity_endtime: '',
          activity_type_id: 1123,
          product_item_name: '',
          item_id: '',
        }
        this.$refs['form'].resetFields()
        this.dialogFormVisible = false
      },
      showItemTable() {
        this.$refs['productItemTable'].showTable()
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.activity_id && this.form.activity_id != undefined) {
              const { msg, status } = await Update(this.form)
              if (200 == status) {
                this.$baseMessage(msg, 'success')
              } else {
                this.$baseMessage(msg, 'error')
              }
            } else {
              const { msg, status } = await doEdit(this.form)
              if (200 == status) {
                this.$baseMessage(msg, 'success')
              } else {
                this.$baseMessage(msg, 'error')
              }
            }
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
