<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" label-width="100px">
            <el-form-item label="积分激励名称" prop="rewardName">
              <el-input v-model="queryParams.rewardName" placeholder="请输入积分激励名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="激励创建时间" prop="createMotivateTime" style="width: 330px">
              <el-date-picker
                clearable
                v-model="queryParams.createMotivateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" clearable>
                <el-option v-for="(label, value) in statusOptions" :key="value" :label="label" :value="value" />
              </el-select>
            </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>

        <el-card shadow="never" class="mt-[10px]">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="8">
                <el-button type="primary" @click="handleAdd(null, 'add')">新增激励</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="extractLogList">
            <el-table-column label="序号" width="50px" type="index"></el-table-column>
            <el-table-column
              :label="label"
              :align="align || 'center'"
              prop="rewardName"
              :min-width="minWidth || '100px'"
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
            >
              <template #default="{ row }">
                <span v-if="prop == 'rewardName'" @click="handleAdd(row, 'detail')" class="show-detail">
                  {{ row[prop] || '-' }}
                </span>
                <span v-else-if="prop == 'rewardType'">
                  {{ typeOptionsObj[row.rewardType] || '-' }}
                </span>
                <span v-else-if="prop == 'rewardUntil'">
                  {{ row.isForever == 1 ? '永久' : row.rewardUntil || '-' }}
                </span>
                <span v-else-if="prop == 'status'">
                  <el-switch v-model="row[prop]" :active-value="1" :inactive-value="0" @change="changeStatus(row)"> </el-switch>
                </span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="120px" fixed="right" class-name="small-padding fixed-width">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleAdd(row, 'edit')">编辑</el-button>
                <el-button link type="danger" @click="handleDel(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" :total="page.total" v-model:page="page.pageNum" v-model:limit="page.pageSize" @pagination="getList" />
        </el-card>
        <el-dialog :title="title" v-model="dialog.visible" width="600px" :before-close="CloseDialog">
          <el-form :model="dialog.form" ref="dialogFormRef" :rules="dialog.rules" label-width="120px" :inline="false">
            <el-form-item label="激励规则名称：" prop="rewardName">
              <div v-if="dialogType == 'detail'">
                {{ dialog.form.rewardName || '-' }}
              </div>
              <el-input v-else v-model="dialog.form.rewardName" placeholder="请输入激励规则名称"></el-input>
            </el-form-item>
            <el-form-item label="激励类型：" prop="rewardType">
              <div v-if="dialogType == 'detail'">
                {{ typeOptionsObj[dialog.form.rewardType] || '-' }}
              </div>
              <el-select v-else v-model="dialog.form.rewardType" placeholder="请选择激励类型">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="激励规则：" :rules="{ required: true }">
<!--              <div v-if="dialogType == 'detail'">
                {{ ruleTypeOptionsObj[dialog.form.rewardObj] || '-' }}{{ ruleTypeOptionsObj[dialog.form.effectFlag] || '-'
                }}{{ dialog.form.effectStandard || '-' }}
              </div>-->
              <div v-if="dialogType == 'detail'">
                {{ ruleTypeOptionsObj?.[dialog.form.rewardObj] || '-' }}
                {{ (ruleSymbolOptions?.find(opt => opt.value == dialog.form.effectFlag)?.label) || '-' }}
                {{ dialog.form.effectStandard ?? '-' }}
              </div>


              <div v-else class="flex gap-[10px] flex-1">
                <el-form-item label="" prop="rewardObj" class="flex-1">
                  <el-select v-model="dialog.form.rewardObj" placeholder="请选择规则类型">
                    <el-option v-for="item in ruleTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" prop="effectFlag" class="flex-1">
                  <el-select v-model="dialog.form.effectFlag" placeholder="请选择规则计算符号">
                    <el-option v-for="item in ruleSymbolOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" prop="effectStandard" class="flex-1">
                  <el-input v-model="dialog.form.effectStandard" placeholder="请输入规则值"></el-input>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="激励内容：" prop="rewardContent">
              <div v-if="dialogType == 'detail'">
                {{ dialog.form.rewardContent || '-' }}
              </div>
              <el-input v-else v-model="dialog.form.rewardContent" placeholder="请输入激励内容"></el-input>
            </el-form-item>
            <el-form-item label="激励截止时间：" prop="rewardUntil">
              <div v-if="dialogType == 'detail'">
                {{ dialog.form.rewardUntil || '-' }}
              </div>
              <div v-else class="flex flex-align-center flex-1 gap-[10px]">
                <el-date-picker
                  :disabled="dialog.form.isForever"
                  v-model="dialog.form.rewardUntil"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间"
                  class="flex-1"
                >
                </el-date-picker>
                <el-checkbox v-model="dialog.form.isForever" @change="setPermanent">永久</el-checkbox>
              </div>
            </el-form-item>
            <div v-if="dialogType == 'detail'">
              <el-form-item label="激励创建时间：">
                {{ dialog.form.createTime || '-' }}
              </el-form-item>
              <el-form-item label="创建人：">
                {{ dialog.form.createBy || '-' }}
              </el-form-item>
            </div>
          </el-form>
          <template #footer>
            <span>
              <el-button @click="CloseDialog">取消</el-button>
              <el-button type="primary" v-if="dialogType != 'detail'" @click="confirmSave">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getTableList, deleteMotivate, addMotivate, updateMotivate, setStatus } from '@/api/points/motivate';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { operate_code } = toRefs<any>(proxy?.useDict('operate_code'));
