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

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.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.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.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.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.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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

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

    @Autowired
    ITzBaseEnterpriseInfoService iTzBaseEnterpriseInfoService;

    @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,
                                                              TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto) {
        return ResponseHelper.buildResponse(iTzBaseEnterpriseInfoService.page(pageParam, tzBaseEnterpriseInfoDto));
    }


    @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)
    @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));
    }

    @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));
    }
}
