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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.boot.module.ymt.api.entity.IdxBizJgProjectContraption;
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.component.event.RestEventTrigger;
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 springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 = "新增")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    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 = "执行流程")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    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")), map);
        return ResponseHelper.buildResponse("ok");
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/withdraw")
    @ApiOperation(httpMethod = "POST", value = "使用登记撤回", notes = "撤回")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    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) {
        jgUseRegistrationServiceImpl.deleteBatch(Collections.singletonList(id));
        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());
            dto.setSupervisionOrgCode(info.getCompany().getOrgCode());
        }
        if (dto.getAuditPassDateRange() != null && !dto.getAuditPassDateRange().isEmpty() && !dto.getAuditPassDateRange().equals("[, ]")) {
            String dateRangeStr = dto.getAuditPassDateRange();
            String[] dates = dateRangeStr.replace("[", "").replace("]", "").split(", ");

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date start = null;
            Date end = null;
            try {
                start = dateFormat.parse(dates[0]);
                end = dateFormat.parse(dates[1]);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            start = calendar.getTime();
            dto.setAuditPassDateStart(start);
            dto.setAuditPassDateEnd(end);
        }
        Page<Map<String, Object>> list = jgUseRegistrationServiceImpl.getList(dto, sort, page, dto.getRoleIds());
        list.getRecords().forEach(x -> {
            x.put("companyType", info.getCompany().getCompanyType());
            x.put("regType", "1".equals(x.get("regType")) ? "历史登记": "2".equals(x.get("regType")) ? "特殊历史登记": "新增登记");
        });
        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 = "/getDetailByIdx")
    public ResponseModel<Map<String, Object>> getDetailByIdx(@RequestParam(value = "record") String record) {
        Map<String, Object> detailByIdx = jgUseRegistrationServiceImpl.getDetailByIdx(record);
        if(detailByIdx.get("equCode") != null && !detailByIdx.get("equCode").equals("")) {
            detailByIdx.put("equCodeCategory", 1);
        }else{
            detailByIdx.put("equCodeCategory", 0);
        }
        return ResponseHelper.buildResponse(detailByIdx);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/getMessage")
    public ResponseModel<Map<String, Object>> getMessage() {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.getUnitInfo(selectedOrgInfo));
    }


    @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(Collections.singletonList(Long.valueOf(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")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    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");
    }

    /**
     * 使用登记流程错误数据处理
     *
     * @param applyNo applyNo
     * @return s
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/yunWei/handleErrorForm")
    @ApiOperation(httpMethod = "POST", value = "使用登记流程错误数据处理", notes = "使用登记流程错误数据处理")
    public ResponseModel<Object> handleErrorForm(@RequestParam("applyNo") String applyNo) {
        jgUseRegistrationServiceImpl.handleErrorForm(applyNo);
        return ResponseHelper.buildResponse("申请单【" + applyNo + "】处理成功");
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/saveHistoryEquip")
    @ApiOperation(httpMethod = "POST", value = "新增历史设备登记", notes = "新增历史设备登记")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<Object> saveHistoryEquip(@RequestBody JSONObject map) {
        JSONObject firstMap = JSONObject.parseObject(JSONObject.toJSONString(map.get("first")));
        JSONObject secondMap = JSONObject.parseObject(JSONObject.toJSONString(map.get("second")));
        secondMap.put("type", firstMap.get("type"));
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.saveHistoryEquip(secondMap));
    }

    /**
     * 根据使用登记证查询工程装置名称
     *
     * @param useRegistrationCode 使用登记证
     * @return projectContraption
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/queryByRegistrationCode")
    @ApiOperation(httpMethod = "POST", value = "根据使用登记证查询工程装置名称", notes = "根据使用登记证查询工程装置名称")
    public ResponseModel<Object> queryByRegistrationCode(@RequestParam("useRegistrationCode") String useRegistrationCode) {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        String companyCode = selectedOrgInfo.getCompany().getCompanyCode();
        String companyType = selectedOrgInfo.getCompany().getCompanyType();
        String useUnitCreditCode = "个人主体".equals(companyType) && companyCode.contains("_") ? companyCode.split("_", 2)[1]
                : companyCode;
        HashMap<String, Object> map = new HashMap<>();
        map.put("useRegistrationCode", useRegistrationCode);
        map.put("useUnitCreditCode", useUnitCreditCode);
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.queryByRegistrationCode(map));
    }


    /**
     * 根据equCode更新气瓶分类历史数据
     * @param cylinderCategory  气瓶类别(0：液化石油气瓶、1：工业气瓶、2其他)
     * @param equCodeList 设备代码集合
     * @return o
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/updateCylinderCategory")
    @ApiOperation(httpMethod = "POST", value = "根据equCode更新气瓶分类历史数据", notes = "根据equCode更新气瓶分类历史数据")
    public ResponseModel<Object> handleErrorForm(@RequestParam("cylinderCategory") String cylinderCategory,
                                                 @RequestParam("equCodeList") List<String> equCodeList) {
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.updateCylinderCategoryByEquCodeBatch(cylinderCategory, equCodeList));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/jgProjectContraptionPage")
    @ApiOperation(value = "查询指定使用单位下的可用装置，已纳管且使用登记证编号为空或者null", notes = "不包括流程中的")
    public ResponseModel<IPage<IdxBizJgProjectContraption>> getJgProjectContraptionPage(@RequestParam String useUnitCreditCode,
                                                                                        @RequestParam(value = "current") int current,
                                                                                        @RequestParam(value = "size") int size) {
        Page<IdxBizJgProjectContraption> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        IPage<IdxBizJgProjectContraption> re = jgUseRegistrationServiceImpl.getJgProjectContraptionPage(useUnitCreditCode, page);
        return ResponseHelper.buildResponse(re);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询工程装置下的所有做过安装告知但是为做使用登记的管道", notes = "查询工程装置下的所有做过安装告知但是为做使用登记的管道")
    @GetMapping(value = "/getDeviceListByProjectContraptionSeq")
    public ResponseModel<Object> getDeviceListByProjectContraption(@RequestParam("record") String projectContraptionSeq) {
        return ResponseHelper.buildResponse(jgUseRegistrationServiceImpl.getDeviceListByProjectContraption(projectContraptionSeq));
    }

}
