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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jg.api.dto.JgUseRegistrationDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistration;
import com.yeejoin.amos.boot.module.jg.api.enums.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgUseRegistrationServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
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 io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
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 javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author system_generator
 * @date 2023-12-12
 */
@RestController
@Api(tags = "Api")
@RequestMapping(value = "/jg-use-registration")
public class JgUseRegistrationController extends BaseController {

    @Autowired
    JgUseRegistrationServiceImpl jgUseRegistrationServiceImpl;


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public ResponseModel<Object> save(@RequestBody JSONObject map) {
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.save(map));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/flowExecute")
    @ApiOperation(httpMethod = "POST", value = "执行流程", notes = "执行流程")
    public ResponseModel<Object> flowExecute(@RequestBody JSONObject map) {
        jgUseRegistrationServiceImpl.flowExecute(Long.valueOf(String.valueOf(map.get("sequenceNbr"))),
                String.valueOf(map.get("instanceId")),
                String.valueOf(map.get("operate")),
                String.valueOf(map.get("comment")),
                String.valueOf(map.getOrDefault("carNumber", "")),
                String.valueOf(map.getOrDefault("manageType", "")),
                String.valueOf(map.get("nextTaskId")));
        return ResponseHelper.buildResponse("ok");
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/withdraw")
    @ApiOperation(httpMethod = "POST", value = "撤回", notes = "撤回")
    public ResponseModel<Object> withdraw(@RequestBody JSONObject map) {
        jgUseRegistrationServiceImpl.withdraw(String.valueOf(map.get("instanceId")), String.valueOf(map.get("nextTaskId")),
                String.valueOf(map.getOrDefault("manageType", "")));
        return ResponseHelper.buildResponse("ok");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "POST", value = "批量删除", notes = "批量删除")
    public ResponseModel<Object> deleteBatch(@RequestBody JSONObject map) {
        List<Long> ids = (List<Long>) map.get("ids");
        jgUseRegistrationServiceImpl.deleteBatch(ids);
        return ResponseHelper.buildResponse("ok");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/deleteMessage")
    @ApiOperation(httpMethod = "POST", value = "删除", notes = "删除")
    public ResponseModel<Object> deleteMessage(@RequestParam("id") Long id) {
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        jgUseRegistrationServiceImpl.deleteBatch(ids);
        return ResponseHelper.buildResponse("ok");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/getList")
    public ResponseModel<Page<Map<String, Object>>> getList(JgUseRegistrationDto dto,
                                                            @ApiParam(value = "排序字段") @RequestParam(value = "sort", required = false) String sort,
                                                            @RequestParam(value = "current") int current,
                                                            @RequestParam(value = "size") int size) {
        Page<Map<String, Object>> page = new Page<>(current, size);
        ReginParams info = getSelectedOrgInfo();
        dto.setCurrentUserId(info.getUserModel().getUserId());
        if (info.getCompany().getLevel().equals(BaseController.COMPANY_TYPE_COMPANY)) {
            dto.setDataType(BaseController.COMPANY_TYPE_COMPANY);
            dto.setUnitCode(CompanyTypeEnum.INDIVIDUAL.getName().equals(info.getCompany().getCompanyType()) ?
                    info.getCompany().getCompanyCode().split("_")[1] : info.getCompany().getCompanyCode());
        } else {
            dto.setDataType(BaseController.COMPANY_TYPE_SUPERVISION);
            dto.setReceiveCompanyCode(info.getCompany().getCompanyCode());
        }
        Page<Map<String, Object>> list = jgUseRegistrationServiceImpl.getList(dto, sort, page, dto.getRoleIds());
        list.getRecords().forEach(x -> x.put("companyType", info.getCompany().getCompanyType()));
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/getEquipList")
    public ResponseModel<Page<Map<String, Object>>> getEquipList(
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size,
            @RequestParam(value = "factoryNum", required = false) String factoryNum,
            @RequestParam(value = "equList", required = false) String equList,
            @RequestParam(value = "equCategory", required = false) String equCategory) {
        Page<Map<String, Object>> page = new Page<>(current, size);
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.getEquipList(page, factoryNum, equList, equCategory));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    @GetMapping(value = "/getDetail")
    public ResponseModel<Map<String, Object>> getDetail(@RequestParam(value = "record", required = false) String record,
                                                        @RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr) {
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.getDetail(record, sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/getMessage")
    public ResponseModel<Map<String, Object>> getMessage() {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        HashMap<String, Object> map = new HashMap<>();
        String companyType = selectedOrgInfo.getCompany().getCompanyType();
        if ("个人主体".equals(companyType)) {
            String[] code = selectedOrgInfo.getCompany().getCompanyCode().split("_");
            map.put("useUnitCreditCode", code.length > 1 ? code[1] : code[0]);
            String[] companyName = selectedOrgInfo.getCompany().getCompanyName().split("_");
            map.put("useUnitName", companyName.length > 1 ? companyName[1] : companyName[0]);
        } else {
            map.put("useUnitCreditCode", selectedOrgInfo.getCompany().getCompanyCode());
            map.put("useUnitName", selectedOrgInfo.getCompany().getCompanyName());
        }
        return ResponseHelper.buildResponse(map);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询当前登录人角色", notes = "查询当前登录人角色")
    @GetMapping(value = "/getRole")
    public ResponseModel<Object> getRole() {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> userOrgRoleMap = FeignUtil.remoteCall(() -> Privilege.userOrgRoleClient.getme());
        List<String> userOrgRoleList = (List<String>) userOrgRoleMap.get("roleId");
        String roleIds = String.join(",", userOrgRoleList);
        map.put("roleIds", roleIds);
        return ResponseHelper.buildResponse(map);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/export")
    @ApiOperation(httpMethod = "GET", value = "导出使用登记证", notes = "导出使用登记证")
    public void exportImageZip(HttpServletResponse response, @RequestParam("sequenceNbr") String sequenceNbr,
                               @RequestParam(value = "printType", defaultValue = "0") String printType) {
        jgUseRegistrationServiceImpl.exportUseRegistrationCertificate(sequenceNbr, response, printType);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/summaryBasicInfo/export")
    @ApiOperation(httpMethod = "GET", value = "导出基本信息汇总表(工业管道/气瓶)", notes = "导出基本信息汇总表(工业管道/气瓶)")
    public void exportSummaryBasicInfo(HttpServletResponse response,
                                       @RequestParam("sequenceNbr") String sequenceNbr,
                                       @RequestParam("category") String category) {
        jgUseRegistrationServiceImpl.exportSummaryBasicInfo(sequenceNbr, response, category);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRegion")
    @ApiOperation(httpMethod = "GET", value = "", notes = "")
    public ResponseModel<Map<String, Object>> exportImageZip(@RequestParam("code") String code) {
        HashMap<String, Object> map = new HashMap<>();
        if (!ObjectUtils.isEmpty(code)) {
            String[] data = code.split("_");
            FeignClientResult<CompanyModel> result = Privilege.companyClient.queryByCompanyCode(data[0]);
            if (!ObjectUtils.isEmpty(result)) {
                CompanyModel result1 = result.getResult();
                if (!ObjectUtils.isEmpty(result1.getRegionSeq())) {
                    FeignClientResult<Collection<RegionModel>> region = Systemctl.regionClient.queryForParent(Long.valueOf(result1.getRegionSeq()));
                    Collection<RegionModel> result2 = region.getResult();
                    List<RegionModel> list = new ArrayList<>(Arrays.asList(result2.toArray(new RegionModel[0])));
                    RegionModel region1 = list.get(0);
                    changeData(map, region1);
                }
            }

        }
        return ResponseHelper.buildResponse(map);
    }


    private HashMap<String, Object> changeData(HashMap<String, Object> map, RegionModel regionModel) {
        if (!ObjectUtils.isEmpty(regionModel.getChildren())) {
            Collection<RegionModel> children = regionModel.getChildren();
            List<RegionModel> list = new ArrayList<>(Arrays.asList(children.toArray(new RegionModel[0])));
            RegionModel region = list.get(0);
            if (map.containsKey("region")) {
                map.put("region", String.valueOf(map.get("region")) + region.getRegionCode() + ",");
                map.put("regionAll", String.valueOf(map.get("regionAll")) + region.getRegionCode() + "_" + region.getRegionName() + ",");
            } else {
                map.put("regionAll", region.getRegionCode() + "_" + region.getRegionName() + ",");
                map.put("region", region.getRegionCode() + ",");
            }

            if (!ObjectUtils.isEmpty(region.getChildren())) {
                Collection<RegionModel> regionChildren = regionModel.getChildren();
                List<RegionModel> regionChildrenList = new ArrayList<>(Arrays.asList(regionChildren.toArray(new RegionModel[0])));
                changeData(map, regionChildrenList.get(0));
            }
        }

        return map;

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "使用登记单条作废", notes = "使用登记单条作废")
    @PutMapping(value = "/cancel/application")
    public ResponseModel<JgUseRegistration> cancelApplication(@RequestBody JgUseRegistrationDto jgUseRegistration) {
        JgUseRegistration result = jgUseRegistrationServiceImpl.cancelApplication(jgUseRegistration.getSequenceNbr(), jgUseRegistration.getCancelReason());
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/yunWei/yuLin")
    @ApiOperation(httpMethod = "POST", value = "榆林使用登记错误数据处理", notes = "榆林使用登记错误数据处理")
    public ResponseModel<Object> yunWeiRegistrationWrongData(@RequestBody List<String> applayNoList) {
        jgUseRegistrationServiceImpl.correctWrongData(applayNoList);
        return ResponseHelper.buildResponse("ok");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @GetMapping(value = "/useDate/handle")
    @ApiOperation(httpMethod = "GET", value = "使用登记单子中投用年月的数据处理", notes = "使用登记单子中投用年月的数据处理")
    public ResponseModel<Object> yunWeiRegistrationWrongData() {
        // 关联 任务 ： 26599 压力管道技术参数除起始位置、备注外均为必填，压力管道信息汇总表要求的字段在其余模块的都要求必填，压力管道信息汇总表也需要展示
        // http://113.142.68.105:5080/zentao/task-view-26599.html
        jgUseRegistrationServiceImpl.useDateHandler();
        return ResponseHelper.buildResponse("ok");
    }
}
