package com.testor.module.regime.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.regime.model.domain.TRegimeData;
import com.testor.module.regime.model.dto.ReturnReleaseUnit;
import com.testor.module.regime.model.dto.TRegimeDataDelParam;
import com.testor.module.regime.model.dto.TRegimeDataListVo;
import com.testor.module.regime.model.dto.TRegimeDataParam;
import com.testor.module.regime.service.TRegimeDataService;
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.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 制度资料管理Controller
 *
 * @author testor-framework
 * @date 2022-07-01 14:14:14
 */
@RestController
@RequestMapping("/regime")
@Api(value = "TRegimeData", tags = "制度资料管理")
@Slf4j
public class TRegimeDataController extends SuperController {
    @Autowired
    private TRegimeDataService tRegimeDataService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysDictDataController sysDictDataController;

    /* Generated Method*/
    @ApiOperation(value = "新增 制度资料管理", notes = "Add TRegimeData")
    @PostMapping(value = "/add")
    public BaseResponse<TRegimeData> addEntity(@RequestBody TRegimeData addRequest) throws Exception {
        return tRegimeDataService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取 制度资料管理 ", notes = "Get TRegimeData By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TRegimeData> getById(String id) throws Exception {
        return tRegimeDataService.getByIds(id);
    }

    @ApiOperation(value = "获取 发布单位下拉框 ", notes = "Get TRegimeData By Id")
    @GetMapping(value = "/getReleaseUnit")
    public BaseResponse<List<ReturnReleaseUnit>> getReleaseUnit(String level) throws Exception {
        return tRegimeDataService.getReleaseUnit(level);
    }

    @ApiOperation(value = "修改 制度资料管理 ", notes = "Update TRegimeData By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TRegimeData updateRequest) throws Exception {
        return tRegimeDataService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 制度资料管理 ", notes = "delete TRegimeData By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TRegimeDataDelParam deleteRequest) throws Exception {
        return tRegimeDataService.deleteEntity(deleteRequest);
    }

    //    @ApiOperation(value = "批量删除制度资料管理", notes = "delete TRegimeData by batch Id")
//    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TRegimeDataDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TRegimeData> tRegimeDataList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TRegimeData data = new TRegimeData();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tRegimeDataList.add(data);
            }
            boolean result = tRegimeDataService.updateBatchById(tRegimeDataList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 制度资料管理 分页列表", notes = "List TRegimeData with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<TRegimeData>> listEntity(@RequestBody TRegimeDataParam param) {
        BaseResponse<BaseResponseList<TRegimeData>> 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<TRegimeData> resultPage = new Page<>(page, limit);
        QueryWrapper<TRegimeData> queryWrapper = this.createQuery(param);
        Page<TRegimeData> resultList = tRegimeDataService.page(resultPage, queryWrapper);
        List<TRegimeData> records = resultList.getRecords();
        List<TRegimeData> tTrainDatabases = converDict(records);
        BaseResponseList<TRegimeData> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(tTrainDatabases);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }



    @ApiOperation(value = "分页列表-新", notes = "List TRegimeData with page")
    @PostMapping(value = "/pageList")
    public BaseResponse<BaseResponseList<TRegimeDataListVo>> pageList(@RequestBody TRegimeDataParam param) {
        BaseResponse<BaseResponseList<TRegimeDataListVo>> 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<TRegimeData> resultPage = new Page<>(page, limit);
        BaseResponseList<TRegimeDataListVo> baseResponseList = tRegimeDataService.pageList(resultPage, param);
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    /**
     * 转字典值
     *
     * @param baseResponseList
     * @return
     */
    private List<TRegimeData> converDict(List<TRegimeData> baseResponseList) {
        List<TRegimeData> data1 = new ArrayList<>();
        for (TRegimeData datum : baseResponseList) {
            TRegimeData tTrainDatabase = BeanHelper.beanToBean(datum, TRegimeData.class);
            String oneMaterialsType = tTrainDatabase.getOneMaterialsType();
            String senMaterialsType = tTrainDatabase.getSenMaterialsType();
            SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "MATERIALS", oneMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials2)) {
                String materials = materials2.getDictValue();
                tTrainDatabase.setOneMaterialsType(materials);
            }
            SysDictDataResponse materials3 = sysDictDataController.getDictTypeDetail("", "MATERIALS", senMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials3)) {
                String materials1 = materials3.getDictValue();
                tTrainDatabase.setSenMaterialsType(materials1);
            }
            data1.add(tTrainDatabase);
        }

        return data1;
    }

    //    @ApiOperation(value = "获取 制度资料管理 列表", notes = "List TRegimeData all")
