package com.xjrsoft.module.form.controller;

import cn.hutool.core.bean.BeanUtil;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.form.entity.FormHistory;
import com.xjrsoft.module.form.entity.FormTemplate;
import com.xjrsoft.module.form.service.IFormHistoryService;
import com.xjrsoft.module.form.vo.FormHistoryListVo;
import com.xjrsoft.module.form.vo.FormTemplateVo;
import com.xjrsoft.module.organization.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 自定义表单历史表  每次修改自定义表单会新增一条数据 前端控制器
 * </p>
 *
 * @author tzx
 * @since 2022-05-09
 */
@RestController
@RequestMapping(GlobalConstant.FORM_MODULE_PREFIX + "/history")
@Api(value = GlobalConstant.FORM_MODULE_PREFIX + "/history", tags = "自定义表单历史表")
@AllArgsConstructor
public class FormHistoryController {

    private final IFormHistoryService formHistoryService;

    @GetMapping(value = "/list")
    @ApiOperation(value = "历史记录")
    @XjrLog(value = "自定义表单历史记录")
    public R list(@RequestParam Long formId) {

        List<FormHistoryListVo> formHistoryListVos = formHistoryService.selectJoinList(FormHistoryListVo.class,
                MPJWrappers.<FormHistory>lambdaJoin()
                        .eq(FormHistory::getFormId, formId)
                        .select(FormHistory::getId)
                        .select(FormHistory.class, x -> VoToColumnUtil.fieldsToColumns(FormHistoryListVo.class).contains(x.getProperty()))
                        .selectAs(User::getName, FormHistoryListVo::getCreateUserName)
                        .leftJoin(User.class, User::getId, FormHistory::getCreateUserId)
                        .orderByDesc(FormTemplate::getCreateDate)
        );

        List<FormHistoryListVo> listVos = BeanUtil.copyToList(formHistoryListVos, FormHistoryListVo.class);
        return R.ok(listVos);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "表单设计模板详情")
    @XjrLog(value = "表单设计模板详情")
    public R info(@RequestParam Long id) {
        FormHistory history = formHistoryService.getById(id);
        if (history == null) {
            return R.error("找不到此数据！");
        }
        return R.ok(BeanUtil.toBean(history, FormTemplateVo.class));
    }

}
