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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProcessTypeEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.PipeDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.Pipe;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectInitiation;
import com.yeejoin.amos.boot.module.ugp.api.service.IPipeService;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.IPipeServiceImpl;
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.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "管段信息Api")
@RequestMapping(value = "/pipe")
public class PipeController extends BaseController {

    @Autowired
    IPipeServiceImpl pipeServiceImpl;

    @Autowired
    IPipeService pipeService;
    @Autowired
    private RedisUtils redisUtils;

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增管段信息", notes = "新增管段信息")
    public ResponseModel<List<PipeDto>> save(@RequestBody List<PipeDto> list,
                                             @RequestParam(value = "projectId") Long projectId) {
        List<PipeDto> result = new ArrayList<>();
        list.forEach(item -> {
            item.setProjectId(projectId);
            PipeDto withModel = pipeServiceImpl.createWithModel(item);
            result.add(withModel);
        });

        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据管段id查询管段信息", notes = "根据管段id查询管段信息")
    public ResponseModel<String> getMessage(@PathVariable Long sequenceNbr) {
        LambdaQueryWrapper<Pipe> lambda = new QueryWrapper<Pipe>().lambda();
        lambda.eq(Pipe::getProjectId, sequenceNbr);
        List<Pipe> pipes = pipeServiceImpl.lambdaQuery().getBaseMapper().selectList(lambda);
        String jArr = JSON.toJSONString(pipes);
        return ResponseHelper.buildResponse(jArr);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/addPipeMessage")
    @ApiOperation(httpMethod = "POST", value = "新增管段信息-json", notes = "新增管段信息-json")
    public ResponseModel<Object> save(@RequestParam(value = "json") String json,
                                      @RequestParam(value = "projectId") Long projectId) {
        pipeService.addPipeMessage(json, projectId);
        return ResponseHelper.buildResponse(json);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCompanyMessage")
    @ApiOperation(httpMethod = "GET", value = "查询当前人所有单位-下拉选择", notes = "查询当前人所有单位")
    public ResponseModel<Object> getCompanyMessage() {
        List<Map<String, Object>> list = new ArrayList<>();
        String exeUserId = RequestContext.getExeUserId();
        FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient.queryByUserId(exeUserId);
        if (!ObjectUtils.isEmpty(agencyUserModelFeignClientResult) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult()) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult().getCompanys())) {
            List<CompanyModel> companies = agencyUserModelFeignClientResult.getResult().getCompanys();
            companies.forEach(item -> {
                HashMap<String, Object> result = new HashMap<>();
                result.put("name", item.getCompanyName());
                result.put("value", item.getSequenceNbr());
                list.add(result);
            });
            return ResponseHelper.buildResponse(list);
        } else {
            return ResponseHelper.buildResponse(null);

        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRoles")
    @ApiOperation(httpMethod = "GET", value = "查询当前人某单位下角色-下拉选择", notes = "查询当前人某单位下角色")
    public ResponseModel<Object> getRoles(@RequestParam Long companyId) {
        String exeUserId = RequestContext.getExeUserId();
        FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient.queryByUserId(exeUserId);
        if (!ObjectUtils.isEmpty(agencyUserModelFeignClientResult) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult()) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult().getOrgRoles())) {
            Map<Long, List<RoleModel>> orgRoles = agencyUserModelFeignClientResult.getResult().getOrgRoles();
            if (!ObjectUtils.isEmpty(orgRoles)) {
                List<RoleModel> roleModels = orgRoles.get(companyId);
                return ResponseHelper.buildResponse(roleModels);
            }
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/changeUserMessage")
    @ApiOperation(httpMethod = "POST", value = "跳转选择公司、角色后修改用户登录缓存西信息", notes = "跳转选择公司、角色后修改用户登录缓存西信息")
    public ResponseModel<Object> changeUserMessage(@RequestParam(value = "companyId") String companyId,
                                                   @RequestParam(value = "roleId") String roleId) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (!ObjectUtils.isEmpty(reginParams) && !ObjectUtils.isEmpty(reginParams.getCompany())) {
           // 所选公司覆盖
            CompanyBo company = reginParams.getCompany();
            company.setSequenceNbr(Long.valueOf(companyId));
            reginParams.setCompany(company);
            // 所选角色覆盖
            RoleBo role = reginParams.getRole();
            FeignClientResult<RoleModel> roleModelFeignClientResult = Privilege.roleClient.seleteOne(Long.valueOf(roleId));
            role.setRoleName(roleModelFeignClientResult.getResult().getRoleName());
            role.setRoleType(roleModelFeignClientResult.getResult().getRoleType());
            role.setSequenceNbr(Long.valueOf(roleId));
            reginParams.setRole(role);
            String result = JSON.toJSONString(reginParams);
            redisUtils.set(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()), result);
            return ResponseHelper.buildResponse(company);
        } else {
            return ResponseHelper.buildResponse(null);
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUsed")
    @ApiOperation(httpMethod = "GET", value = "常用功能", notes = "常用功能")
    public ResponseModel<Object> getUsed() {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String roleName = reginParams.getRole().getRoleName();
        String key = "_commonly_used";
        HashMap<String, Object> resultData = new HashMap<>();
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        FeignClientResult<List<DictionarieValueModel>> commonlyUsed = Systemctl.dictionarieClient.dictValues(roleName + key);
        List<DictionarieValueModel> result = commonlyUsed.getResult();
        result.forEach(item -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", item.getDictDataKey());
            map.put("url", item.getDictDataValue());
            map.put("img", item.getDictDataDesc());
            maps.add(map);
        });
        resultData.put("current", 1);
        resultData.put("total", maps.size());
        resultData.put("records", maps);
        return ResponseHelper.buildResponse(resultData);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getOperationalLogs")
    @ApiOperation(httpMethod = "GET", value = "通用流程操作日志查询", notes = "通用流程操作日志查询")
    public ResponseModel<Object> getOperationalLogs(@RequestParam("instanceId") String instanceId,
                                                    @RequestParam("current") int current,
                                                    @RequestParam("size") int size) {
        Page<Map<String, Object>> mapPage = new Page(current, size);
        Page<Map<String, Object>> operationalLogs = pipeService.getOperationalLogs(mapPage, instanceId);
        return ResponseHelper.buildResponse(operationalLogs);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getFlowChart")
    @ApiOperation(httpMethod = "GET", value = "通用流程操作日志查询", notes = "通用流程操作日志查询")
    public ResponseModel<Object> getFlowChart(@RequestParam("sequenceNbr") Long sequenceNbr) {

        return ResponseHelper.buildResponse("https://img0.baidu.com/it/u=887570163,3972811143&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500");
    }

}

