<template>
  <div class="p-2">
    <!-- <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition> -->

    <el-table v-loading="loading" :data="mkConfigList" @selection-change="handleSelectionChange">
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="参与人数" align="center" prop="joinCount">
        <template #default="scope">
          <el-button link type="primary" @click="handleJoin(scope.row)">{{ scope.row.joinCount }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="获奖人数" align="center" prop="awardCount">
        <template #default="scope">
          <el-button link type="primary" @click="handleAward(scope.row)">{{ scope.row.awardCount }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" prop="">
        <template #default="scope">
          <el-button link type="primary" @click="handleAward(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status == 0 ? '未发布' : '已发布' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['manage:mkConfig:edit']"></el-button>
          </el-tooltip>
          <el-button link type="primary" @click="handleStatus(scope.row,'1')" v-if="scope.row.status == 0"
            v-hasPermi="['manage:mkConfig:edit']">发布</el-button>
          <el-button link type="primary" @click="handleStatus(scope.row,'0')" v-if="scope.row.status == 1"
            v-hasPermi="['manage:mkConfig:edit']">撤销发布</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    <!-- 每日任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <div v-if="queryParams.type == '0'" style="height: 400px;overflow-y: auto;">
        <el-form ref="mkConfigFormRef" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="每日封顶积分：" prop="name">
            <el-input style="width: 150px;" type="number" v-model="form.dailyConfig.dailyLimit" placeholder="请输入积分">
              <template #append>分</template>
            </el-input>
          </el-form-item>
          <el-row v-for="(item, index) in form.dailyConfig.dailyReward" :key="index" :gutter="10"
            style="margin-bottom: 10px; margin-right: 5px !important">
            <el-col :span="11">
              <el-form-item :label="`奖励${index + 1}：`" prop="">
                <el-select v-model="item.rewardType" placeholder="请选择" style="width: 150px">
                  <el-option label="服务" :value="1"></el-option>
                  <el-option label="商品" :value="2"></el-option>
                  <el-option label="商品2" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="所需积分：">
                <el-input style="width: 100px;" v-model="item.rewardNum" type="number" placeholder="请输入积分"
                  class="no-arrows">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <vxe-button mode="text" v-if="index == 0" icon="vxe-icon-add" class="handle_btn add_btn"
                @click="amendDailyReward(index,'add')"></vxe-button>
              <vxe-button mode="text" v-else icon="vxe-icon-minus" class="handle_btn rem_btn"
                @click="amendDailyReward(index,'remove')"></vxe-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 大转盘弹层 -->
      <div v-else style="height: 400px;overflow-y: auto;">
        <el-form ref="dzpFormRef" :model="form" :rules="rules" label-width="70px">
          <el-row v-for="(item, index) in form.roundConfig" :key="index" :gutter="10"
            style="margin-bottom: 10px; margin-right: 5px !important">
            <el-col :span="14">
              <el-form-item :label="`奖品${index + 1}：`" prop="">
                <el-select v-model="item.rewardType" placeholder="请选择" style="width: 120px">
                  <el-option label="服务" :value="1"></el-option>
                  <el-option label="商品" :value="2"></el-option>
                  <el-option label="商品2" :value="3"></el-option>
                </el-select>
                <span style="margin: 0px 10px;"> + </span>
                <el-select v-model="item.goodsId" placeholder="请选择" style="width: 120px">
                  <el-option label="服务" :value="1"></el-option>
                  <el-option label="商品" :value="2"></el-option>
                  <el-option label="商品2" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="获奖概率：" label-width="95px">
                <el-input style="width: 100px;" v-model="item.rewardNum" type="number" placeholder="请输入概率"
                  class="no-arrows">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <vxe-button mode="text" v-if="index == 0" icon="vxe-icon-add" class="handle_btn add_btn"
                @click="amendRoundConfig(index,'add')"></vxe-button>
              <vxe-button mode="text" v-else icon="vxe-icon-minus" class="handle_btn rem_btn"
                @click="amendRoundConfig(index,'remove')"></vxe-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 获奖人员 -->
    <el-dialog title="获奖人员" v-model="mkReward.visible" width="600px" append-to-body>
      <div>
        <el-table :data="mkRewardUserLists" border style="width: 100%">
          <el-table-column prop="userId" label="用户ID" width="180" />
          <el-table-column prop="nickName" label="昵称" width="170" />
          <el-table-column prop="" label="获得奖品" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="">查看详情</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="" label="邀请人数" width="80">
            <template #default="scope">
              <el-button link type="primary" @click="">{{ scope.row.inviteCount }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MkConfig" lang="ts">
import { listMkConfig, getMkConfig, delMkConfig, addMkConfig, updateMkConfig,mkRewardUserList } from '@/api/manage/mkConfig';
import { MkConfigVO, MkConfigQuery, MkConfigForm } from '@/api/manage/mkConfig/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const mkConfigList = ref<MkConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const taskList = ref<Array<string | number>>([]); //每日任务弹层明细
const queryFormRef = ref<ElFormInstance>();
const mkConfigFormRef = ref<ElFormInstance>();
const dzpFormRef = ref<ElFormInstance>();
const mkReward= reactive({
  visible: false,
})
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const mkRewardUserParams = reactive({
  pageNum: 1,
  pageSize: 10,
  bizId:null,
})
const initFormData: MkConfigForm = {
  id: undefined,
  name: undefined,
  type: undefined,
  status: undefined,
  rewardConfig: undefined,
  joinCount: undefined,
  awardCount: undefined,
  dailyConfig: {
    dailyLimit: undefined,
    dailyReward: []
  },
  roundConfig: undefined,
}
const data = reactive<PageData<MkConfigForm, MkConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    type: undefined,
    status: undefined,
    rewardConfig: undefined,
    joinCount: undefined,
    awardCount: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
// 路由监听================================================
let router = useRouter();
watch(
  () => router.currentRoute.value,
  () => {
    let query = router.currentRoute.value.query;
    if (query) {
      queryParams.value.type = query.type as string;
    }
    console.log('路由信息：', router.currentRoute.value);
  },
  { immediate: true }
);
/** 查询营销配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMkConfig(queryParams.value);
  mkConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  mkReward.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  mkConfigFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MkConfigVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加营销配置";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MkConfigVO) => {
  reset();
  const _id = row?.id
  const res = await getMkConfig(_id);
  Object.assign(form.value, res.data);
  form.value.id=_id;
  dialog.title = `${queryParams.value.type == '1' ? '大转盘' : '每日任务'}`;
  dialog.visible = true;
}

/** 提交按钮 */
const submitForm = () => {
  if (queryParams.value.type == '0'){//每日奖励
    mkConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await updateMkConfig(form.value).finally(() =>  buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
  }else{ //大转盘
    let roundConfig_copy=[];
    for (let i = 0; i < form.value.roundConfig.length; i++) {
      const element = form.value.roundConfig[i];
      if (element.rewardType&&element.goodsId&&element.rewardNum) {
        roundConfig_copy.push(element);
      }else{
        proxy?.$modal.msgError(`奖品${i+1}配置不完整`);
        return
      }
    }
    dzpFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await updateMkConfig(form.value).finally(() =>  buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
    });
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: MkConfigVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除营销配置编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delMkConfig(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('manage/mkConfig/export', {
    ...queryParams.value
  }, `mkConfig_${new Date().getTime()}.xlsx`)
}

/**
 * 获取获奖人员列表
 * @param row 
 */
const mkRewardUserLists=ref([]);
const handleAward = async (row: any) => {
  loading.value = true;
  mkRewardUserParams.bizId = row.id;
  const res = await mkRewardUserList(mkRewardUserParams).finally(() => loading.value = false);
  mkRewardUserLists.value= res.rows;
  mkReward.visible = true;

  // dialog.title = "修改营销配置";
}
// 发布  撤销发布
const handleStatus = async (row: any,type:string) => {
  await proxy?.$modal.confirm('是否确认' + (type == '0' ? '撤销发布' : '发布') + '名称为"' + row.name + '"的数据项？');
  loading.value = true;
  row.status = type;
  const res = await updateMkConfig(row).finally(() =>  loading.value = false);
  proxy?.$modal.msgSuccess("操作成功");
  await getList();
}
// 新增 删除每日任务奖励
const amendDailyReward= async (index:number,type:string) => {
  if (type=='add') {
    form.value.dailyConfig.dailyReward.push({
      rewardNum:null,
      rewardType:null
    }
    )
  }else{
    form.value.dailyConfig.dailyReward.splice(index,1)
  }
}
/**
 * 添加 删除大转盘奖品项
 * @param index 
 * @param type 
 */
const amendRoundConfig= async (index:number,type:string) => {
  if (type=='add') {
    form.value.roundConfig.push({
      goodsId: null,
      rewardNum:null,
      rewardType:null
    })
  }else{
    form.value.roundConfig.splice(index,1)
  }
}
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.handle_btn {
  cursor: pointer;
  border-radius: 5px;
  padding: 0px 10px;
}

.add_btn {
  color: #1296db;
  border: 1px solid #1296db;
}

.rem_btn {
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

/* 去掉input的上下箭头 */
:deep(.no-arrows input::-webkit-inner-spin-button),
:deep(.no-arrows input::-webkit-outer-spin-button) {
  -webkit-appearance: none !important;
}

:deep(.no-arrows input[type='number']) {
  -moz-appearance: textfield;
}

:deep(.el-input-group__append) {
  padding: 0px 10px;
}
</style>