package com.testor.module.fives.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataListResponse;
import com.testor.common.constant.StatusEnum;
import com.testor.common.util.FileUtil;
import com.testor.module.fives.model.domain.TFivesStandard;
import com.testor.module.fives.model.domain.TFivesSubOption;
import com.testor.module.fives.model.dto.TFivesStandardDTO;
import com.testor.module.fives.model.dto.TFivesStandardDelParam;
import com.testor.module.fives.model.dto.TFivesStandardParam;
import com.testor.module.fives.model.dto.TFivesStandardReportDTO;
import com.testor.module.fives.model.vo.TFivesStandardListVO;
import com.testor.module.fives.model.vo.TFivesStandardVO;
import com.testor.module.fives.model.vo.TFivesSubOptionVO;
import com.testor.module.fives.service.TFivesStandardService;
import com.testor.module.fives.service.TFivesSubOptionService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 5s标准验收管理Controller
 *
 * @author testor-framework
 * @date 2022-07-11 14:00:17
 */
@RestController
@RequestMapping("/module/fives/standard")
@Api(value = "TFivesStandard", tags = "5s标准验收管理")
@Slf4j
public class TFivesStandardController extends SuperController {
    @Autowired
    private TFivesStandardService tFivesStandardService;

    @Autowired
    private TFivesSubOptionService tFivesSubOptionService;

    @Value("${ureport.path}")
    private String path;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @ApiOperation(value = "新增 5s标准验收管理", notes = "Add TFivesStandard")
    @PostMapping(value = "/add")
    public BaseResponse<String> addEntity(@RequestBody TFivesStandardDTO addRequest) {
        return tFivesStandardService.add(addRequest);
    }

