<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="freeQueuingModalVisible" :title="dialogTitle" :before-close="handleBeforeClose">
    <el-form ref="freeQueuingModalRef" :rules="rules" :model="form" label-width="auto">
      <el-form-item label="活动名称" prop="activitiesName">
        <el-input placeholder="请输入活动名称" v-model="form.activitiesName" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="支持商家" prop="shopIds">
        <el-select style="width: 100%" multiple filterable remote reserve-keyword placeholder="请输入商家名称" :remote-method="handleSerachShop" :loading="searchShopLoading" v-model="form.shopIds">
          <el-option v-for="shop in shopList" :key="shop.shopId" :label="shop.shopName" :value="shop.shopId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商家免单比例(现金)" prop="shopExemptionRatio">
        <el-input placeholder="请填写免单比例，范围0 - 1，保留两位小数" v-model="form.shopExemptionRatio"></el-input>
      </el-form-item>
      <el-form-item label="发起方" prop="isPlatformInit">
        <el-radio-group size="mini" v-model="form.isPlatformInit">
          <el-radio :label="1">平台</el-radio>
          <el-radio :label="0">商家</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="close">取消</el-button>
        <el-button size="mini" type="primary" :loading="isLoading" @click="onConfirm">{{ form.id ? '确认编辑' : '确认创建排队免单' }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { createFreeQueuingApi, updateFreeQueuingApi } from '@/api/freeQueuing'
import { businessListGetAll } from '@/api/business'

export default {
  data() {
    return {
      isLoading: false,
      freeQueuingModalVisible: false,
      dialogTitle: '新增排队免单',
      form: {
        id: undefined,
        activitiesName: '', // 活动名称
        shopIds: [],
        isPlatformInit: 1, // 是否为平台发起 0：商家
        shopExemptionRatio: ''
      },
      rules: {
        activitiesName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        shopIds: [{ required: true, type: 'array', message: '请选择商家', trigger: 'change' }],
        shopExemptionRatio: [
          { required: true, message: '请填写商家免单比例', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === undefined || value === '') {
                callback(new Error('请输入 aaa 值'))
              } else if (isNaN(value) || value < 0 || value > 1) {
                callback(new Error('免单比例值必须是 0 到 1 之间的小数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        isPlatformInit: [{ required: true, message: '请选择是否是平台发起', trigger: 'change' }]
      },
      shopList: [],
      searchShopLoading: false
    }
  },

  methods: {
    show(row) {
      this.reset()
      if (row) {
        this.form.id = row.id
        this.form.isPlatformInit = Number(row.isPlatformInit)
        this.form.activitiesName = row.activitiesName
        this.form.shopIds = row.shopIds ? row.shopIds.split(',') : []
        this.form.shopExemptionRatio = row.shopExemptionRatio || ''
        this.dialogTitle = '编辑排队免单'
      } else {
        this.dialogTitle = '新增排队免单'
      }
      this.freeQueuingModalVisible = true
      this.$nextTick(() => {
        this.$refs.freeQueuingModalRef.clearValidate()
      })
    },

    // 搜索商家
    async handleSerachShop(query) {
      if (query !== '') {
        this.searchShopLoading = true
        const res = await businessListGetAll({
          page: 1,
          pageSize: 50,
          shopName: query, // 店铺名称
          shopCode: '', // 店铺编码
          chargePersonName: '', // 店铺负责人
          contractState: '', // 合同状态 1-有效 0-无效
          shopType: 2,
          keyword: '' // 手机号搜索
        })

        this.shopList = res.data.list
        this.searchShopLoading = false
      } else {
        this.shopList = []
      }
    },

    async onConfirm() {
      try {
        this.isLoading = true
        await this.$refs.freeQueuingModalRef.validate()
        const api = this.form.id ? updateFreeQueuingApi : createFreeQueuingApi
        const data = JSON.parse(JSON.stringify(this.form))
        data.shopExemptionRatio = (data.shopExemptionRatio * 1).toFixed(2)
        data.shopIds = data.shopIds.join(',')
        await api(data)
        this.$message.success(data.id ? '编辑成功' : '发起排队免单成功')
        this.$emit('refresh')
        this.close()
      } finally {
        this.isLoading = false
      }
    },

    handleBeforeClose(done) {
      this.$refs.freeQueuingModalRef.resetFields()
      done()
    },

    close() {
      this.reset()
      this.freeQueuingModalVisible = false
    },

    reset() {
      this.form = {
        id: undefined,
        activitiesName: '', // 活动名称
        shopIds: [],
        isPlatformInit: 1, // 是否为平台发起 0：商家
        shopExemptionRatio: ""
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
