<!--
 * @Descripttion: (优惠券/tb_coupon 编辑弹窗)
 * @version: (1.0)
 * @Author: (lwh)
 * @Date: (2023-07-24)
 * @LastEditors: (lwh)
 * @LastEditTime: (2023-07-25)
-->
<template>
  <el-dialog v-model="props.modelValue" title="修改优惠券信息" width="900px" @closed="closeDialog" @open="openDialog">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-row :gutter="20">


        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="优惠劵名称" prop="couponName">
            <el-input v-model="formData.couponName" placeholder="请输入优惠劵名称" />
          </el-form-item>
        </el-col>

      </el-row>


      <el-row>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="优惠劵介绍" prop="couponDesc">
            <el-input v-model="formData.couponDesc" placeholder="请输入优惠劵介绍" />
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="使用须知" prop="couponUseIntro">
            <el-input :rows="5" type="textarea" v-model="formData.couponUseIntro" placeholder="请输入使用须知" />
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="优惠劵类型" prop="couponType">
            <el-radio-group v-model="formData.couponType">
              <el-radio v-for="item in  coupon_type " :key="item.dictValue" :label="parseInt(item.dictValue)">{{
                item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :lg="12" v-if="formData.couponType == 1">
          <el-form-item :label-width="labelWidth" label="减免金额" prop="couponDeductionMoney">
            <el-input-number v-model.number="formData.couponDeductionMoney" controls-position="right" :min="0"
              precision="2" />
            <span class="number-unit">元</span>
          </el-form-item>
        </el-col>
        <el-col :lg="12" v-if="formData.couponType == 2">
          <el-form-item :label-width="labelWidth" label="折扣率" prop="couponDiscountRate">
            <el-input-number v-model.number="formData.couponDiscountRate" controls-position="right" :min="0" :max="9.9"
              precision="1" />
            <span class="number-unit">%</span>
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="最低消费金额" prop="couponMinConsumeMoney">
            <el-input-number v-model.number="formData.couponMinConsumeMoney" controls-position="right" :min="0"
              precision="2" />
            <span class="number-unit">元</span>
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="到期类型" prop="couponExpireType">
            <el-radio-group v-model="formData.couponExpireType">
              <el-radio v-for="item in  coupon_expire_type " :key="item.dictValue" :label="parseInt(item.dictValue)">{{
                item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :lg="12" v-if="formData.couponExpireType == 1">
          <el-form-item :label-width="labelWidth" label="有效天数" prop="couponEffectiveDays">
            <el-input-number v-model.number="formData.couponEffectiveDays" controls-position="right" :min="0" />
            <span class="number-unit">天</span>
          </el-form-item>
        </el-col>
        <el-col :lg="12" v-if="formData.couponExpireType == 2">
          <el-form-item :label-width="labelWidth" label="" prop="couponFixedStartTime">
            <!-- <el-date-picker v-model="formData.couponFixedStartTime" type="datetime" :teleported="false"
              placeholder="选择日期时间"></el-date-picker> -->
            <el-date-picker v-model="formData.couponFixedTime" type="daterange" range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="适用范围" prop="couponApplicableScope">
            <el-radio-group v-model="formData.couponApplicableScope">
              <el-radio v-for="item in  applicable_scope " :key="item.dictValue" :label="parseInt(item.dictValue)">{{
                item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :lg="24" v-if="formData.couponApplicableScope == 2">
          <el-form-item :label-width="labelWidth" label="" prop="">
            <el-button type="primary" plain @click="handleChooseGoods">+ 指定商品</el-button>

            <el-table v-if="formData.couponApplicableScopeConfig.length != 0" v-loading="loading"
              :data="formData.couponApplicableScopeConfig" ref="tableRef" border highlight-current-row>
              <el-table-column prop="goodsPicture" width="150" label="图片" align="center">
                <template #default="scope">
                  <el-image preview-teleported :hide-on-click-modal="true" lazy class="table-td-thumb" fit="contain"
                    :src="scope.row.goodsPicture?.split(',')[0]" :preview-src-list="scope.row.goodsPicture?.split(',')">
                    <div><el-icon :size="15">
                        <document />
                      </el-icon></div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="goodsName" width="400" label="商品名称" align="left" :show-overflow-tooltip="true" />
              <el-table-column prop="goodsPriceLowest" label="价格" align="center" />
              <el-table-column prop="goodsTotalInventory" label="库存总量" align="center" />
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="发送数量" prop="couponSendNumber">
            <div style="display: block;">
              <el-input-number v-model.number="formData.couponSendNumber" controls-position="right" :min="-1" />
              <div class="input-intro">(-1不限制)</div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="显示状态" prop="couponDisplayStatus">
            <el-radio-group v-model="formData.couponDisplayStatus">
              <el-radio v-for="item in  display_status " :key="item.dictValue" :label="parseInt(item.dictValue)">{{
                item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="排序" prop="couponSort">
            <el-input-number v-model.number="formData.couponSort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleEditClick(formRef)" :loading="loadingStatus">编辑</el-button>
        <el-button @click="handleResetClick(formRef)">重置</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择商品 -->
  <ChooseMultipleGoodsDialog v-model="ChooseGoodsDialogVisible" :data="ChooseGoodsDialogRow">
  </ChooseMultipleGoodsDialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import modal from '@/plugins/modal.js'
import { reactive, ref, watch } from "vue";
import { addOrUpdateCoupon } from "@/api/business/Marketing/CouponManage/Coupons/coupon.js";
import ChooseMultipleGoodsDialog from '@/views/business/components/ChooseMultipleGoodsDialog.vue';


// 打开弹窗时回调
const openDialog = async () => {
  await getcoupon_type()
  await getcoupon_expire_type()
  await getapplicable_scope()
  await getdisplay_status()

}

const formData = ref({
  ...props.data,
});
watch(props, async (v) => {
  formData.value = v.data;

});

// 业务参数
// 优惠劵类型字典选项列表
const coupon_type = ref([]);
// 到期类型字典选项列表
const coupon_expire_type = ref([]);
// 适用范围字典选项列表
const applicable_scope = ref([]);
// 显示状态字典选项列表
const display_status = ref([]);
// 选择商品弹窗参数
const ChooseGoodsDialogVisible = ref(false);
const ChooseGoodsDialogRow = ref({});

// -业务方法
//字典获取
async function getcoupon_type() {
  await proxy.getDicts('coupon_type').then((res) => {
    coupon_type.value = res.data
  })
}
//字典获取
async function getcoupon_expire_type() {
  await proxy.getDicts('coupon_expire_type').then((res) => {
    coupon_expire_type.value = res.data
  })
}
//字典获取
async function getapplicable_scope() {
  await proxy.getDicts('applicable_scope').then((res) => {
    applicable_scope.value = res.data
  })
}
//字典获取
async function getdisplay_status() {
  await proxy.getDicts('display_status').then((res) => {
    display_status.value = res.data
  })
}

// 打开选择商品弹窗
const handleChooseGoods = () => {
  ChooseGoodsDialogVisible.value = true
  ChooseGoodsDialogRow.value = formData.value
}



// -基础参数
const props = defineProps({
  modelValue: Boolean,
  data: Object,
  done: Function,
});

const loadingStatus = ref(false)
const labelWidth = 100;
const formRef = ref();
const { proxy } = getCurrentInstance()
const emits = defineEmits(["update:modelValue"]);
const imgData = ref({
  fileDir: "Coupon"
})

// 验证
const rules = reactive({
  couponGuid: [{ required: true, message: "不能为空", trigger: "blur", type: "number" }],
  couponName: [{ required: true, message: "优惠劵名称不能为空", trigger: "blur" }],
  couponDesc: [{ required: true, message: "优惠劵介绍不能为空", trigger: "blur" }],
  couponType: [{ required: true, message: "优惠劵类型不能为空", trigger: "blur", type: "number" }],
  couponMinConsumeMoney: [{ required: true, message: "最低消费金额不能为空", trigger: "blur" }],
  couponExpireType: [{ required: true, message: "到期类型不能为空", trigger: "blur", type: "number" }],
  couponSendNumber: [{ required: true, message: "发送数量(-1不限制)不能为空", trigger: "blur", type: "number" }],
  couponDisplayStatus: [{ required: true, message: "显示状态不能为空", trigger: "blur", type: "number" }],
  couponSort: [{ required: true, message: "排序不能为空", trigger: "blur", type: "number" }],
});

// -基础方法
// 提交
const handleEditClick = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    loadingStatus.value = true

    if (formData.value.couponGoodsIds.length != 0) {
      formData.value.couponGoodsIds = formData.value.couponGoodsIds.join(',')
    }
    if (formData.value.couponApplicableScopeConfig) {
      formData.value.couponApplicableScopeConfig = JSON.stringify(formData.value.couponApplicableScopeConfig)
    }
    if(formData.value.couponFixedTime.length != 0){
      formData.value.couponFixedStartTime = formData.value.couponFixedTime[0]
      formData.value.couponFixedEndTime = formData.value.couponFixedTime[1]
    }

    const { code } = await addOrUpdateCoupon(formData.value);
    if (code == 200) {
      modal.msgSuccess('修改成功')
      closeDialog();
      loadingStatus.value = false
    }
  });
}

const handleResetClick = async (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
}
const closeDialog = () => {
  props.done();
  emits("update:modelValue", false);
};

</script>
