package com.yeejoin.amos.boot.module.cylinder.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.cylinder.api.entity.TzsCitInfo;
import com.yeejoin.amos.boot.module.cylinder.api.service.TzsAuthService;
import com.yeejoin.amos.boot.module.cylinder.biz.service.impl.TzsCitInfoServiceImpl;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.NewRegionModel;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.util.*;

/**
 * 特种设备权限controller
 */
@RestController
@Api(tags = "特种设备权限Api")
@RequestMapping(value = "/tzs-auth-api")
public class TzsAuthController extends BaseController {

    @Value("${tzs.auth.user.photo}")
    String userPhoto;

    @Autowired
    TzsAuthService tzsAuthService;

    @Autowired
    TzsCitInfoServiceImpl citInfoService;

    /**
     * 判断用户是否是管理员
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/isUserAdmin")
    @ApiOperation(httpMethod = "GET", value = "判断用户是否是管理员", notes = "判断用户是否是管理员")
    public ResponseModel<Boolean> isUserAdmin() {
        Boolean flag = false;
        AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
        LambdaQueryWrapper<TzsCitInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TzsCitInfo::getCtiUserId, me.getUserId());
        TzsCitInfo ctiInfo = citInfoService.getOne(wrapper);
        if (!ValidationUtil.isEmpty(ctiInfo)) {
            if ("班长".equals(ctiInfo.getUserRole())) {
                flag = true;
            }
        }
        return ResponseHelper.buildResponse(flag);
    }

    /**
     * 获取用户regionCode
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserRegincode")
    @ApiOperation(httpMethod = "GET", value = "获取用户regionCode", notes = "获取用户regionCode")
    public ResponseModel<List<String>> getUserRegincode() {
        List<String> regionList = tzsAuthService.getUserRegionCode();
        AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
        return ResponseHelper.buildResponse(regionList);
    }

    /**
     * 获取用户组织机构树
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserReginTree")
    @ApiOperation(httpMethod = "GET", value = "获取用户组织机构树", notes = "获取用户组织机构树")
    public ResponseModel<Collection<RegionModel>> getUserReginTree() {
        List<RegionModel> result = tzsAuthService.getUserReginTree();
        return ResponseHelper.buildResponse(result);
    }

    /**
     * 获取三级组织机构树
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getThreeUserReginTree")
    @ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
    public ResponseModel<Collection<NewRegionModel>> getRegionTree(@RequestParam(value = "parentId",required = false) Long parentId) {
        return ResponseHelper.buildResponse(thirdLevelRegion(Systemctl.regionClient.queryForTree(null).getResult()));
    }

    /**
     * 去区域树中level多余空格以及保留三级
     * @param result
     */
    public List<NewRegionModel> thirdLevelRegion(Collection<RegionModel> result) {
        List<NewRegionModel> newRegionList = new ArrayList<>();

        for (RegionModel regionModel : result) {
            if (!"4".equals(regionModel.getLevel())) {
                NewRegionModel newRegion = new NewRegionModel();
                newRegion.setRegionCode(regionModel.getRegionCode());
                newRegion.setRegionName(regionModel.getRegionName().trim());
                newRegion.setLabel(regionModel.getRegionName().trim());
                newRegion.setValue(regionModel.getRegionCode());
                newRegion.setLevel(regionModel.getLevel().trim());
                if (!ValidationUtil.isEmpty(regionModel.getChildren())) {
                    newRegion.setChildren(thirdLevelRegion(regionModel.getChildren()));
                }
                newRegionList.add(newRegion);
            }
        }
        return newRegionList;
    }


    /**
     * 获取用户监管机构
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserRegulator")
    @ApiOperation(httpMethod = "GET", value = "获取用户组织机构树", notes = "获取用户组织机构树")
    public ResponseModel<Map<String, Object>> getUserRegulator() {
        Map<String, Object> map = new HashMap<>();
        FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient.getme();
        if (result.getResult() != null) {
            List<CompanyModel> list = result.getResult().getCompanys();
            if (list != null && !list.isEmpty()) {
                CompanyModel company = list.get(0);
                if ("company".equals(company.getLevel())) {
                    FeignClientResult<CompanyModel> cResult = Privilege.companyClient.seleteOne(company.getParentId());
                    if (cResult.getResult() != null) {
                        map.put("regulator", cResult.getResult().getCompanyName());
                    }
                    map.put("orgCode", cResult.getResult().getOrgCode() + "_" + cResult.getResult().getCompanyName());
                } else {
                    map.put("regulator", company.getCompanyName());
                    map.put("orgCode", list.get(0).getOrgCode() + "_" + list.get(0).getCompanyName());
                }
                map.put("company", company.getCompanyName());
                map.put("companyId", company.getParentId() != 0L ? company.getParentId() : company.getSequenceNbr());
                map.put("USE_UNIT_NAME", list.get(0).getCompanyName());
                map.put("USE_UNIT_CREDIT_CODE", list.get(0).getCompanyCode());
            }
            map.put("userName", result.getResult().getRealName());
            map.put("userPhoto", userPhoto);
        }
        return ResponseHelper.buildResponse(map);
    }
}
