package com.xjrsoft.module.evaluate.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.module.evaluate.dto.AddEvaluateTemplateDto;
import com.xjrsoft.module.evaluate.dto.EvaluateTemplatePageDto;
import com.xjrsoft.module.evaluate.dto.UpdateEvaluateTemplateDto;
import com.xjrsoft.module.evaluate.dto.UpdateEvaluateTemplateStatusDto;
import com.xjrsoft.module.evaluate.entity.EvaluateTemplate;
import com.xjrsoft.module.evaluate.service.IEvaluateTemplateService;
import com.xjrsoft.module.evaluate.vo.EvaluateTemplatePageVo;
import com.xjrsoft.module.evaluate.vo.EvaluateTemplateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @title: 评价模版
* @Author szs
* @Date: 2024-01-15
* @Version 1.0
*/
@RestController
@RequestMapping("/evaluationmanagemen" + "/evaluateTemplate")
@Api(value = "/evaluationmanagemen"  + "/evaluateTemplate",tags = "评价模版代码")
@AllArgsConstructor
public class EvaluateTemplateController {


    private final IEvaluateTemplateService evaluateTemplateService;

    @GetMapping(value = "/page")
    @ApiOperation(value="评价模版列表(分页)")
    @SaCheckPermission("evaluatetemplate:detail")
    public RT<PageOutput<EvaluateTemplatePageVo>> page(@Valid EvaluateTemplatePageDto dto){
        Page<EvaluateTemplatePageVo> page = evaluateTemplateService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<EvaluateTemplatePageVo> pageOutput = ConventPage.getPageOutput(page, EvaluateTemplatePageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询评价模版信息")
    @SaCheckPermission("evaluatetemplate:detail")
    public RT<EvaluateTemplateVo> info(@RequestParam Long id){
        EvaluateTemplateVo evaluateTemplateVo = evaluateTemplateService.getInfo(id);
        if (evaluateTemplateVo == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(evaluateTemplateVo);
    }


    @PostMapping
    @ApiOperation(value = "新增评价模版")
    @SaCheckPermission("evaluatetemplate:add")
    public RT<Boolean> add(@Valid @RequestBody AddEvaluateTemplateDto dto){
        //处理入参中的deptIds
        //如果传过来的字符串中含有0(通用)，其他的可以不需要了
        if(dto.getDeptIds() != null && !dto.getDeptIds().equals("")){
            String[] deptIdStrArr = dto.getDeptIds().split(",");
            for (String  deptIdStr: deptIdStrArr) {
                if(deptIdStr.equals("0")){
                    dto.setDeptIds("0");
                    break;
                }
            }
        }
        //加上中括号
        String deptIds = "[" + dto.getDeptIds() + "]";
        dto.setDeptIds(deptIds);

        EvaluateTemplate evaluateTemplate = BeanUtil.toBean(dto, EvaluateTemplate.class);
        evaluateTemplate.setCreateDate(new Date());
        QueryWrapper<EvaluateTemplate> queryWrapperSortcode = new QueryWrapper<>();
        queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
        EvaluateTemplate e = evaluateTemplateService.getOne(queryWrapperSortcode);
        evaluateTemplate.setSortCode(e.getSortCode() + 1);
        evaluateTemplate.setStatus(1);
        boolean isSuccess = evaluateTemplateService.save(evaluateTemplate);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改评价模版")
    @SaCheckPermission("evaluatetemplate:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateEvaluateTemplateDto dto){
        String deptIds = "[" + dto.getDeptIds() + "]";
        dto.setDeptIds(deptIds);
        EvaluateTemplate evaluateTemplate = BeanUtil.toBean(dto, EvaluateTemplate.class);
        evaluateTemplate.setModifyDate(new Date());
        evaluateTemplate.setModifyUserId(StpUtil.getLoginIdAsLong());
        return RT.ok(evaluateTemplateService.updateById(evaluateTemplate));

    }

    @DeleteMapping
    @ApiOperation(value = "删除评价模版")
    @SaCheckPermission("evaluatetemplate:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(evaluateTemplateService.removeBatchByIds(ids));

    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid EvaluateTemplatePageDto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) {
        List<EvaluateTemplatePageVo> customerList = isTemplate != null && isTemplate ? new ArrayList<>() : ((PageOutput<EvaluateTemplatePageVo>) page(dto).getData()).getList();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, EvaluateTemplatePageVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);

        return RT.fileStream(bot.toByteArray(), "EvaluateTemplate" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping(value = "/change-status")
    @ApiOperation(value="修改状态")
    @SaCheckPermission("evaluatemanage:edit")
    public RT<Boolean> changeStatus(@Valid @RequestBody UpdateEvaluateTemplateStatusDto dto){
        Boolean release = evaluateTemplateService.changeStatus(dto);
        return RT.ok(release);
    }
}