//    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TRegimeData>> listAllEntity(TRegimeDataParam param) {
        BaseResponse<BaseResponseList<TRegimeData>> baseResponse = new BaseResponse<>();
        QueryWrapper<TRegimeData> queryWrapper = this.createQuery(param);
        List<TRegimeData> resultList = tRegimeDataService.list(queryWrapper);
        BaseResponseList<TRegimeData> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TRegimeData> createQuery(TRegimeDataParam queryParam) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        QueryWrapper<TRegimeData> queryWrapper = new QueryWrapper<>();
        //根据单位层级选择信息
        if (queryParam.getLevel() != null && StringUtils.isNotBlank(queryParam.getLevel().toString())) {
            String orgId = loginUser.getOrgId();
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            String treeLevel = one.getTreeLevel().toString();
            String level = queryParam.getLevel().toString();
            if ("1".equals(level)) {
                queryWrapper.eq(TRegimeData.RELEASE_UNIT, "中粮集团");
            }
            if ("2".equals(level)) {
                if ("1".equals(treeLevel)) {
                    queryWrapper.eq(TRegimeData.ORG_ID, one.getOrgId())
                            .ne(TRegimeData.RELEASE_UNIT, "中粮集团");
                }
                if ("2".equals(treeLevel)) {
                    String s = one.getParentIds().split(",")[1];
                    queryWrapper.eq(TRegimeData.ORG_ID, s)
                            .ne(TRegimeData.RELEASE_UNIT, "中粮集团");
                }
                if ("3".equals(treeLevel)) {
                    String s = one.getParentIds().split(",")[1];
                    queryWrapper.eq(TRegimeData.ORG_ID, s)
                            .ne(TRegimeData.RELEASE_UNIT, "中粮集团");
                }
            }
            if ("3".equals(level)) {
                if ("1".equals(treeLevel)) {
                    List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.TREE_LEVEL, "2"));
                    List<String> strings = new ArrayList<>();
                    for (SysOrg org : list) {
                        strings.add(org.getOrgId());
                    }
                    queryWrapper.in(TRegimeData.ORG_ID, strings);
                }
                if ("2".equals(treeLevel)) {
                    queryWrapper.eq(TRegimeData.ORG_ID, one.getOrgId());
                }
                if ("3".equals(treeLevel)) {
                    String s = one.getParentIds().split(",")[2];
                    queryWrapper.eq(TRegimeData.ORG_ID, s);
                }
            }
            if ("4".equals(level)) {
                if ("1".equals(treeLevel)) {
                    List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.TREE_LEVEL, "3"));
                    List<String> strings = new ArrayList<>();
                    for (SysOrg org : list) {
                        strings.add(org.getOrgId());
                    }
                    queryWrapper.in(TRegimeData.ORG_ID, strings);
                }
                if ("2".equals(treeLevel)) {
                    List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, one.getOrgId()));
                    List<String> strings = new ArrayList<>();
                    for (SysOrg org : list) {
                        strings.add(org.getOrgId());
                    }
                    queryWrapper.in(TRegimeData.ORG_ID, strings);
                }
                if ("3".equals(treeLevel)) {
                    queryWrapper.eq(TRegimeData.ORG_ID, one.getOrgId());
                }
            }
        }

        if (StringHelper.isNotEmpty(queryParam.getStartTime()) && StringHelper.isNotEmpty(queryParam.getEndTime())) {
            queryWrapper.between(TRegimeData.UPDATE_DATE, queryParam.getStartTime()+" 00:00:00", queryParam.getEndTime()+" 23:59:59");
        }
        if (StringHelper.isNotEmpty(queryParam.getReleaseUnit())) {
            String releaseUnit = queryParam.getReleaseUnit();
            List<String> list = Arrays.asList(releaseUnit.split(","));
            queryWrapper.in(TRegimeData.RELEASE_UNIT_ID, list);
        }
//        if (StringHelper.isNotEmpty(queryParam.getLevel().toString())) {
//            queryWrapper.eq(TRegimeData.LEVEL, queryParam.getLevel().toString());
//        }
        if (StringHelper.isNotEmpty(queryParam.getMaterialsName())) {
            queryWrapper.like(TRegimeData.MATERIALS_NAME, queryParam.getMaterialsName());
        }
        if (StringHelper.isNotEmpty(queryParam.getOneMaterialsType())) {
            queryWrapper.eq(TRegimeData.ONE_MATERIALS_TYPE, queryParam.getOneMaterialsType());
        }
        if (StringHelper.isNotEmpty(queryParam.getSenMaterialsType())) {
            queryWrapper.eq(TRegimeData.SEN_MATERIALS_TYPE, queryParam.getSenMaterialsType());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TRegimeData.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TRegimeData.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.orderByDesc(TRegimeData.UPDATE_DATE);
        }
        if (StringHelper.isNotEmpty(queryParam.getRegimeDataType())) {
            queryWrapper.eq(TRegimeData.REGIME_DATA_TYPE, queryParam.getRegimeDataType());
        }
        return queryWrapper;
    }
}
