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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.yeejoin.amos.boot.biz.common.annotation.RequireUserDetails;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tcm.api.dto.EquEnterDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzIndividualityDto;
import com.yeejoin.amos.boot.module.tcm.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.tcm.api.entity.PageParam;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tcm.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.EnterpriseManageServiceImpl;
import com.yeejoin.amos.boot.module.tcm.biz.utils.JsonUtils;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.component.event.RestEventTrigger;
import org.typroject.tyboot.core.foundation.context.RequestContext;
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.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 企业数据信息
 *
 * @author duanwei
 * @date 2022-08-10
 */
@RestController
@Api(tags = "企业数据信息Api")
@RequestMapping(value = "/baseEnterprise", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TzBaseEnterpriseInfoController extends BaseController {

    @Autowired
    ITzBaseEnterpriseInfoService iTzBaseEnterpriseInfoService;

    @Autowired
    EnterpriseManageServiceImpl enterpriseManageService;

    @Autowired
    RedisUtils redisUtils;

    @Value("classpath:/json/equipCategory.json")
    private Resource equipCategory;

    @Autowired
    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    /**
     * 新增企业数据信息
     *
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增企业数据信息", notes = "新增企业数据信息")
    public boolean saveTzBaseEnterpriseInfo(HttpServletRequest request,
                                            @RequestBody TzBaseEnterpriseInfo tzBaseEnterpriseInfo) {
        return iTzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(HttpServletRequest request, @PathVariable Long id) {
        return iTzBaseEnterpriseInfoService.removeById(id);
    }

    /**
     * 修改企业数据信息
     *
     * @return
     */
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改企业数据信息", notes = "修改企业数据信息")
    public boolean updateByIdTzBaseEnterpriseInfo(HttpServletRequest request,
                                                  @RequestBody TzBaseEnterpriseInfo tzBaseEnterpriseInfo) {
        return iTzBaseEnterpriseInfoService.updateById(tzBaseEnterpriseInfo);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<TzBaseEnterpriseInfoDto> selectById(HttpServletRequest request, @PathVariable Long id) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.detail(id));
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<TzBaseEnterpriseInfo>> listPage(String pageNum, String pageSize,
                                                               TzBaseEnterpriseInfo tzBaseEnterpriseInfo) {

        Page<TzBaseEnterpriseInfo> pageBean;
        QueryWrapper<TzBaseEnterpriseInfo> tzBaseEnterpriseInfoQueryWrapper = new QueryWrapper<>();
        Class<? extends TzBaseEnterpriseInfo> aClass = tzBaseEnterpriseInfo.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(tzBaseEnterpriseInfo);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(tzBaseEnterpriseInfo);
                        tzBaseEnterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(tzBaseEnterpriseInfo);
                        tzBaseEnterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(tzBaseEnterpriseInfo);
                        tzBaseEnterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(tzBaseEnterpriseInfo);
                        tzBaseEnterpriseInfoQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
            }
        });
        IPage<TzBaseEnterpriseInfo> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {

            pageBean = new Page<>(0, Integer.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iTzBaseEnterpriseInfoService.page(pageBean, tzBaseEnterpriseInfoQueryWrapper);
        return ResponseHelper.buildResponse(page);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getEquInfo/{sequenceNbr}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "通过企业id查询设备", notes = "通过企业id查询设备")
    public ResponseModel<List<EquEnterDto>> getInfo(@PathVariable(value = "sequenceNbr") String sequenceNbr) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getInfo(sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getEquInfoByUseUnit", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "通过企业名称查询设备", notes = "通过企业名称查询设备")
    public ResponseModel<List<EquEnterDto>> getInfoByUseUnit(String useUnit) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getInfoByUseUnit(useUnit));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<IPage<TzBaseEnterpriseInfoDto>> page(PageParam pageParam, @RequestParam(value = "sort", required = false) String sort, TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.page(pageParam, tzBaseEnterpriseInfoDto, sort));
    }

    /**
     * 分页查询企业信息 从jczs迁移过来
     *
     * @param pageParam
     * @param sort
     * @param map
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getPageList", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页查询企业信息", notes = "分页查询企业信息")
    public ResponseModel<IPage<TzBaseEnterpriseInfoDto>> getPageList(PageParam pageParam, @RequestParam(value = "sort", required = false) String sort, @RequestParam Map<String, Object> map) {
        TzBaseEnterpriseInfoDto dto = JSON.parseObject(JSON.toJSONString(map), TzBaseEnterpriseInfoDto.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!ValidationUtil.isEmpty(map.get("createDateRange"))) {
            String createDateRangeObj = Objects.toString(map.get("createDateRange"));
            String[] split = createDateRangeObj.replace("[", "").replace("]", "").split(",");
            String startDateStr = split[0];
            String endDateStr = split[1];
            try {
                Date startDate = sdf.parse(startDateStr);
                Date endDate = sdf.parse(endDateStr);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                endDate = calendar.getTime();
                dto.setCreateDateStart(startDate);
                dto.setCreateDateEnd(endDate);
            } catch (Exception e) {
            }
        }
        // 处理监管标签列表
        Optional.ofNullable(map.get("regulatoryLabelList"))
                .map(Object::toString)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(com.yeejoin.amos.boot.module.tcm.biz.utils.StringUtils::splitAndClean)
                .filter(list -> !list.isEmpty())
                .ifPresent(dto::setRegulatoryLabelList);

        // 处理单位类型列表：优先使用 JgUnitTypeList，没有则使用 unitTypeList
        List<String> unitTypeList = Optional.ofNullable(map.get("JgUnitTypeList"))
                .map(Object::toString)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(com.yeejoin.amos.boot.module.tcm.biz.utils.StringUtils::splitAndClean)
                .orElseGet(() -> Optional.ofNullable(map.get("unitTypeList"))
                        .map(Object::toString)
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(com.yeejoin.amos.boot.module.tcm.biz.utils.StringUtils::splitAndClean)
                        .orElse(Collections.emptyList())
                );
        dto.setUnitTypeList(unitTypeList);
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.page(pageParam, dto, sort));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/info")
    @ApiOperation(httpMethod = "GET", value = "查询企业端当前登录人所在企业详情", notes = "查询企业端当前登录人所在企业详情")
    public ResponseModel<IPage<TzBaseEnterpriseInfoDto>> pageInfo(PageParam pageParam) {
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.page(pageParam, companyModels.get(0).getCompanyCode()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getInfoByUseCode", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据统一信用代码查询企业详情", notes = "根据统一信用代码查询企业详情")
    public ResponseModel<TzBaseEnterpriseInfoDto> getInfoByUseCode(String useCode) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getInfoByUseCode(useCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getInfoByUseCode/map", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据统一信用代码查询企业详情返回map", notes = "根据统一信用代码查询企业详情返回map")
    public ResponseModel<Map<String, Object>> getInfoByUseCodeMap(String useCode) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getInfoByUseCodeMap(useCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getInfoByUseCodeList", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据统一信用代码查询企业详情", notes = "根据统一信用代码查询企业详情")
    public ResponseModel<IPage<TzBaseEnterpriseInfoDto>> getInfoByUseCodeList(String useCode) {
        Page<TzBaseEnterpriseInfoDto> page = new Page<>();
        page.setRecords((Collections.singletonList(iTzBaseEnterpriseInfoService.getInfoByUseCode(useCode))));
        return ResponseHelper.buildResponse(page);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyInfoUpdate", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "修改企业信息", notes = "修改企业信息")
    public ResponseModel<TzBaseEnterpriseInfoDto> companyInfoUpdate(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.companyInfoUpdate(map, getSelectedOrgInfo()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/adminInfoUpdate", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "修改企业信息", notes = "修改企业信息")
    public ResponseModel<Object> adminInfoUpdate(@RequestBody Map<String, Object> map) {
        Map<String, Object> result = iTzBaseEnterpriseInfoService.adminInfoUpdate(map);
        return ResponseHelper.buildResponse(result);
    }

    /**
     * 根据企业名称查询企业详情
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据企业名称查询", notes = "根据企业名称查询")
    public ResponseModel<TzBaseEnterpriseInfoDto> selectByUseUnit(HttpServletRequest request, String useUnit) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.selectByUseUnit(useUnit));
    }

    /**
     * 将监管系统全量用户导入 业务企业表 和 平台企业表
     *
     * @return OK
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/syncUnitData", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "同步企业信息", notes = "同步企业信息")
    public ResponseModel<String> syncUnitData() {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.syncEnterpriseInfo());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/setLabel", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "设置企业标签", notes = "设置企业标签")
    public ResponseModel<Object> setLabel(@RequestBody Map<String, Object> map) {

        ArrayList<String> enterpriseLabel = new ArrayList<>();
        ArrayList<Long> enterpriseIds = (ArrayList) map.get("enterpriseIds");
        if (!ObjectUtils.isEmpty(map) && !ObjectUtils.isEmpty(map.get("enterpriseLabel")) && !ObjectUtils.isEmpty(map.get("enterpriseIds"))) {
            enterpriseLabel = (ArrayList) map.get("enterpriseLabel");
        }
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.setLabel(enterpriseIds, enterpriseLabel));

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getEnterpriseType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "同步企业信息", notes = "同步企业信息")
    public ResponseModel<List<Map<String, Object>>> getEnterpriseType() {
        return ResponseHelper.buildResponse(tzBaseEnterpriseInfoMapper.getEquipType("UNIT_TYPE_NEW"));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getEquipType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "同步企业信息", notes = "同步企业信息")
    public ResponseModel<List<Map<String, Object>>> getEquipType() {
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        return ResponseHelper.buildResponse(resourceJson.get(EquipmentClassifityEnum.BDLS.getCode()));
    }

    /**
     * 监管对接
     *
     * @param unitCode
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getUnitLicenceMessage", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据统一信用代码查询许可信息", notes = "根据统一信用代码查询许可信息")
    public ResponseModel<BaseUnitLicence> getUnitLicenceMessage(@RequestParam("unitCode") String unitCode) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getUnitLicenceMessage(unitCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getInfoById")
    @ApiOperation(httpMethod = "GET", value = "根据ID查询企业详情", notes = "根据ID查询企业详情")
    public ResponseModel<IPage<TzBaseEnterpriseInfoDto>> infoById(Long sequenceNbr, String companyCode) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getInfoById(sequenceNbr, companyCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyInfoUpdateById", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "根据ID修改企业信息-监管单位使用", notes = "根据ID修改企业信息-监管单位使用")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    @RequireUserDetails
    public ResponseModel<TzBaseEnterpriseInfoDto> companyInfoUpdateById(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.updateCompanyInfoById(map, getSelectedOrgInfo()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/personalInfoUpdateById", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "根据ID修改企业信息", notes = "根据ID修改企业信息")
    public ResponseModel<TzIndividualityDto> personalInfoUpdateById(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.personalInfoUpdateById(map));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "DELETE", value = "批量删除企业", notes = "批量删除企业")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    @RequireUserDetails
    public ResponseModel<List<TzBaseEnterpriseInfo>> deleteBatch(@RequestParam String ids) {
        return ResponseHelper.buildResponse(enterpriseManageService.delete(Arrays.asList(ids.split(","))));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/enableBatch")
    @ApiOperation(httpMethod = "PUT", value = "企业启用", notes = "企业启用")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    @RequireUserDetails
    public ResponseModel<ReginParams> enableBatch(@RequestParam String ids, @RequestBody(required = false) Map<String, Object> params) {
        return ResponseHelper.buildResponse(enterpriseManageService.enable(Arrays.asList(ids.split(",")), new JSONObject(Optional.ofNullable(params).orElse(new JSONObject())), getSelectedOrgInfo()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/disableBatch")
    @ApiOperation(httpMethod = "PUT", value = "企业停用", notes = "企业停用")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    @RequireUserDetails
    public ResponseModel<ReginParams> disableBatch(@RequestParam String ids, @RequestBody(required = false) Map<String, Object> params) {
        JSONObject psJson = new JSONObject(params);
        if(StringUtils.isBlank(psJson.getString("reason"))){
            throw new BadRequest("停用原因不能为空!");
        }
        return ResponseHelper.buildResponse(enterpriseManageService.disable(Arrays.asList(ids.split(",")), psJson, getSelectedOrgInfo()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getListByIds", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据统一信用代码查询企业详情返回map", notes = "根据统一信用代码查询企业详情返回map")
    public ResponseModel<List<Map<String, String>>> getListByIds(@RequestParam List<Long> ids) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.getListByIds(ids));
    }
}