const operateCode = computed(() => operate_code.value);
const { point_reward_type } = toRefs<any>(proxy?.useDict('point_reward_type'));
const pointRewardType = computed(() => point_reward_type.value);
const extractLogList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '积分激励名称',
    prop: 'rewardName'
  },
  {
    label: '激励类型',
    prop: 'rewardType'
  },
  {
    label: '激励内容',
    prop: 'rewardContent'
  },
  {
    label: '激励创建时间',
    prop: 'createTime'
  },
  {
    label: '激励截止时间',
    prop: 'rewardUntil'
  },
  {
    label: '状态',
    prop: 'status'
  }
]);

const statusOptions = {
  0: '停用',
  1: '启用'
};
const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  rewardName: '',
  status: '',
  createMotivateTime: []
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  let startDate = queryParams.value.createMotivateTime[0] || '';
  let endDate = queryParams.value.createMotivateTime[1] || '';
  const res = await getTableList({ ...queryParams.value, ...page.value, startDate, endDate });
  extractLogList.value = res.data;
  page.value.total = res.total;
  loading.value = false;
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const formObj = {
  id: '',
  rewardName: '',
  rewardType: '',
  rewardObj: 1,
  effectFlag: '',
  effectStandard: 0,
  rewardContent: '',
  rewardUntil: '',
  isForever: false,
  status: 1,
  createTime: null,
  createBy: null
};
const dialog = ref({
  visible: false,
  form: {
    ...formObj
  },
  rules: {
    rewardName: [{ required: true, message: '请输入激励规则名称', trigger: 'blur' }],
    rewardType: [{ required: true, message: '请选择激励类型', trigger: 'blur' }],
    rewardObj: [{ required: true, message: '请选择激励规则类型', trigger: 'blur' }],
    effectFlag: [{ required: true, message: '请选择激励规则符号', trigger: 'blur' }],
    effectStandard: [{ required: true, message: '请输入激励规则值', trigger: 'blur' }],
    rewardContent: [{ required: true, message: '请输入激励内容', trigger: 'blur' }],
    rewardUntil: [
      {
        required: true,
        validator: (_: any, value: any, callback: any) => {
          if (!dialog.value.form.isForever && !value) {
            return callback(new Error('请选择激励结束时间'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});
const typeOptions = computed(() => pointRewardType.value);
const typeOptionsObj = computed(() => {
  const obj: any = {};
  typeOptions.value.forEach((item: any) => {
    obj[item.value] = item.label;
  });
  return obj;
});
const ruleTypeOptions = computed(() => [
  {
    label: '积分',
    value: 1
  }
]);
const ruleTypeOptionsObj = computed(() => {
  const obj: any = {};
  ruleTypeOptions.value.forEach((item: any) => {
    obj[item.value] = item.label;
  });
  return obj;
});
/*const ruleSymbolOptions = computed(() => operateCode.value);*/
const ruleSymbolOptions = [
  { label: '>', value: 1 },
  { label: '<', value: 2 },
  { label: '=', value: 3 }
];

const setPermanent = () => {
  if (dialog.value.form.isForever) {
    dialog.value.form.rewardUntil = '';
  }
};
const dialogFormRef = ref(null);
const CloseDialog = () => {
  dialog.value.form = formObj;
  dialogFormRef.value.resetFields();
  dialog.value.visible = false;
};
const activeRow = ref(null);
const dialogType = ref('add');
const title = computed(() => {
  return {
    add: '新增',
    edit: '编辑',
    detail: '详情'
  }[dialogType.value];
});
const handleAdd = async (row:any, type:any) => {
  activeRow.value = row;
  dialogType.value = type;
  dialog.value.visible = true;
  if (type != 'add') {
    await proxy?.$nextTick();
    dialog.value.form = {
      ...dialog.value.form,
      rewardName: row.rewardName,
      rewardType: `${row.rewardType}`,
      rewardObj: row.rewardObj,
      effectFlag: row.effectFlag,
      effectStandard: +row.effectStandard,
      rewardContent: row.rewardContent,
      rewardUntil: row.rewardUntil,
      isForever: row.isForever == 1
    };
    if (type == 'detail') {
      if (row.isForever == 1) {
        dialog.value.form.rewardUntil = '永久';
      } else {
        dialog.value.form.rewardUntil = row.rewardUntil;
      }
      dialog.value.form.createTime = row.createTime;
      dialog.value.form.createBy = row.createBy;
    } else {
      if (row.isForever == 1) {
        dialog.value.form.rewardUntil = '';
      } else {
        dialog.value.form.rewardUntil = row.rewardUntil;
      }
    }
  }
};
const confirmSave = () => {
  dialogFormRef.value.validate(async (valid:any) => {
    if (!valid) return;
    ElMessageBox.confirm(`是否确定${dialogType.value == 'add' ? '新增' : '编辑'}积分激励？`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let ajax = dialogType.value === 'add' ? addMotivate : updateMotivate;
        let params = {
          ...dialog.value.form,
          isForever: dialog.value.form.isForever ? 1 : 0
        };
        if (dialogType.value === 'edit') {
          params.id = activeRow.value.id;
        }
        const res = await ajax(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          return;
        }
        ElNotification({
          title: '提示',
          message: `${dialogType.value == 'add' ? '新增' : '编辑'}成功`,
          type: 'success'
        });
        CloseDialog();
        await getList();
      })
      .catch(() => {});
  });
};
const handleDel = async (row: any) => {
  ElMessageBox.confirm(`是否确定删除该积分激励？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteMotivate(row.id);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '删除成功',
        type: 'success'
      });
      await getList();
    })
    .catch(() => {});
};
const changeStatus = async (row: any) => {
  const params = {
    id: row.id,
    status: row.status
  };
  const res = await setStatus(params);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  ElNotification({
    title: '提示',
    message: '修改状态成功',
    type: 'success'
  });
  await getList();
};
onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.show-detail {
  cursor: pointer;
  color: var(--el-color-primary);
}
</style>