    @ApiOperation(value = "获取 5s标准验收管理 编辑回显使用 ", notes = "Get TFivesStandard By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TFivesStandardVO> getById(String id) {
        BaseResponse<TFivesStandardVO> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TFivesStandard data = tFivesStandardService.getById(id);
            if (ObjectHelper.isNotEmpty(data)) {
                // 返回对象
                TFivesStandardVO tFivesStandardVO = BeanHelper.beanToBean(data, TFivesStandardVO.class);

                QueryWrapper<TFivesSubOption> levelOneQuery = new QueryWrapper<>();
                levelOneQuery.eq("status", StatusEnum.USE.getCode());
                levelOneQuery.eq("parent_id", id);
                // 内容类型（1-大类；2-小类）
                levelOneQuery.eq("content_type", "1");
                List<TFivesSubOption> levelOne = tFivesSubOptionService.list(levelOneQuery);
                List<TFivesSubOptionVO> resultLevelOne = BeanHelper.listToList(levelOne, TFivesSubOptionVO.class);
                resultLevelOne.forEach(action -> {
                    String levelOneId = action.getId();
                    QueryWrapper<TFivesSubOption> levelTowQuery = new QueryWrapper<>();
                    levelTowQuery.eq("status", StatusEnum.USE.getCode());
                    levelTowQuery.eq("parent_id", id);
                    // 内容类型（1-大类；2-小类）
                    levelTowQuery.eq("content_type", "2");
                    levelTowQuery.eq("sub_id", levelOneId);
                    List<TFivesSubOption> levelTow = tFivesSubOptionService.list(levelTowQuery);
                    List<TFivesSubOptionVO> resultLevelTow = BeanHelper.listToList(levelTow, TFivesSubOptionVO.class);
                    action.setLevelTow(resultLevelTow);
                });
                tFivesStandardVO.setLevelOne(resultLevelOne);
                baseResponse.setData(tFivesStandardVO);
            }
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 5s标准验收管理 ", notes = "Update TFivesStandard By Id")
    @PutMapping(value = "/update")
    public BaseResponse<String> updateEntity(@RequestBody TFivesStandardDTO addRequest) {
        return tFivesStandardService.update(addRequest);
    }

    @ApiOperation(value = "删除 5s标准验收管理 ", notes = "delete TFivesStandard By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<String> deleteEntity(@RequestBody TFivesStandardDelParam deleteRequest) {
        return tFivesStandardService.deleteEntity(deleteRequest);
    }

    /*@ApiOperation(value = "批量删除5s标准验收管理", notes = "delete TFivesStandard by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TFivesStandardDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            *//* 批量删除 *//*
            List<TFivesStandard> tFivesStandardList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TFivesStandard data = new TFivesStandard();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tFivesStandardList.add(data);
            }
            boolean result = tFivesStandardService.updateBatchById(tFivesStandardList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }*/

    @ApiOperation(value = "获取 5s标准验收管理 分页列表", notes = "List TFivesStandard with page")
    @GetMapping(value = "/list")
    public BaseResponse<TFivesStandardListVO> listEntity(TFivesStandardParam param) {
        BaseResponse<TFivesStandardListVO> baseResponse = new BaseResponse<>();
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TFivesStandard> resultPage = new Page<>(page, limit);
        QueryWrapper<TFivesStandard> queryWrapper = this.createQuery(param);
        queryWrapper.select("id", "standard_type", "sub_option", "child", "standard_name", "total_score");
        queryWrapper.orderByDesc("create_date");
        queryWrapper.eq("status", StatusEnum.USE.getCode());

        TFivesStandardListVO tFivesStandardListVO = new TFivesStandardListVO();

        QueryWrapper<TFivesStandard> sumQueryWrapper = this.createQuery(param);
        sumQueryWrapper.select("ifnull(sum(total_score),0) as list_total_score");
        sumQueryWrapper.eq("status", StatusEnum.USE.getCode());
        TFivesStandard one = tFivesStandardService.getOne(sumQueryWrapper);
        String listTotalScore = one.getListTotalScore();

        Page<TFivesStandard> resultList = tFivesStandardService.page(resultPage, queryWrapper);
        BaseResponseList<TFivesStandard> baseResponseList = new BaseResponseList<>();

        Map<String, List<SysDictDataListResponse>> map = new HashMap<>(16);

        List<TFivesStandard> records = resultList.getRecords();

        records.forEach(action -> {

            // 一级
            String standardType = action.getStandardType();
            List<SysDictDataListResponse> levelOne = map.get(standardType);
            action.setStandardType(tFivesStandardService.getDictValue(levelOne, standardType, map, "5S_ACCEPTANCE_STANDARD_TYPE"));

            // 二级
            String subOption = action.getSubOption();
            List<SysDictDataListResponse> levelTow = map.get(subOption);
            String s1 = tFivesStandardService.getDictValue(levelTow, subOption, map, standardType);
            action.setSubOption(s1);

            // 三级
            String child = action.getChild();
            List<SysDictDataListResponse> levelThree = map.get(child);
            String s2 = tFivesStandardService.getDictValue(levelThree, child, map, subOption);
            action.setChild(s2);

        });


        baseResponseList.setData(records);
        baseResponseList.setTotal(resultList.getTotal());

        tFivesStandardListVO.setListTotalScore(listTotalScore);
        tFivesStandardListVO.setBaseResponseList(baseResponseList);

        baseResponse.setData(tFivesStandardListVO);


        return baseResponse;
    }

    /*@ApiOperation(value = "获取 5s标准验收管理 列表", notes = "List TFivesStandard all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TFivesStandard>> listAllEntity(TFivesStandardParam param) {
        BaseResponse<BaseResponseList<TFivesStandard>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TFivesStandard> queryWrapper = this.createQuery(param);
        List<TFivesStandard> resultList = tFivesStandardService.list(queryWrapper);
        BaseResponseList<TFivesStandard> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }*/

    @ApiOperation(value = "5s验收标准导出", notes = "")
    @GetMapping("/exportFiveStandard")
    public void exportFiveStandard(TFivesStandardReportDTO param) throws Exception {
        String url = this.path + "/ureport/excel?_u=file:fivesStandard.ureport.xml";
        String str="";
        String standardName = param.getStandardName();
        if (StrUtil.isNotEmpty(standardName)) {
            str = str + "&standardName=" + standardName;
        }
        String standardType = param.getStandardType();
        if (StrUtil.isNotEmpty(standardType)) {
            str =str+"&standardType=" + standardType;
        }
        String subOption = param.getSubOption();
        if (StrUtil.isNotEmpty(subOption)) {
            str = str + "&subOption=" + subOption;
        }

        String child = param.getChild();
        if (StrUtil.isNotEmpty(child)) {
            str = str + "&child=" + child;
        }
        url=url+str;
        String fileName = "5s验收标准.xlsx";
        FileUtil.downloadHttpFile(url, request, response, fileName);
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TFivesStandard> createQuery(TFivesStandardParam queryParam) {
        QueryWrapper<TFivesStandard> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TFivesStandard.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TFivesStandard.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TFivesStandard.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TFivesStandard.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TFivesStandard.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TFivesStandard.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStandardType())) {
            queryWrapper.eq(TFivesStandard.STANDARD_TYPE, queryParam.getStandardType());
        }
        if (StringHelper.isNotEmpty(queryParam.getStandardName())) {
            queryWrapper.like(TFivesStandard.STANDARD_NAME, queryParam.getStandardName());
        }
        if (StringHelper.isNotEmpty(queryParam.getSubOption())) {
            queryWrapper.eq(TFivesStandard.SUB_OPTION, queryParam.getSubOption());
        }
        if (StringHelper.isNotEmpty(queryParam.getChild())) {
            queryWrapper.eq(TFivesStandard.CHILD, queryParam.getChild());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getTotalScore())) {
            queryWrapper.eq(TFivesStandard.TOTAL_SCORE, queryParam.getTotalScore());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TFivesStandard.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TFivesStandard.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByAsc(TFivesStandard.CREATE_DATE);
        }
        return queryWrapper;
    }
}
