<template>
  <div>
    <el-dialog  v-model="visible" :z-index="99" :title="title" width="100%" align-center fullscreen>
      <el-form :inline="true" :rules="rules" :disabled="method=='look'" :model="modalForm" class="demo-form-inline" ref="ruleFormRef">
        <div class="barbox" style="margin-top: -10px;">
          <div class="bar"></div>
          <div class="name">系统优惠券信息</div>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠卷名称：" prop="coupon_name">
              <el-input v-model="modalForm.coupon_name" style="width: 240px" placeholder="请输入优惠卷名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="使用范围：" prop="application_scope">
              <el-select   @change="changeScope" style="width:240px" v-model="modalForm.application_scope" placeholder="请选择使用范围" clearable>
                        <el-option label="全场通用"  :value="1" />
                        <el-option label="单项" :value="2" />
                        <el-option label="会员" :value="3" />
                    </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券类型：" prop="coupon_type">
              <el-select  @change="changeCouponType" style="width:240px" v-model="modalForm.coupon_type" placeholder="请选择优惠券类型" clearable>
                        <el-option label="无门槛"  :value="1" />
                        <el-option label="满减" :value="2" />
                    </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="有效类型：" prop="valid_type">
              <el-select  @change="changeValidType" style="width:240px" v-model="modalForm.valid_type" placeholder="请选择有效类型" clearable>
                        <el-option label="绝对时效"  :value="1" />
                        <el-option label="相对时效" :value="2" />
                    </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" >
            <el-form-item label="是否互斥：" prop="is_mutex">
              <el-select style="width:240px" v-model="modalForm.is_mutex" placeholder="请选择是否互斥" clearable>
                        <el-option label="否"  :value="0" />
                        <el-option label="是"  :value="1" />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" >
            <el-form-item label="优惠卷金额：" prop="coupon_price">
              <el-input v-model.number="modalForm.coupon_price" style="width: 240px" placeholder="请输入优惠卷金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发放对象：" prop="distribution_object">
              <el-select style="width:240px" v-model="modalForm.distribution_object" placeholder="请选择发放对象" clearable>
                <!-- 1:全部用户 2:新注册用户 3:会员 4:完善资料 -->
                      <el-option label="全部用户"  :value="1" />
                      <el-option label="新注册用户"  :value="2" />
                      <el-option label="会员"  :value="3" />
                      <el-option label="完善资料"  :value="4" />
                      
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" v-if="showCouponDesc">
            <el-form-item label="满减条件金额：" prop="with_amount" :rules="[
              {
                required: true,
                message: '请输入满减条件金额',
                trigger: 'blur'
              },
              {
                type: 'number',
                message: '请输入数字',
                trigger: 'blur'
              }
            ]">
              <el-input v-model.number="modalForm.with_amount" style="width: 240px" placeholder="请输入满减条件金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8"  v-if="showCouponCount">
            <el-form-item label="发放数量：" prop="coupon_count" :rules="[
              {
                required: true,
                message: '请输入发放数量',
                trigger: 'blur'
              },
              {
                type: 'number',
                message: '请输入数字',
                trigger: 'blur'
              }
            ]">
              <el-input v-model.number="modalForm.coupon_count" style="width: 240px" placeholder="请输入发放数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="showValidDays">
            <el-form-item label="有效天数：" prop="valid_days">
               <el-input v-model.number="modalForm.valid_days" style="width: 240px" placeholder="请输入有效天数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="showValidDate">
          <el-col :span="8">
            <el-form-item label="有效时间：" prop="">
              <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss"  :disabled-date="disabledDateFn" format="YYYY-MM-DD HH:mm:ss" @change="confirmDate" />

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="modalForm.application_scope==3">
          <el-col :span="8">
            <el-form-item label="适用会员时间：" prop="system_member_ids" :rules="[
              {
                required: true,
                message: '请选择适用会员时间',
                trigger: 'blur'
              }]">
              <el-select multiple value-key="system_member_id" style="width:240px" v-model="modalForm.system_member_ids" placeholder="请选择适用会员类型" clearable>
                        <el-option :label="formatDay(item.member_days)"  :value="item.system_member_id" v-for="item in vipList"/>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
      <div class="barbox">
        <div class="bar"></div>
        <div class="name">操作</div>
      </div>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="" style="padding-left:30px">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="submit(ruleFormRef)">
              确定
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
     

      <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </div>
    </template> -->
    </el-dialog>
    <el-dialog v-model="dialogVisible" title="温馨提示" width="400">
      <span>确定取消该订单？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { onBeforeMount, reactive, ref, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import userApi from "../api/user";
import { ElMessage } from "element-plus";
import { formatOrderStatus, formatRefundStatus, formatDate } from '../utils/format'

const ruleFormRef = ref(null);
const method=ref(null);
const dateRange=ref(['','']);
const emit=defineEmits(['refreshList']);
const modalForm = reactive({
  is_mutex:1
})
const vipList = ref([]);
const showValidDays = ref(false);
const showValidDate = ref(false);
const showCouponDesc=ref(false);
const showCouponCount=ref(false);
const rules = reactive({
  coupon_name:[
    {
      required: true,
      message: '请输入优惠卷名称',

      trigger: 'blur',
    }
  ],
  coupon_type:[
    {
      required: true,
      message: '请选择优惠卷类型',

      trigger: 'blur',
    }
  ],
  application_scope:[
    {
      required: true,
      message: '请选择使用范围',


      trigger: 'blur',
    }
  ],
  distribution_object:[
    {
      required: true,
      message: '请选择发放对象',
      trigger: 'change',
    }
  ],
  application_scope:[
    {
      required: true,
      message: '请选择使用范围',


      trigger: 'blur',
    }
  ],
  is_mutex:[
    {
      required: true,
      message: '请选择是否互斥',


      trigger: 'blur',
    }
  ],
  valid_type:[
    {
      required: true,
      message: '请输入有效类型',

      trigger: 'blur',

   },
  
    {
      type: 'number',
      message: '请输入数字',
      trigger: 'blur'
    }
  ],
  coupon_price:[
    {
      required: true,
      message: '请输入优惠卷金额',
      trigger: 'blur',

   },
  
    {
      type: 'number',
      message: '请输入数字',
      trigger: 'blur'
    }
  ],
 
});
const disabledDateFn = (time) => {
    return time.getTime() < Date.now() - 8.64e7;
}
const formatDay=(val)=>{
  if(val==365){
    return '1年'
  }else if(val>=30){
    return val/30+'个月'
  }else{
    return val+'天'
  }
}
const confirmDate=  (val) => {
  console.log(val);
    if(val && val[0] && val[1]){
      modalForm.valid_start_time=val[0];
      modalForm.valid_end_time=val[1];
    }else{
      delete modalForm.valid_start_time;
      delete modalForm.valid_end_time;
    }
}
const changeValidType=(val) => {
  showValidDate.value = false;
  showValidDays.value =false;
  modalForm.system_member_ids=null;
   if(val==1){
     showValidDate.value = true;
     delete modalForm.valid_days;
   }else if(val==2){
     showValidDays.value = true;
     delete modalForm.valid_start_time;
     delete modalForm.valid_end_time;
   }else{
    delete modalForm.valid_start_time;
    delete modalForm.valid_end_time;
    delete modalForm.valid_days;
   }
}
const getVipList = async () => {
    const res = await userApi.getVipSettingList();
    console.log(res.data);
    vipList.value = res.data;
}
const changeCouponType=(val) => {
  showCouponDesc.value = false;
  showCouponCount.value =false;
  if(val==1){
    delete modalForm.with_amount;
   showCouponCount.value =true;
 }else if(val==2){
  delete modalForm.coupon_count;
  showCouponDesc.value =true;
  
 }else{
   delete modalForm.coupon_count;
   delete modalForm.with_amount;
 }
}
const changeScope=(val) => {
  if(val!=3){
    delete modalForm.system_member_ids;
  }
}
const handleAdd = () => {
  if(!modalForm.coupon_id){
    delete modalForm.coupon_id
  }
  userApi.saveSysCoupon(modalForm).then((res) => {
    let result = res;
   
    if (result.code == 200) {
        ElMessage.success("添加成功");
        visible.value = false;
        emit('refreshList')
    }

  })
};
const handleEdit = () => {
  userApi.editSysCoupon(modalForm.coupon_id,modalForm).then((res) => {
    let result = res;
   
    if (result.code == 200) {
        ElMessage.success("修改成功");
        visible.value = false;
        emit('refreshList')
    }

  })
};


const submit = async(form) => {
  await form.validate((valid, fields) => {
    if (valid) {
      method.value === 'edit'?handleEdit() : handleAdd()
    } else {
      console.log('error submit!', fields)
    }
 
  });
}
const visible = ref(false);
const dialogVisible = ref(false);
const title = ref('订单详情')
const route = useRoute();
const router = useRouter();


const cancelOrder = () => {

};
const confirmCancel = () => {
  dialogVisible.value = false;
  cancelOrder()

}

const init = (type, id) => {
  visible.value = true;
  method.value = type;
  modalForm.coupon_id = id;
  delete modalForm.valid_start_time;
  delete modalForm.valid_end_time;
  dateRange.value=[];
  showValidDate.value = false;
  showValidDays.value =false;
  delete modalForm.valid_days;
  delete modalForm.with_amount;
  showCouponDesc.value = false;
  delete modalForm.coupon_count;
  showCouponCount.value =false;
  if (method.value === 'edit') {
    title.value = '编辑系统优惠券配置'
  } else if (method.value === 'view') {
    title.value = '新建系统优惠券配置'
  }else if (method.value === 'look') {
    title.value = '查看系统优惠券配置'
  }
  getVipList();
  nextTick(() => {
    ruleFormRef.value.resetFields();
    modalForm.discount_end_time = '';
    if (method.value === 'edit' || method.value === 'look') {
      userApi.getSysCouponDetail(modalForm.coupon_id).then((res) => {
        let result = res.data;
        Object.assign(modalForm, result);
        changeCouponType(modalForm.coupon_type);
        changeValidType(modalForm.valid_type);
        // modalForm.valid_start_time = modalForm.valid_start_time ?modalForm.valid_start_time : '';
        // modalForm.valid_end_time = modalForm.valid_end_time ?modalForm.valid_end_time : '';
        dateRange.value = [modalForm.valid_start_time, modalForm.valid_end_time]
      })
    }
  })

}

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.barbox {
  margin: 10px 0;
  display: flex;
  align-items: center;

  .bar {
    width: 4px;
    height: 25px;
    background: var(--el-color-primary);
  }

  .name {
    margin-left: 8px;
    font-size: 16px;
  }
}
</style>